0

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?

Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155
Hraaig
  • 51
  • 5
  • 4
    [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 24 '16 at 18:14

1 Answers1

0

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'){

Mikey
  • 6,432
  • 4
  • 20
  • 36
  • thanks a lot. but now i get a parser error: unexpected end of json input. – Hraaig May 24 '16 at 21:10
  • That usually means that you are not sending back a valid JSON string. Open your network tab in your browser's developer tool, look under XHR, and check the response. If you get back a JSON string, put it through a [validator](http://jsonlint.com/) to see where the problem is. You might not be sending back a JSON string at all as you are not entering the third `if` statement as explained in my edit. – Mikey Jun 03 '16 at 13:18