Issue parsing json from jquery - javascript

I'm new to jquery I have a php that returns a json, so I can get it from jquery, but there is a problem getting the result.
Here's my code:
calculate: function(me, answer, res_id, soulmates) {
console.log('CALCULATE: ');
var deferred = $.Deferred();
data = {
'me': me,
'answer': answer,
'resid': res_id,
};
$.ajax({
url: appConfig.calculate_url,
type: 'post',
beforeSend: function() {
console.log('BEFORE');
Site.switch_calculation_animations();
console.log('AFTER');
console.log(appConfig.calculate_url);
},
data: JSON.stringify(data),
timeout: 15000
}).done(function(ans) {
console.log(ans);
console.log(ans.ok);
console.log(ans.combi_id);
console.log(ans.slug);
if (ans.ok == 'yes') {
console.log('YES');
deferred.resolve(ans);
}
}).fail(function(jqXHR, textStatus, error) {
console.log('ERROR');
Site.handle_exception('calculate', {
'textStatus': textStatus,
'error': error
});
deferred.reject();
});
console.log('END CALCULATE');
return deferred.promise();
},
The console log I get is:
CALCULATE:
app.js?v=35:242 BEFORE
app.js?v=35:244 AFTER
app.js?v=35:245 /es/test_calculate/4170/waiting/
app.js?v=35:266 END CALCULATE
app.js?v=35:250 {"ok":"yes","combi_id":6059244666,"slug":"true"}
app.js?v=35:251 undefined
app.js?v=35:252 undefined
app.js?v=35:253 undefined
So although the ok value is "yes", do not enter into the if command. Why? What I'm missing?
Thanks

Try this:
}).done(function(ans) {
var data = $.parseJSON(ans)
console.log(data);
console.log(data.ok);
console.log(data.combi_id);
console.log(data.slug);
if (data.ok == 'yes') {
console.log('YES');
deferred.resolve(data);
}

Related

Why e.status is getting as undefined in success function of ajax request?

I am getting my reponse as {"status":true}. But when I do console.log(e.status) I am getting as undefined.
When I do console.log(e) I get {"status":true}
This is my ajax request
$("#msgfrm").on("submit", function(e) {
event.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.ajax({
url: 'ajaxinsert.php',
method: 'POST',
data: {
name: name,
email: email
},
success: function(e) {
console.log(e);
console.log(e.status);
if (e.status === 'true') {
alert("success");
} else {
alert("Fail");
}
}
});
});
Please tell me what is my error??
It is because you are getting result as string. Try parsing it before using it.
success:function(e){
var obj=jQuery.parseJSON(e);
alert(obj);
alert(obj.status);
}

Make $ .ajax consider Response code 40x as success

jQuery executes the function "success" if the HTTP status code is in the range of 200 and 299 or is equal to 304.
However, for example, for the code 401 I need jQuery considers that the Ajax call is successful, and it evaluates the response as JSON and executes the function "success".
The problem is that this behavior is hard-coded in the method "done":
// Determine if successful
isSuccess = status> = 200 && status <300 || === status 304;
I do not really see how to do that.
EDIT:
This is what I have for the moment:
var options = {
url: '',
type: 'POST',
data: {},
success: function(response, status){},
error: function(res, status, error){
notify("Une erreur s'est produite !", "danger");
},
complete: function(res, status){}
};
$.extend(options, opts);
var dataString = '';
$.each(options.data, function(key, value){
dataString += ((dataString.length > 0) ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value)
});
$.ajax({
url: site_url + options.url,
type: options.type,
data: dataString,
dataType: 'json',
statusCode: {
401: function() {
setTimeout(function(){
location.reload();
}, 2000);
}
},
success: function(response, status){
if (response.response.result.status == 'ok'){
options.success(response, status);
} else {
if ('message' in response.response.result){
notify(response.response.result.message, "danger");
} else if (response.response.errors.length > 0) {
notify(response.response.errors[0], "danger");
}
}
},
error: options.error,
complete: options.complete
});
I want the answer to be parsed according to the dataType provided (which is only for the "success" method), and, in the case of a code 401, processing is the same as for the other responses containing the correct JSON code, except for a further instruction.
I think it is a mistake for jQuery not be able to change the codes indicating a request as having failed. The content of the response may be important anyway and require special processing.
For a complete web page, the browser still displays the content returned by the server in case of error.
Instead of trying to override the "success" callback why not just make the function call inside the "error" callback,ofcourse before checking the specific error occurred.
error: function(a, b, c){
if(a.status == 401){
// Your custom function call / code.
}
}
Do you have to handle the status code in the success or error block? How about the complete block? It follows both outcomes..
complete
Type: Function( jqXHR jqXHR, String textStatus )
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Source: http://api.jquery.com/jquery.ajax/
Example:
$.ajax({
url: "http://www.google.com"
}).success(function(){ //--> use .done() instead
//things to do on success
}).error(function(){ //--> use .fail() instead
//things to do on error
}).complete(function( data ) { //--> use .always() instead
switch(data.status){
//your logic here
}
});
Finally, given the need for that to go through the "complete" method, it is necessary to recode the entire automation of jQuery.
So there is no interest in using $ .ajax in this case.
That's why I had to code this replacement function that uses the jQuery syntax:
var altAjax = function(opts){
var options = {
url: '',
type: 'GET',
data: {},
dataType: 'text',
successCodes: [304, 401, 403, 404, 500],
statusCode: {},
success: [],
error: [],
complete: []
};
$.extend(options, opts);
var success = function(data, textStatus, xhr){
if ($.isArray(options.success)){
$.each(options.success, function(index, callback){
callback(data, textStatus, xhr);
});
} else if ($.isFunction(options.success)){
options.success(data, textStatus, xhr);
}
if ($.isFunction(options.statusCode[xhr.status])){
options.statusCode[xhr.status](data, textStatus, xhr);
}
}
var error = function(xhr, textStatus, errorThrown){
if ($.isArray(options.error)){
$.each(options.error, function(index, callback){
callback(xhr, textStatus, errorThrown);
});
} else if ($.isFunction(options.error)){
options.error(xhr, textStatus, errorThrown);
}
if ($.isFunction(options.statusCode[xhr.status])){
options.statusCode[xhr.status](xhr, textStatus, errorThrown);
}
}
var complete = function(xhr, textStatus){
if ($.isArray(options.complete)){
$.each(options.complete, function(index, callback){
callback(xhr, textStatus);
});
} else if ($.isFunction(options.complete)){
options.complete(xhr, textStatus);
}
}
var dataString = '';
$.each(options.data, function(key, value){
dataString += ((dataString.length > 0) ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(($.isArray(value) || $.isPlainObject(value)) ? JSON.stringify(value) : value);
});
var req = new XMLHttpRequest();
var url = options.url;
if (options.type.toUpperCase() != 'POST'){
url += ((url.indexOf('?') > -1) ? '&' : '?') + dataString;
}
req.onload = function(){
var textStatus = 'error';
if ((this.status >= 200 && this.status <= 299) || $.inArray(this.status, options.successCodes) > -1) {
var data;
switch (options.dataType.toLowerCase()) {
case 'json':
try {
data = JSON.parse(this.responseText);
} catch (ex){
error(this, textStatus, ex.name + ': ' + ex.message);
break;
}
textStatus = 'success';
success(data, textStatus, this);
break;
case 'xml':
try {
data = $.parseXML(this.responseText);
} catch (ex){
error(this, textStatus, ex.name + ': ' + ex.message);
break;
}
textStatus = 'success';
success(data, textStatus);
break;
default:
textStatus = 'success';
success(this.responseText, textStatus);
}
} else {
error(this, textStatus, null);
}
complete(this, textStatus);
};
req.open(options.type, url, true);
if (options.type.toUpperCase() == 'POST'){
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(dataString);
} else {
req.send();
}
req = null;
};
Instead of success use the complete function and check the xhr.statusText value
$.ajax('url.json', {
complete:function(result) {
if(/^(2\d\d|304|401)$/.test(result.statusText)) {
success();
} else {
error();
}
}
});
You need to handle the conditions at client side checking the status code. You can fetch the status as below:
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},

Ajax success function not working in jquery mobile

I am trying to validate a basic login form with username and password fields. I need to validate username and password from check.php ajax page. There is no problem in ajax request and response. I am getting proper response from ajax page. But Ajax success function is not working properly.
ajaxrequest.html
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Here i have added my ajax page. This page only validates posted username and password. Finally it returns json object. What am i doing wrong?
serverurl/check.php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
if(isset($_POST['formData']) && isset($_POST['action']) && $_POST['action'] == 'login'){
parse_str($_POST['formData'],$searchArray);
$uname = "arun";
$pwd = "welcome";
$resultArray = array();
if($uname == $searchArray['username'] && $pwd == $searchArray['password'])
{
$resultArray['uname'] = $searchArray['username'];
$resultArray['pwd'] = $searchArray['password'];
$resultArray['status'] = 'success';
}else{
$resultArray['status'] = 'failed';
}
echo json_encode($resultArray);
}
Your code should be
success: function (result) {
console.log("Ajax response");
//don't do this
//res = JSON.stringify(result);
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
After JSON.stringify you are accessing like stringJson.status this will not work. it mast have "parsed" "json object" not stringify.
Don't need to convert your JSON to String.
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
//Don't need to converting JSON to String
//res = JSON.stringify(result);
//directly use result
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Your AJAX call is perfect but datatype is not declared in ajax
Try with jSON OR JSONP. You will get success.
$.ajax({
url : 'serverurl/check.php',
type: 'post',
dataType: "json", OR "jsonp",
async: false,
data: {action : 'login', formData : $('#check-user').serialize()},
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
alert(JSON.stringify(result)); // Check response in alert then parse according to that
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
Under some circumstances your server might not return the response correctly. Have you tried to handle the actual response code (e.g. if your server returns 200) like this:
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
....
statusCode: {
200: function (response) {
// do your stuff here
}
}
});

Jquery $.Deferred Not Passing Parameters

I need to combine three methods:
An AJAX to check the existence of a code
If the code exists, confirm whether to overwrite
Overwrite
I've written three methods that return a $.Deferred in order to chain them together with .done(), which are below:
function checkFunction() {
var code = $("#code").val();
return $.ajax({
url: "${pageContext.request.contextPath}/dataManagement/codeMaintenance/check",
method: "POST",
async: false,
data: {
"reasonCode": code
},
success: function(response, textStatus, jqXHR) {
var exists = response.dataMap.exists;
console.log("Code exists: " + exists);
if (exists == true) {
return $.Deferred().resolve(true);
} else {
return $.Deferred().reject();
}
}, error: function() {
return $.Deferred().reject("AJAX ERROR");
}
});
};
var confirmFunction = function(codeExists) {
console.log("Confirming overwrite");
if (codeExists == true) {
var confirm = confirm("Code Exists: Do you wish to overwrite?");
if (confirm == true) {
return $.Deferred(true);
} else {
return $.Deferred(false);
}
} else {
return $.Deferred(true);
}
};
var saveFunction = function() {
console.log("Saving");
var code = $("#code").val();
return $.ajax({
url: "${pageContext.request.contextPath}/dataManagement/codeMaintenance/save",
method: "POST",
data: {
"reasonCode": code
},
success: function(response, textStatus, jqXHR) {
alert("test");
return $.Deferred(true);
}
});
};
I then attempt to execute via this line:
checkFunction().done(confirmFunction(codeExists)).done(saveFunction());
Unfortunately, the parameter I set on the $.Deferred from the first method does not get passed as a parameter to confirmFunction().
What am I doing wrong?
Jason
In short: plenty.
You try to use return inside of asynchronous functions in the success handlers of your $.ajax() calls.
Here you pass the result of the function call and not a reference of the function as callbacks:
checkFunction().done(confirmFunction(codeExists)).done(saveFunction());
This should be more like this:
checkFunction().done(confirmFunction).done(saveFunction);
In confirmFunction() you return a new Deferred object. What you should do is create a Deferred object, return the respective promise and then resolve/reject the Deferred object. So, e.g., your checkFunction() function should look like this:
function checkFunction() {
var code = $("#code").val();
// create deferred object
var result = $.Deferred();
return $.ajax({
url: "${pageContext.request.contextPath}/dataManagement/codeMaintenance/check",
method: "POST",
async: false,
data: {
"reasonCode": code
},
success: function(response, textStatus, jqXHR) {
var exists = response.dataMap.exists;
console.log("Code exists: " + exists);
if (exists == true) {
result.resolve(true);
} else {
result.reject();
}
}, error: function() {
result.reject("AJAX ERROR");
}
});
return result.promise();
}

JQuery mutiple post in the same time

I have three functions ,and every function post to special php page to get data..
and every function need some time because every php script need some time ..
function nb1() {
$.post("p1.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb2() {
$.post("n2.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb3() {
$.post("c3.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
$(window).load(function() {
nb1();
nb2();
nb3();
});
how can i threading all posts to work in the same time ?
You can use the jQuery when function (https://api.jquery.com/jquery.when/) to wait for all three promises to resolve.
You only need to make sure you also return the promise in your nb1, nb2, nb3 functions.
function nb1() {
return $.post("p1.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb2() {
return $.post("n2.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
function nb3() {
return $.post("c3.php", {
action: 1
}, function(data) {
console.log(data);
}, "json")
.fail(function(data) {
console.log("error");
});
}
$(window).load(function() {
$.when(nb1(), nb2(), nb3()).then(function(){
///
});
});
Do you really need to wait for window.load? Otherwise I would use document.ready beacuse it executes sooner.
You can use jQuery.when to call all ajax requests at once. And the success or failure events can be handled collectively.
Eg.
jQuery.when(
jQuery.post("p1.php", {
action: 1
}),
jQuery.post("n2.php", {
action: 1
}),
jQuery.post("c3.php", {
action: 1
})
).done(function(a1, a2, a3){
// handle success
var p1_responseTxt = a1;
var n2_responseTxt = a2;
var c3_responseTxt = a3;
}).fail(function (jqXHR, textStatus, errorThrown) {
// handle error
});
Here, the done function's params a1, a2, a3 correspond to the success data of p1, n2, c3 respectively.

Categories

Resources