Why does inner method's inside execute last? - javascript

At following method i'm trying to get grid selected row. By the way, i use syncfusion component library.
My question when i call the grid.rowSelected, function's inside works last. So i can't pass model in ajax.
What's the reason of it ?
function editPackage() {
var editPackageModel;
var grid = document.getElementById("Grid").ej2_instances[0];
grid.rowSelected = function(args) {
console.log(args.data);*// works last*
editPackageModel = args.data;*// works last*
}
$.ajax({
type: "GET",
url: "/Package/Edit",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: editPackageModel,
success: function (result) {
$('#generalModal').html(result);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}

I'm not sure exactly what is the situation with "grid", i assume you have that element ready before the function is called, so try this:
var grid = document.getElementById("Grid").ej2_instances[0];//Get node reference.
grid.rowSelected = function (args) {//Setup event listener.
editPackage(args.data);//Pass the data from the event to your function
}
function editPackage(editPackageModel) {//Get the "model" and send ajax
$.ajax({
type: "GET",
url: "/Package/Edit",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: editPackageModel,
success: function (result) {
$('#generalModal').html(result);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}

Related

Passing parameter over jQuery GET call receive null on server side

I'm trying to make a GET call in jQuery passing a parameter here is what I'm doing
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere",
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
}
On server side the controller is called but the data I'm getting is always null...
[HttpGet]
public IEnumerable<TypeOfObject> GetDataHere([FromBody]string id)
{}
Any idea how's that happening?
You need to give the value a key so that the ModelBinder can recognise and work with it:
data: { id: id },
You also need to remove the [FromBody] attribute in the action signature, as GET data is sent in the URL (either as part of the querystring, or in a routing structure).
Lastly, the options object of $.ajax() has no failure property so that can be removed as it's redundant.
I upvoted #RoryMcrossan, but there is another solution.
you could just add it to the end of the url.
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});

how to create a javascript rusable class to pass parameters to ajax

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

jquery ajax - second array push not working [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
i have this code that needs to populate an array that will be used on some diagramming tools. so there's a button that will show the results and a checkbox that enables the user to add another set of rows to the array. i use .push() for the array and it works. now, the problem is that the second push on my second ajax calls did not add the data to the array. here's my code:
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one fails
alert("pushed");
});
},
failure: function (data) {
alert(data.d);
}
});
drawChart(rows);
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});
i really don't know why it fails. what happens is that even if the condition is satisfied and the second ajax call succeeds, the contents of the array rows is still the first array push. what's the problem with the code?
the result you are getting is actually expected because of async nature of ajax
you should call the method within the success callback of the second ajax call like this
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values);
});
drawChart(rows); // here
},
failure: function (data) {
alert(data.d);
}
});
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});

Jquery Ajax Call, doesn't call Success or Error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I return the response from an asynchronous call?
I am using Jquery Ajax to call a service to update a value.
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesn't go here
},
error: function (textStatus, errorThrown) {
Success = false;//doesn't go here
}
});
//done after here
return Success;
}
and Service:
[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
try
{
CHData.UpdatePurpose(Vid, PurpId);
//List<IDName> abc = new List<IDName>();
//abc.Add(new IDName { Name=1, value="Success" });
return "Success";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
the service is being called Successfully from the AJAX. Value is also being Changed. But after the Service, success: or error: functions are not being called, in this case success should have been called but it is not working.
I used firebug and found that, the success or error functions are being skipped and goes directly to return Success;
Can't seem to find what's the problem with the code.
Update:
adding async: false fixed the problem
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous function. Otherwise you will have to make a callback.
So I just added async:false, to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object

"undefined" for alerting an ajax call response , why?

i am trying to alert the return value captured by the ajax request. The web method it is refering is returning a boolean value of true or false, and when i am trying to access it outside the ajax method it gives a message "undefined" :?
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
},
});
alert(authInfo);
});
</script>
why is the alert(authInfo) giving me as "undefined" ?? Please help !
where does this piece of code fit on the above context ?
if(auhthInfo){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) {
return { orgval: value};
},
});
};
Your "$.ajax()" call is asynchronous, and thus the results are not available until the response is returned from the server.
If you put your "alert()" inside the "success" callback, it should work (if the HTTP transaction works).
EDITED TO HANDLE YOUR NEW CODE:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// alert(msg.d); // here it will work as it is only called when it succeeds.
MyHanlder(msg);
},
});
// alert(authInfo); // here authinfo has no value as the AJAX call may not have returned.
});
function MyHandler(msg) {
if(msg.d){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) { return { orgval: value}; },
});
};
}
</script>
The request and the response that you get via ajax calls are asynchronous. I think it is not possible to alert the value that you get in response at the end of ready function because you are not assured that you will be getting your response before the function completes execution.
You are alerting the authInfo variable before the actual ajax call have returned. If you try this:
success:function(msg) {
authInfo = msg.d;
alert(authInfo);
}
I think you will get the correct result.
Because the AJAX call is done asynchronously, the alert does not have the value at the time of execution. If you place the alert inside the success function you should see the appropriate results. I also noticed you have an extra comma in the $.ajax parameters after the success function parameter.
It appears:
alert(authInfo);
Is running immediately when your document is ready.
However, the variable is not being initialized until after the AJAX call completes.
Try moving the alert to:
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
alert(authInfo);
},
});
If you need to do anything more complex with the value, you can try re-factoring the code into another function:
function onSuccess(msg)
{
if(msg.d)
{
window.alert('The value is true!');
}
else
{
window.alert('The value is false!')
}
}
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
});

Categories