Ajax request jquery - ajax

Need
Pull PlanId from the Get variable send it to Web Service and I have GetPlanInfo function
Get the details of the package and display them
var MainServiceURL = 'http://someWebService';
var plan=[];
function planInit()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: MainServiceURL + "/GetPlanInfo",
data: {"ID" : ID ,"countryID" : CountryID},
success: function(response) {
plan = response.d;
main();
}
});
}
function main(plan)
{
document.getElementById("costPerMonth").innerHTML = plan.CostPerMonth;
document.getElementById("firstMonthPrice").innerHTML = plan.FirstMonthPrice;
document.getElementById("planName").innerHTML = plan.Name;
document.getElementById("landline").innerHTML = plan.Landline;
document.getElementById("mobile").innerHTML = plan.Mobile;
}
Where error?

Within the function main you treat a plan variable like a known object and you try to access its properties. However, plan is only an argument for the function main, which you don't pass once you get the response from your request. Look at:
success: function(response) {
plan = response.d;
main();
}
When you write like this, you call main function without passing plan argument. It should look like:
success: function(response) {
plan = JSON.parse(response).d;
main(plan);
}
Because as a response you only get a string - you have to translate it to JSON object using JSON.parse function.

Related

call function in ajax success callback

Is it possible to call a function in success callback of ajax request?
For example I have something like that :
constructor(private http: HttpClient,private serviceComposition: CompositionService) { }
[...]
save() {
var isValid = this.isValidCompo();
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
this.serviceComposition.changeValue(isValid);
})
}
}
I want to call a function of my service (named : changeValue() ) if my ajax request is a success.
But I have this error message : core.js:12632 ERROR TypeError: Cannot read property 'changeValue' of undefined
Do you know if it's possible to resolve that ?
I am suspecting this binding is going wrong in call backs,
prefer using arrow function because of "this" operator binding.
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done((data) => {
this.serviceComposition.changeValue(isValid);
})
}
if not u can store this reference in a variable and call it
var self = this;
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
self.serviceComposition.changeValue(isValid);
})
}
Use an arrow function to access this of your parent scope. In your example, this is referring to your jQuery XHR object.
So:
// [parent scope]
$.ajax({
...
}).done((data) => {
// [child scope]
// `this` now refers to [parent scope], so the following is valid
this.serviceComposition.changeValue(isValid);
});
Another common practice prior to arrow functions (ES6) would've been assigning a const self = this; variable in the [parent scope] area to be accessed in the child method. Either method works the same.
Also check out the MDN docs on this. It's a confusing topic for many.

Bypass Ajax request within javascript promise in Unit Testing

I have a function called getStudentData(),returns resolved data.
Inside getStudentData(), I have an Ajax request.
I want to Bypass Ajax request in my unit test case using Mocha , so that when i make a call to getStudentData(), the data should be returned.
Please find the code below:
getStudentData: function() {
return studentData || (studentData = new Promise(function(resolve, reject) {
var request = {
//request data goes here
};
var url = "/student";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json",
success: function(response, status, transport) {
//success data goes here
},
error: function(status, textStatus, errorThrown) {
reject(status);
}
});
}).then(function(data) {
return data;
})['catch'](function(error) {
throw error;
}));
}
Please let me know how to Bypass Ajax request By stubbing data using sinon.js .so that when i make a call to getStudentData() , data should be returned.
First of all doing:
then(function(data){ return data; })
Is a no-op. So is:
catch(function(err){ throw err; });
Now, your code uses the explicit construction anti-pattern which is also a shame, it can be minimized to:
getStudentData: function() {
var request = {
//request data goes here
};
var url = "/student";
return studentData ||
(studentData = Promise.resolve($.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json" })));
}
Now, that we're over that, let's talk about how you'd stub it. I'd do:
myObject.getStudentData = function() {
return Promise.resolve({}); // resolve with whatever data you want to test
};
Which would let you write tests that look like:
it("does something with data", function() { // note - no `done`
// note the `return` for promises:
return myObj.getStudentData().then(function(data){
// data available here, no ajax request made
});
});
Although in practice you'll test other objects that call that method and not the method itself.

Passing multiple objects to my controller

I am passing an object to my controller like so:
var form = JSON.stringify({
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val()
});
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
contentType: "application/json; charset=utf-8",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
my controller sees this as the object it is looking for:
public ActionResult CreateSubcontracts(RoutingSubcontracts s)
My problem is that I'd like to pass along just one more string. I know I can make a view specific model but I was wondering if I could do something like this for example:
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu)
I have tried the the following with no luck:
data: JSON.stringify({ "s": form, "bu": "251" }),
but the complex object just comes through as null. Is there a way I can pass the object and a string through as well?
Try adding the string item in the JSON you already have. Dont stringify it or it will just send a big string that youll have to parse again on the server.
var form = {
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val(),
"bu": "251" // add it here
};
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
In your view jquery create a second var for bu. Assign the data in you ajax call like this;
data: { "s" : form, "bu" : "251" }
In your controller method change the signature to include a default value for bu like this;
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu = "NoValue")
With the default value set bu will act like an optional parameter

How do I get JSON result from jquery .ajax call in done()?

I am trying to use the newer .done() syntax for a call to .ajax(), but I don't see how to get the data returned from the server into my .done() function. Here is my code:
function checkLink(element) {
var resultImg = $(element).parent().parent().find("img");
resultImg.attr("src", "/resources/img/ajaxLoad.gif");
$.ajax({
type: 'POST',
url: '/services/Check.asmx/CheckThis',
data: '{somedata: \'' + whatever + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: onSuccess,
error: onFailure
}).done(function () { success2(resultImg); });
}
function success2(img) {
img.attr('src', '/resources/img/buttons/check.gif');
}
function onSuccess(data) {
// The response from the function is in the attribute d
if (!data.d) {
alert('failed');
}
else {
alert('hurray!');
}
}
checkLink is called from a simple button push. Both onSuccess() and success2() are firing just fine. But... what I need is the "data" parameter from onSuccess passed to success2... or alternately, be able to pass "resultImg" to onSuccess (although I would prefer using .done instead of the deprecated method). It seems I can either pass my own parameters, or access the JSON result from the AJAX call... but not both. How do I accomplish this?
You can close over the resultImg variable:
function checkLink(element) {
var resultImg = $(element).parent().parent().find("img");
resultImg.attr("src", "/resources/img/ajaxLoad.gif");
$.ajax({
type: 'POST',
url: '/services/Check.asmx/CheckThis',
data: '{somedata: \'' + whatever + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: onSuccess,
error: onFailure
}).done(success2);
function success2(data) {
resultImg.attr('src', '/resources/img/buttons/check.gif');
// do whatever with data
}
function onSuccess(data) {
// The response from the function is in the attribute d
if (!data.d) {
alert('failed');
}
else {
alert('hurray!');
}
}
}

How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)

I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.

Resources