1

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?

12
  • 2
    SyntaxError: JSON.parse means that the JSON returned from the server is invalid. Nov 10, 2014 at 21:36
  • 1
    ALSO... why do you have console.log in your PHP?! That's most definitely going to throw an error.
    – gen_Eric
    Nov 10, 2014 at 21:38
  • 1
    Just look at what the actual response to the request is in the network panel of your browser’s development tools – most likely that will tell you already where you messed it up.
    – CBroe
    Nov 10, 2014 at 21:38
  • 1
    Also also, you have $_POST["myString "]. Why is there a space there? Your key is "myString", not "myString ".
    – gen_Eric
    Nov 10, 2014 at 21:42
  • 1
    Just a note, you can't do return response; in your processIT function. AJAX is asynchronous, which means it runs in the background and calls its callback whenever it's ready. You can't return from an AJAX call. Also, why do you have $(function () { inside processIT?
    – gen_Eric
    Nov 10, 2014 at 21:50

1 Answer 1

5

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>";
7
  • I fixed those issues. Now I do not get the json error anymore. But I am also not getting the variables passed. I do see them being passed in the fierbug console, but the return tells me that the values are either empty or not submitted.
    – Kalinka
    Nov 10, 2014 at 21:53
  • If you just do echo json_encode($_POST); die();, what do you see?
    – gen_Eric
    Nov 10, 2014 at 21:54
  • ...and you see them being passed in Firebug's request tab?
    – gen_Eric
    Nov 10, 2014 at 21:56
  • I removed the stringify and now i see the variables i am passing.
    – Kalinka
    Nov 10, 2014 at 21:56
  • 1
    JSON is "normally" used to encode objects/arrays (that can contain strings, numbers, objects, or arrays). You can json_encode a string, but sometimes it doesn't decode. If it works as you want, then it's fine :-)
    – gen_Eric
    Nov 11, 2014 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.