JQuery.ajax returns error: Unexpected token with error message: parseerror?

I have a jquery.ajax procedure that calls a php script. The PHP script searches the Google search API and returns json to the calling ajax script.

The script works fine on 99% of the installations, however, on some, when I call:

error: function(jqXHR, textStatus, errorThrown){ alert('HTTP Error: '+errorThrown+' | Error Message: '+textStatus); } 

It returns:

HTTP error: SyntaxError: Unexpected token <| Error message: parsererror

How can I fix this using javascript console or chrome developer tools? Code plug below ...

 var result=''; jQuery.ajax ({ contentType: "application/json; charset=utf-8", dataType: "json", url: <?php echo '"' .plugins_url('/script.php', __FILE__); ?>?Query="+ jQuery('#search_keyword').val(), success: function(data) { //do something with results }, error: function(jqXHR, textStatus, errorThrown){ console.log(arguments); alert('HTTP Error: '+errorThrown+' | Error Message: '+textStatus); return; } }); 

UPDATE: OBJECT Console.log Error:

 responseText: "<br /><b>Warning</b>: array_map() [<a href='function.array-map'>function.array-map</a>]: Argument #2 should be an array in <b>/filepath/wp-content/plugins/test/test.php</b> on line <b>75</b><br /><br /><b>Warning</b>: Invalid argument supplied for foreach() in <b>/filepath/wp-content/plugins/test/test.php</b> on line <b>90</b><br />↵No Records Returned. Search may be down. Wait a few minutes" 
+6
source share
2 answers

You will probably return HTML where it should not have been used for JSON.

Try console.log(arguments); before warning to see what is coming back

+11
source

This tells you where the problem is:

 responseText: "<br /><b>Warning</b>: array_map() [<a href='function.array-map'>function.array-map</a>]: Argument #2 should be an array in <b>/filepath/wp-content/plugins/test/test.php</b> on line <b>75</b><br /><br /><b>Warning</b>: Invalid argument supplied for foreach() in <b>/filepath/wp-content/plugins/test/test.php</b> on line <b>90</b><br />↵No Records Returned. Search may be down. Wait a few minutes" 

Most likely, in some installations it behaves differently due to different error_reporting settings

In production environments, error messages should be turned off, but as a rule, your code should never issue any warnings or notifications.

In any case, you should better handle your errors, especially in

 Argument #2 should be an array in /filepath/wp-content/plugins/test/test.php on line 75 Invalid argument supplied for foreach() in /filepath/wpcontent/plugins/test/test.php on line 90 

Both of these warnings are caused by the fact that your variable is not an array (maybe false or null), usually this can be fixed with is_array before accessing the array or always by checking the return value of all functions.

0
source

Source: https://habr.com/ru/post/897335/


All Articles