简体   繁体   中英

AJAX Post Error - SyntaxError: Unexpected token R in JSON at position 5

I am trying to send the following JSON file to an AJAX POST method.

See AJAX method below:-

$(document).on('submit', '#create-recipe-form', function(){
    // get form data
    var form_data= {
                     "recipe_name":"ghjghjh",
                     "category_name":"Desert",
                     "category_id":"8",
                     "Apple":"Apple",
                     "Carrots":"Carrots",
                     "step1":"ghj",
                     "step2":"",
                     "step3":"",
                     "step4":"",
                     "prep":"6"
                      };

    // submit form data to api
    $.ajax({
        url: "http://localhost:8082/recipe_app/api/recipes/create_recipe.php",
        type : "POST",
        //contentType : 'application/json',
        contentType : 'json',
        data : form_data,
        success : function(result) {

            createRecipeIngredientsForm();

            // recipe was created, go back to recipes list
            //showRecipes();
        },
        error: function(xhr, resp, text) {
            // show error to console
            console.log(xhr, resp, text);
        }
    });

The above AJAX method actually correctly calls the .php file and the data is inserted into the database. But there is an error returned and therefore the 'success' section never runs. This is so frustrating, can anybody shed any light?

SyntaxError: Unexpected token R in JSON at position 5 at parse () at ajaxConvert ( http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:8754:19 ) at done ( http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9222:15 ) at XMLHttpRequest. ( http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9514:9 )

replace this line of your ajax

form_data=JSON.stringify($(this).serializeObject());

to

form_data=$(this).serializeObject();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM