jQuery Ajax get value via function? - javascript

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}

You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}

Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Related

Return data from an ajax call whose type is POST

I have an ajax call that is of type post and I want to return the data by way of using return.
I have tried:
function GetDataById(Id){
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
return data;
},
error: function (jqXHR, exception) {
}
});
}
and I have tried:
function GetDataById(Id){
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
return data;
},
error: function (jqXHR, exception) {
}
});
}
and what I am doing is:
(function(){
const data = GetDataById(208);
console.log(data);
})();
$.ajax() returns a promise. If you want to implement a function that gets the data after the call, you can simply return $.ajax() call and use promise's then and catch instead.
function GetDataById(Id){
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8"
});
}
(function(){
GetDataById(208).then(data => console.log(data));
})();

how to get the json string in a variable

i got my json string inside the ajax as function like this way
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
here i get data like
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
i want it in a variable like
var myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
There you go :
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
var jsonobject = data;
},
error: function () {
alert('Error');
}
});
Also I strongly advise you to use promises to make API calls: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var jsonobject= null;
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
jsonobject=data;
alert('Success');
},
error: function () {
alert('Error');
}
});
If you want wait for ajax response and fill up variable then pass async: false in ajax request options.
Based on your comment, you need to parse the JSON in your success handler,
success: function (data) {
alert('Success');
var myjsonobject = JSON.parse( data );
},

how do to polling in jquery?

I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});
$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)
Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}
You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}

Can I use jquery's .done() more than once?

I have 2 JS literals:
var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
And this is my document.ready:
$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});
obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});
jQuery just executes the first call and obj2.List() ain't called at all.
How to properly use the deffered objects in this case?
Change your Add and List function to RETURN the ajax object.
Add: function (id) {
return $.ajax({..
and
List: function (id) {
return $.ajax({...
This way - it will return the jqXHR obj which will return the deferred object.
This implement the Promise interface which has : the callbacks you are looking for.
edit :
look at this simple example which does work :
var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("at success --"+data.data)
}
});
}
};
obj1.Add(2).done(function (a){alert("at done --"+a.data);});

ajax call not working with in ajax

I using the mvc controller with ajax. I perfom the task using the jquery confirm box. when i click the "ok" button its needs to the call another ajax and its link to the another controller but its not working
Sample code:
function button_click() {
$.ajax({
type: 'POST',
url: 'url',
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { call(data); }
else { alert(data.data); }
}
});
}
function call(data)
{
var ans = confirm(data)
if(ans)
{
$.ajax({
type: 'POST',
url: '#(Url.Action("StudentList", new { Area = "Mec", Controller = "HOD" }))',, // this url not goes to the controller
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { alert(data.data); }
else { }
}
});
} else { }
}
i have tried your code but it worked for me.the difference is that
you need to pass data in correct format. data:data or data:{ data:data } but not data:{data}
function button_click() {
$.ajax({
type: 'POST',
url: 'Demo/Demo_action',
data: { data: "what you want to pass" },
//dataType: 'json',
//contentType: 'application/json',
success: function (data) {
if (data == "hello") {
call(data);
}
}
});
}
function call(data) {
var ans = confirm(data)
if (ans) {
$.ajax({
type: 'POST',
url: '#(Url.Action("Demo_action2", new { Area = "Mec", Controller = "Home" }))',
//url: 'Home/Demo_action2', // this url not goes to the controller
data: { data: data },
dataType: 'json',
success: function (data) {
alert(data);
}
});
}
else
{ }
}

Categories