Kalinka
Kalinka

Reputation: 205

"SyntaxError: JSON.parse: unexpected character" Error when passing multiple variables from AJAX to PHP

I am using AJAX to pass variables from a form to a PHP page to process data at a database.

Once the user clicks a button it fires a the following JavaScript:

$(document).ready(function() {

    $("#myForm").submit(function(event) {

        /* validate the fields */
        var firstDate= "11/10/2014"
        var secondDate = "10/10/2014"
        var myString = "some Text";
        var myArray = ["name1", "name2", "name3", "123-123-33gf"];

        processIT(firstDate, secondDate, muString, myArray);

    });/* end of submit */

});

function processIT(firstDate, secondDate, muString, myArray) {
    var response = ""; 
    $(function () {
        $.ajax({
            url: 'api.php',           // the script to call to get data
            type: "POST", 
            data: {
                firstDate: firstDate, 
                secondDate : secondDate , 
                myString : myString , 
                myArray : myArray , 
            },                 // you can insert url argumnets here to pass to api.php
            dataType: 'json',         // return data format
            success: function(data) { //
                alert(data);
             },
             error: function (jqXHR, textStatus, errorThrown){
                 console.log(textStatus, errorThrown);
             },
        });
    });
    return response;
}

The api.php page has the following

<?php 


    if ( isset($_POST["firstDate"]) && !empty($_POST["firstDate"])){
        $response .= "<p>firstDate= " . $_POST["firstDate"] . "</p>"; 
    }
    else $response .= " 1 ";
    if ( isset($_POST["secondDate"]) && !empty($_POST["secondDate"])){
        $response .= "<p>secondDate = " . $_POST["secondDate"] . "</p>";
    }
    else $response .= " 2 ";
    if ( isset($_POST["myString"]) && !empty($_POST["myString"])){
        $response .= "<p>myString = " . $_POST["myString"] . "</p>";
    }
    else $response .= " 3 ";
    if ( isset($_POST["myArray"]) && !empty($_POST["myArray"])){
        $response .= "<p>myArray = " . $_POST["myArray"] . "</p>";
    }
    else $response .= " 4 ";

echo json_encode($response);
?>

But when I click the button I get the following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

But if I change the POST to GET, I can see the passed variables, but still get the same error.

Any ideas what I am doing wrong?

Upvotes: 1

Views: 845

Answers (1)

gen_Eric
gen_Eric

Reputation: 227280

Your PHP file is not outputting a valid JSON response, that's why JSON.parse is throwing an error. There are a number of errors in your PHP code, and those errors are being included in the output, thus making an invalid JSON response.

console.log("firstDate" + $_POST["firstDate"]);

This is not valid PHP code. PHP doesn't have console.log(). It has echo. P.S. You use . to concatenate strings in PHP, not +.

$_POST["secondDate "]
$_POST["myString "]
$_POST["myArray "]

These keys. There is no space at the end. They should be:

$_POST["secondDate"]
$_POST["myString"]
$_POST["myArray"]

Finally, $_POST["myArray"] is an array. You can't concatenate it to a string. Try this:

$response .= "<p>myArray = ".implode(', ', $_POST["myArray"])."</p>";

Upvotes: 5

Related Questions