Javascript - Handling a AJAX call response from a web service - javascript

I'm using Javascript and Jquery to call a web service. The service should return an object. If the object returned contains Result=0, I want to show an alert, and if it doesn't, I want to show a different alert.
My code is shown below. I've tried "if (data.Result)" and "if (data.Result=0)", and neither of them work and show the "stock added" popup message.
Any help would be appreciated.
Object returned:
data: Object
Booking: Object
BookingId: "28eec5f6-29a7-e411-941a-00155d101201"
BookingProductIds: null
BookingStatus: 2
CrossSellProducts: null
ErrorMessage: ""
Result: 0
Javascript code:
function generateOrder() {
ABC.TixService.AddStockProduct(null, null, productRequest, ticketingRequest, function (context, data) {
if (data.Result) {
alert("stock added");
}
else
alert("error");
});
AddStockProduct: function (context, bookingId, productRequests, request, action) {
$.ajax({
url: 'TixService.svc/AddStockProduct',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ bookingId: bookingId, productRequests: productRequests, request: request }),
context: { context: context, action: action },
success: function (data) {
this.action(this.context, data.AddStockProductResult);
},
error: function (xhr, ajaxOptions, thrownError) {
ErrorResponse(xhr, thrownError);
}
});
},

Shouldn't the test be:
if(data.Result === 0){
alert('stock added');
}

Related

How to define a variable in PHP

I am getting the error message $data is undefined when I try to debug my code by using var_dump($data);
This is my java-script code and the paste bin is my PHP code, there was just too much to put it in one post.
https://pastebin.com/EH0WvA30
However I am not sure what to define it as, or where to define it in my PHP code. Any help would be great. Thanks
function getItinerary (){
$.ajax({
url: 'php/itinerary.php',
type: 'POST',
dataType: 'json',
data: {action: 'LOAD'
userId: $userId,
attractionId: $attractionId
}, //Here put two mode keys and values, userId and attractionId like {userId: '<value here required by your server>',attractionId: '<value here required by your server>'}
success: function(data) {
console.log(data);
alert('request successful');
},
error: function () {
alert('Network or Server error');
}
});
}
Due to this if condition
if(!empty($_POST['userId']) && !empty($_POST['attractionId']) && !empty($_POST['action'])) {
}
If you don't send useId and attractionId in your ajax request, the condition will return false.
I think that's the reason for not working
Update your ajax code like this
function getItinerary (){
$.ajax({
url: 'php/itinerary.php',
type: 'POST',
dataType: 'json',
data: {action: 'LOAD'}, //Here put two mode keys and values, userId and attractionId like {userId: '<value here required by your server>',attractionId: '<value here required by your server>'}
success: function(data) {
console.log(data);
alert('request successful');
},
error: function () {
alert('Network or Server error');
}
});
}

Ajax Call not being accessed in most pages

This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!

Post request is succeeding according to database but failing according to Ajax block

I am posting to my database (for context using GAE, and Objectify as a DAO) and it posts correctly (and the backend returns a response of 202), however, under the Ajax it is not calling the "success" block (i.e. in the method below even when it post's correctly, it calls alert("error1")). The source code for Ajax says a Post is supposed to call the success block when the status is between 200 and 300. Any ideas why it isn't working? Any help would be great!
function userExist() {
var rootUrl = "http://localhost:8888/api/";
function loginToJSON() {
return JSON.stringify({
"username": $('#username').val(),
"password": $('#password').val()
});
}
//System.out.println(loginToJSON());
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootUrl + 'userLogin',
dataType: "json",
data: loginToJSON(),
success: function(data, status, jqXHR) {
alert("success");
},
error: function(jqXHR, status, errorThrown){
alert("error1");
}
});
}
The relevant java backend is
#POST
public Response login(Login l) {
if (loginService.checkCred(l)) {
return Response.status(202).build();
} else {
return Response.status(403).build();
}
}

Jquery Ajax callback not working calling success and failed

I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.
The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?
Here is my code:
$('input[type=button]').click(function () {
bookingID = $(this).closest('tr').attr('id');
sendEmail(bookingID, this);
});
function sendEmail(id, thisContext) {
var data = JSON.stringify({ 'id': id });
/*******
This calls setButtonSuccess AND setButtonFailed which is wrong
I want to execute only setButtonSuccess OR setButtonFailed depending on whether successful or not
*******/
jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};
function setButtonSuccess(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-success");
};
function setButtonFailed(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-warning");
};
function jsonPOST (pWebServiceFunction, pData, pOnCallbackSuccess, pOnCallbackFailed, async) {
$.ajax({
type: "POST",
url: url + pWebServiceFunction,
data: pData,
contentType: "application/raw; charset=utf-8", dataType: "json",
async:async,
processdata: true,
success: function (msg) {
if (msg.success === true) {
pOnCallbackSuccess(msg);
}
else {
pOnCallbackFailed(url + pWebServiceFunction);
}
},
error: function (xhr, ajaxOptions, thrownError) //When Service call fails
{
pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
}
});
};
Thanks
You're calling the functions immediately instead of passing a function that will call them later. It should be:
jsonPOST("~Booking/ResendEmail", data, function() {
setButtonSuccess(thisContext, "Email Sent");
}, function() {
setButtonFailed(thisContext, "Email Failed");
}, false);

asp.net ashx handler: can't receive response

Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.

Categories

Resources