简体   繁体   中英

AJAX: Return from PHP fires error: requested JSON parse failed

When I run my little javascript with an AJAX call to PHP it always returns with a JSON parsererror.

In PHP I can see that my json is filled with an array like this: json encode: {"Year":"2012","Make":"Ford","Model":"Taurus","Error":"no error"}

This is the site:

The AJAX will be called when the visitor leaves the field VIN on the left and should fill the 3 fields on the right automatically.

 function decode_my_vin(myvin) { alert("javascript began"); dataoneID = '00000'; dataoneKEY = 'x0x0x'; jQuery.ajax( { cache: false, type: 'POST', url: '/wp-content/themes/Impreza-child/vin-decoder.php', dataType: "json", data: { 'value1_VIN': myvin, 'value2_ID': dataoneID, 'value3_KEY': dataoneKEY, }, success: function(response) { var resultYear = response.Year; var resultMake = response.Make; var resultModel = response.Model; var resultMessage = response.Message; alert("success returned: Year " + resultYear + " Make " + resultMake + " Model " + resultModel + " Message " + resultMessage); document.getElementById("fld_7290902_1").value = resultYear; document.getElementById("fld_1595243_1").value = resultMake; document.getElementById("fld_7532728_1").value = resultModel; document.getElementById("fld_7532728_1").value = resultMessage; return; }, error: function (jqXHR, exception) { var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\\n' + jqXHR.responseText; } alert("Error in jquery: " + msg); $('#post').html(msg); }, complete: function(value) { alert("returned after complete: " + value); } }); } 
 <?php header('Content-Type: application/json'); $vinResult = array( 'Year' => '2012', 'Make' => 'Ford', 'Model' => 'Taurus', 'Error' => 'No Error' ); echo json_encode($vinResult); ?> 

In your error function of ajax call, it gives error for $('#post').html(msg); saying not function. Try using jQuery('#post') instead of $('#post') .

To parse your response, use var data = jQuery.parseJSON( response ); and then access fields by data.Year etc.

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