jQuery AJAX does not detect success - javascript

I have the following code.
$(".likeBack").on("click", function(){
var user = $(this).attr("user");
var theLikeBack = $(this).closest(".name-area").find(".theLikeBack");
$.ajax({
type: "POST",
dataType: "json",
url: "processes/rewind-knock.php",
data: "user="+user+"&type=likeback",
success: function(json){
alert("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
alert("XHR: " + jqXHR + " | Text Status: " + textStatus + " | Error Thrown: " + errorThrown);
}
});
});
Here, everything is functional. Network tab shows request and response well received as required. However, the success part is not getting executed. I tried adding beforeSend and complete and both are getting executed but success part (nothing inside the success blog is getting executed). I don't understand the reason why.
UPDATE
Add error part. It returns:
XHR: [object Object] | Text Status: parsererror | Error Thrown: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
UPDATE 2
Screenshot

give data in ajax like this and check,
data : {'user':user,'type':'likeback'},
In your Php code when you return the data, place all data in a array then use this,
echo json_encode($arr); //return the array in json form
now in your success function use
console.log(JSON.parse(json));
hope may help you. Thank you

Related

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();

.done not fired on ajax call

I have a function that makes a ajax call. The .done doesn't seems to be firing. I checked for the error on my console. It says
function getIncidentInfo() {
$.ajax({
type: "GET",
url: "../../page_components/statsboard/stats.php",
data: $(this).serialize(),
dataType: "json",
}).done(function(response) {
incidentAr = response;
for (var i in incidentAr) {
var zaNorth = parseInt(incidentAr[i].zaNorth);
......
}
}).fail(function(xhr, status, error) {
console.log("Status: " + status + " Error: " + error);
console.log(xhr);
});
}
I asked my friend to try the same piece of code and it works.
The script in stats.php is throwing an XDebug error and is returning HTML describing the error instead of the JSON you are expecting. Loading the stats.php page in a browser, or check your PHP logs to find out what the error is.
Check .always(response) instead of .done(response). Some services return non 200 codes with a response body to describe the error.
Check response.responseJSON, response.responseText, and response.responseXML. You may have to state response.responseJSON = eval(respaonse.responseText).
However, I see that the responseText is of HTML type, so my guess (and I say this because you're getting a 200 status and not a 404 or 500) is that you are getting a more generic server error that is rendering a response from a route you did not intend to query.

Status 200 OK, same domain, valid JSON data and no response (Ajax)

Here's my ajax call:
$.ajax({
url : hostGlobal + "site/modulos/prefeitura/acoes-jquery.php",
type: "POST",
dataType : "JSON",
data: {
acao: "filtrarCidades",
estado_id: $(".estados:chosen").val()
},
success: function(json) {
console.log("worked");
$(".cidades").html('');
var options = "<option value=\"\"></option>";
$.each(json, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$(".cidades").html(options);
if (!filterThroughCEP) {
$(".cidades").trigger("chosen:updated");
}
},
error: function(e) {
console.log(e.responseText);
}
});
Here's the php action:
if ($acao == 'filtrarCidades') {
$estado_id = $_POST['estado_id'];
$cidade->where = "estado_id = '".$_POST['estado_id']."'";
$cidade->LoadFromDB();
for ($c=0; $c<count($cidade->itens); $c++) {
$cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome;
}
echo json_encode($cidades);
die();
}
json_encode($cidades) is valid json data (UTF8), here's one example using debug:
{"1778":"Bras\u00edlia"}
This {"1778":"Bras\u00edlia"} goes as e.responseText (Error), even with Status OK, and the URL is on the same domain (No need for JSONP). I have no idea why I can't reach success.
EDIT: I've set the contentType:
contentType: "application/json",
And the call still can't "reach" success. Here's the third error argument:
SyntaxError: Unexpected token
at parse (native)
at ajaxConvert (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7608:19)
at done (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7363:15)
at XMLHttpRequest.<anonymous> (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9)
It is indeed related to unicode characters inside the strings that come from the database.
EDIT2: I wrote the whole thing again, and now it's clearer:
function getCitiesByState() {
$.ajax({
url : hostGlobal + "site/estrutura/ajax.php",
type: "POST",
dataType : "text",
data: {
action: "getCitiesByState",
state_id: $(".estados option:selected").val()
},
success: function(json, textStatus, jqXHR) {
console.log($.parseJSON(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
PHP:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
Output:
[{"id":"1778","estado_id":"7","nome":"Brasília","cep":"","loc_no_abrev":"Brasília"}]
Error:
Uncaught SyntaxError: Unexpected token
I think that the problem is the object property
{"1778":"Bras\u00edlia"}
means an object with an invalid property name, thus json decoding fails;
to prove if this is right try either
use plain text as dataType and log it, it should work [but of course you will not be able to convert it to json]
changeLoadFromDB method so that property name is valid [starts with letter, _ or $], you will have a valid JSON response, but you will need to change the way you use it
it 1778 is an ID, a proper structure should be
{id:"1778",property:"Bras\u00edlia"} and work flawless
give it a try and let us know
EDIT:
as jcaron kindly suggested, i have to fix, this answer: the "1778" is indeed a valid property name, but invalid identifier if dot notation is used.
Since I don't know how jQuery manage this i would suggest to test as above, and see if one of the tests gives results.

Error in Jquery Ajax request, it always executes the error block

I am sending an ajax call to my server, where parameter is "general" or any text, for a search query, why is it always giving error. The response is in JSON, and I have already mentioned it, any issues with the code below? Any help will be highly appreciated
$.ajax({
url : "${kb_endpoint_url}",
dataType : 'json',
data : { search_query : queryValue }, // queryValue = general
success : function(data) {
console.log("success");
},
error: function ( xhr, status, error) {
console.log( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error );
}
This prints: xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined
Edit: I tried changing the type to application/json and now the console prints
xhr.responseText: undefined //status: No conversion from text to application/json //Error: undefined
xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined
I think ; this error means that the response coming back from your URL is not JSON, there's an error attempting to parse it as such.
Either look in your network panel (easier), or adjust your error handler to see what response your server is actually returning, by looking at the responseText
If the server is returning the text undefined, this is not valid JSON and cannot be parsed.
Only null is valid in JSON format, so trying to parse undefined will give this error.
For examples:
JSON.parse("undefined"); // Throws an error, "Unexpected token u"
JSON.parse("null"); // Returns null
If you comment dataType : 'json', your ajax runs properly. Your response is not in JSON format.
$.ajax({
url : "${kb_endpoint_url}",
dataType : 'json',
type : 'post',
data : { search_query : queryValue }, // queryValue = general
success : function(data) {
console.log("success");
},
error: function ( xhr, status, error) {
console.log( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error );
}
});
Another file (mentioned url )
<?php
echo json_encode($_POST);
?>

How to post json array to PHP using jQuery's ajax method?

I have a json array created by javascript and need to post it to a php file in order to save the data into the database.
var myArray = [{
"picture":"picture1.jpg",
"picture_comment":"some comment about picture1",
"pictureid":16,
"u0id":80,
"u1id":82,
"u2id":78,
"u3id":79,
"u4id":81,
"param0": "60f3f",
"param1":"48dd2",
"param2":"4f2f7",
"param3":"8d101",
"param4":"5efcc",
"active":false,
"dutyid":1256,
"t":0
},
{
"picture":"picture2.jpg",
"picture_comment":"some comment about picture2",
"pictureid":160,
"u0id":18,
"u1id":48,
"u2id":70,
"u3id":95,
"u4id":74,
"param0": "1123f",
"param1":"48d13",
"param2":"595f7",
"param3":"78ad8",
"param4":"4efdc",
"active":false,
"dutyid":125,
"t":4
}
//goes like this about more than 20 times.
;
I have tried to post it using jQuery.ajax but I was not successful.
$.ajax({
type: "POST",
url: "goDoMyWork.php",
data: myArray,
dataType: "json",
success: function(){
alert("Done! You'll be redirecting now.");
window.location.href = "/index.php";
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert("Fail!");
}
});
I have to insert some of the data into one table and some of them into another table.
I have got the following error using:
alert(jqXHR + '-' + textStatus + '-' + errorThrown);
[object Object]-parsererror-SyntaxError: JSON.parse: unexpected character
Try changing data: myArray to data: {mydata : myArray}. Passing your array directly causes jQuery to pass it in an odd format. http://api.jquery.com/jQuery.param/
JSON.parse is the function that transforms text in json-format into a JavaScript object. What you seem to be wanting to do is throw some data at the server, where the server will handle it further.
What you are actually doing is setting the dataType to json. In the documentation you can read that this is the data-type you are expecting to get back from the server. jQuery will therefor throw the data it gets back from the server through JSON.parse, but apparently the data is not a well-formed json-string. Removing the dataType from your request will fix this, as the data will most likely not be parsed. Therefor, whatever gets returned will be in the form of a string.

Categories