Search code examples
javascriptjqueryajaxcordovajsonp

Parsererror when using AJAX and JSONP with Cordova


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);

}
?>

Solution

  • 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);
    
        }
    
    ?>