1

I am trying to post 4 variables to a database on an external server using a mobile application created using Cordova 4.0.0.

I have already had a look a countless posts similar to this trying, POST, GET, contentType etc. and none of these seem to work. I have worked with JSONP before and it worked fine (I used that code as a template), but this doesn't seem to work.

Here is the console log:

2015-01-30 09:19:09.817 Alert[1253:353531] {"readyState":4,"status":200,"statusText":"load"}
2015-01-30 09:19:09.817 Alert[1253:353531] parsererror
2015-01-30 09:19:09.817 Alert[1253:353531] {"line":2,"column":2097,"sourceURL":"file:///private/var/mobile/Containers/Bundle/Application/D1746CD9-C9B3-4A31-9965-E4A6AAED3347/Alert.app/www/js/jquery-2.1.3.min.js"}

Here is my AJAX Post request.

function pushToDataLog(beaconid, uuid, timestamp, status)
{
    jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "http://url.co.uk/ips/pushdata.php", //Where to make Ajax calls
        dataType:"jsonp", // Data type, HTML, json etc.
        jsonp: "callback",
        data : {beaconid: beaconid, uuid: uuid, timestamp: timestamp, status:status},
        crossDomain: true,
        contentType: 'application/json',
        success:function(response){
            //console.log(JSON.stringify(response));
        },
        error:function (xhr, ajaxOptions, thrownError){
            console.log(xhr);
            console.log(ajaxOptions);
            console.log(thrownError);
        }
    });
}

I dont understand what is causing the parse error..

EDIT

Here is my PHP file stored on the server:

<?php

if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {


$beaconid = NULL;
$entertimestamp= NULL;
$exittimestamp = NULL;

//GET THE VARIABLES FROM JAVASCRIPT
if(isset($_REQUEST['beaconid'])){
    $beaconid = $_REQUEST['beaconid'];
}
if(isset($_REQUEST['uuid'])){
    $uuid = $_REQUEST['uuid'];
}
if(isset($_REQUEST['timestamp'])){
    $timestamp = $_REQUEST['timestamp'];
}
if(isset($_REQUEST['status'])){
    $status = $_REQUEST['status'];
}

define('DB_SERVER', 'a');
define('DB_USER', 'a');
define('DB_PASSWORD', 'a');
define('DB_DATABASE', 'a');

$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

if (!$mysqli) {
    trigger_error('mysqli Connection failed! ' . htmlspecialchars(mysqli_connect_error()), E_USER_ERROR);
}else{
    print '<p>Database Connected!</p>';
}

//if( isset($name) && $name != '' ){

    $stmt = $mysqli->prepare("INSERT INTO a(BeaconID,UUID,Timestamp,Status) VALUES (?, ?, ?, ?)");

    if ($stmt === false) {
        trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
    }

    $bind = mysqli_stmt_bind_param($stmt, "isii", $beaconid, $uuid, $timestamp, $status);

    if ($bind === false) {
        trigger_error('Bind param failed!', E_USER_ERROR);
    }

    $exec = mysqli_stmt_execute($stmt);

    if ($exec === false) {
        trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR); 
    }

    printf ("New Record has id %d.\n", mysqli_insert_id($mysqli));

    //CLOSE THE SQL QUERY/STATEMENT
    mysqli_stmt_close($stmt);

    $json = json_encode("Success");
    echo $_GET['callback'].'('.$json.')';

//}

mysqli_close($mysqli);

}
?>
smj2393
  • 1,929
  • 1
  • 23
  • 50
  • Please take a look a this: http://stackoverflow.com/questions/5359224/parsererror-after-jquery-ajax-request-with-jsonp-content-type , it seems you are experiencing the same issue. Are you returning the value correctly? – briosheje Jan 30 '15 at 09:45
  • I had a look at that previously. Do you mean on from the PHP file? – smj2393 Jan 30 '15 at 09:49
  • Exactly. Also, are you forced to use jsonp? – briosheje Jan 30 '15 at 09:51
  • I have edited the question to show my PHP file on the server. No I am not, but I thought this was required with CrossDomain? – smj2393 Jan 30 '15 at 09:53
  • 1
    Well, at this point I'm not really sure how to move on since I'm not really expert with jsonp. What I would personally try is: 1) removing the prints. 2) instead of json_encode("seccess") I would try json_encode(array("res" => "success")); Not sure that these will fix, but you still can try them if you want to :P In any case, I've personally NEVER returned a single string using json_encode, I usually always return an array (which is then converted into a JSON object by PHP and read as a JSON object from javascript on the client side). – briosheje Jan 30 '15 at 09:59
  • wait wait wait wait.. does json_encode accept a string as a parameter..? http://php.net/manual/en/function.json-encode.php Just checking, lol. – briosheje Jan 30 '15 at 10:02
  • I have just tested the PHP outside the app and it submits data to the server fine. Adding in json_encode(array("res" => "success")); outputs the syntax error "unexpected token :" {"res":"successs"} – smj2393 Jan 30 '15 at 10:35

1 Answers1

0

With the help of @briosheje I managed to solve this issue. In case anyone has a similar problem in the future here is how I solved it:

The problem AJAX request was fine, the issue was in the PHP file on the server. To solve this I sent a json encoded array back containing success / failure messages.

Here is the full php file:

<?php

    $beaconid = NULL;
    $uuid = NULL;
    $timestamp = NULL;
    $status = NULL;

    //GET THE VARIABLES FROM JAVASCRIPT
    if(isset($_REQUEST['beaconid'])){
        $beaconid = $_REQUEST['beaconid'];
    }
    if(isset($_REQUEST['uuid'])){
        $uuid = $_REQUEST['uuid'];
    }
    if(isset($_REQUEST['timestamp'])){
        $timestamp = $_REQUEST['timestamp'];
    }
    if(isset($_REQUEST['status'])){
        $status = $_REQUEST['status'];
    }

    /*$beaconid = 1;
    $uuid = "1213sdfdsdf";
    $timestamp = 3424;
    $status = 1;*/


    define('DB_SERVER', 'xxx');
    define('DB_USER', 'xxx');
    define('DB_PASSWORD', 'x');
    define('DB_DATABASE', 'x');

    if($beaconid != '' && $uuid != '' && $timestamp != '' && $status != ''){

        $mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

        if (!$mysqli) {
            trigger_error('mysqli Connection failed! ' . htmlspecialchars(mysqli_connect_error()), E_USER_ERROR);
            $arr = array ('state'=>'connection failed');
        }else{
            $stmt = $mysqli->prepare("INSERT INTO datalog(BeaconID,UUID,Timestamp,Status) VALUES (?, ?, ?, ?)");

            $arr = array ('state'=>'data pushed to the datalog');

            if ($stmt === false) {
                trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
                $arr = array ('state'=>'statement failed');
            }

            $bind = mysqli_stmt_bind_param($stmt, "isii", $beaconid, $uuid, $timestamp, $status);

            if ($bind === false) {
                trigger_error('Bind param failed!', E_USER_ERROR);
                $arr = array ('state'=>'build param failed');
            }

            $exec = mysqli_stmt_execute($stmt);

            if ($exec === false) {
                trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR); 
                $arr = array ('state'=>'statemente execute failed');
            }

        }

        $arr = json_encode($arr);   //response send to the app
        echo $_GET['callback'].'('.$arr.')';    //need this to prevent parsererror

        //CLOSE THE SQL QUERY/STATEMENT
        mysqli_stmt_close($stmt);


        mysqli_close($mysqli);

    }

?>
smj2393
  • 1,929
  • 1
  • 23
  • 50