Search code examples
javascriptjqueryxmlhttprequest

Unexpected end of input jquery using ajax


I am having the following jQuery script.

http://www.codeshare.io/aQxBp

And getting the error:

SyntaxError: Unexpected end of input

My js file is correct on syntax side, do not missing any closing or opening bracket. Thanks for any suggestion.


Solution

  • The here is that you are telling your ajax call to expect to receive JSON. When JSON is not received, an error will be thrown when JSON.parse tries to parse a non-JSON string. JSON is fairly simple in nature but you have to be intentional. To make an ajax call similar to this (note response.emailtoinvite):

    jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "sendinvitation.php", //Where to make Ajax calls
        dataType: "json", // Data type, HTML, json etc.
        data: myData, //Form variables
        success: function(response) {
            alert(response.emailtoinvite);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            //$(".btn.btn-primary").show(); //show submit button
            alert(thrownError);
        }
    
    });
    

    ....sendinvitation.php will have to send back a proper JSON string. The following works:

    {emailtoinvite: "[email protected]", idToInvite: 136}
    

    Important things to note here, all strings must be wrapped in double quotation marks "". Also, the entire string must be wrapped in {}. numbers can be left without quotes around them.

    Also important to note that the above is not proper syntax, but does sometimes work. Proper syntax also requires you to wrap you "keys" in quotes "" as well:

    {"emailtoinvite": "[email protected]", "idToInvite": 136}