简体   繁体   中英

Communication between JavaScript, PHP and MySQL

I'm trying to learn JavaScript to code for Cordova. I read many tutorials, but none of them helped me with the folowing problem.

My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.

Here is my

<?PHP
$response = array();

require_once __DIR__ . '/db_config.php';

$db_link = mysqli_connect (
                 DB_SERVER, 
                 DB_USER, 
                 DB_PASSWORD, 
                 DB_DATABASE
                );
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
    die ('keine Verbindung '.mysqli_error());
}

if(isset($_POST['action']) && $_POST['action'] == 'insert'){
    $name = $_POST['name'];
    $sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
    $db_erg = mysqli_query($db_link, $sql);
    if (!$db_erg){
        echo "error";
    }else{
        echo "ok";
    }
}

if(isset($_POST['action']) && $_POST['action']=='read'){
    $sql = "SELECT * FROM testTable";

    $db_erg = mysqli_query( $db_link, $sql );
    if (!$db_erg )
    {
        $response["success"] = 0;
        $response["message"] = "Oops!";
        echo json_encode($response);
        die('Ungültige Abfrage: ' . mysqli_error());
    }

    while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
    {
        //$response["success"] = $zeile['pid'];
        //$response["message"] = $zeile['name'];
        $response[]=$zeile;
    }
    echo json_encode($response);
    mysqli_free_result( $db_erg );
}
?>

and here are my 2 functions in the cordova app:

function getNameFromServer() {
    var url = "appcon.php";
    var action = 'read';
    $.getJSON(url, function (returnedData) {
        $.each(returnedData, function (key, value) {
            var id = value.pid;
            var name = value.name;
            $("#listview").append("<li>" + id + " - " + name) + "</li>";
        });
    });            
}

function sendNameToServer() {
    console.log("sendNameToServer aufgerufen");
    var url2send = "appcon.php";
    var name = $("#Name").val()
    var dataString = name;
    console.log(dataString);
    if ($.trim(name).length>0) {
        $.ajax({
            type: "POST",
            url: url2send,
            data: { action: 'insert', name: dataString },
            crossDomain: true,
            cache: false,
            beforeSend: function () {
                console.log("sendNameToServer beforeSend wurde aufgerufen");
            },
            success: function (data) {
                if (data == "ok") {
                    alert("Daten eingefuegt");
                }
                if (data == "error") {
                    alert("Da ging was schief");
                }
            }
        });
    }        
}

My Questions/Problems:

  1. The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).

  2. How can I pass "action = read" to the PHP script in the getNameFromServer() function?

The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?

Here is one part answer to your question.

$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.

function getNameFromServer() {
    $.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
        $.each(returnedData, function (key, value) {
            var id = value.pid;
            var name = value.name;
            $("#listview").append("<li>" + id + " - " + name) + "</li>";
        });
    });            
}

Edit: Since you are using $.getJSON() , the request method is a GET , which means you have to use $_GET in your third if statement in your PHP script.

if(isset($_GET['action']) && $_GET['action'] == 'read'){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM