jQuery Ajax Call function - javascript

I want to be able to call a function from the "on success" region instead of having to place my code in that region. I'll be using the code twice so I'm trying to figure out how to place it outside of the jQuery.ajax() function.
Here is my current code:
$.ajax({
type: "GET",
url: "ws/getweather.ashx?zip=" + vZip,
dataType: "xml",
success: function (xml) {
$(xml).find('weather').each(function () {
// Load New Data
...
});
},
error: function (xml) {
alert("Unrecognized Region. Please try again.");
}
});
So instead of having...
function (xml) {
$(xml).find('weather').each(function () {
// Load New Data
...
});
I'd like to put the name of another function, and pass the xml to that function. That way I can have other events call the same set of code.
Thanks in advance!
UPDATE===================================================
Thanks to Mike Richards for his timely response. I'm including the exact syntax below because I had to add a few details to make it work...meaning, pass the XML to the other function.
$.ajax({
type: "GET",
url: "ws/getweather.ashx?zip=32751",
dataType: "xml",
success: function (xml){
weatherize(xml);
},
error: function (xml) {
alert("Unrecognized Region. Please try again.");
}
});
And then somwhere below, my other function
function weatherize(xml) {
$(xml).find('weather').each(function () {
// Load New Data
...
})
};

you can just pass in a function for that parameter :)
success : successFunction,
and then, somehwere else:
function successFunction(data) {
// Do Something
}

Related

How to pass a variable from ajax to nested ajax

I'm sending ajax call and getting an answer that I need from the first ajax then I want to pass my result to my nested ajax, my var (result) is null in the nested ajax/settimeout fun, can I pass it ? Am I missing something ?
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
contentType:'json' ,
dataType:'text',
success: function (result) {
alert(result);**-> is fine - not null**.
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function
var a = result;-> tried to pass it to a new var..IDK.. I
thought it will help... it didn't.
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,-> here it's null
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
You can try something like this will help to pass value to nested ajax call
function test(){
var myText = 'Hello all !!';
$.get({
//used the jsonplaceholder url for testing
'url':'https://jsonplaceholder.typicode.com/posts/1',
'method':'GET',
success: function (data) {
//updating value of myText
myText = 'welcome';
$.post({
'url':'https://jsonplaceholder.typicode.com/posts',
'method':'POST',
//data.title is the return value from get request to the post request
'data':{'title':data.title},
'success':function (data) {
alert(data.title +'\n' + myText);//your code here ...
}
});
}
});
}
An old question and you've likely moved on, but there's still no accepted answer.
Your setTimeout takes an anonymous function, so you are losing your binding; if you have to use a Timeout for some reason, you need to add .bind(this) to your setTimeout call (see below)
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,
success: function (data) {
}
});
}.bind(this), 2000);
At a guess you're using a Timeout because you want to ensure that your promise (i.e. the first ajax call) is resolving prior to making the nested call.
If that's your intention, you can actually scrap setTimeout completely as you have the nested call in the first ajax success call, which only runs once the promise has been resolved (providing there isn't an error; if so, jQuery would call error rather than success)
Removing setTimeout means you won't lose your binding, and a should still be result (hopefully a is an object, otherwise your second call is also going to experience issues...)
Lastly, after overcoming the binding issue you wouldn't need var a = result; you should be able to pass result directly to your nested ajax call.
Good luck!
In the nested ajax you send a as a param name, not as a param value.
So you can try the following (change param to actual param name which your server expects):
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
dataType:'text',
success: function (result) {
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
data: {param: result},
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});

Why can I not do this?

function name does not exist in the current context is the error it gives me. I want a dynamic ajax call. Why does this happen? I get the handlers are processed server side, but I do not know how to go around this issue.
var getManager = function (functionName, contentDiv) {
console.log("aircraft manager refresh called");
$.ajax({
type: "GET",
url: '#Url.Action(functionName, "AdminTools")',
cache: false,
data: {},
error: function () {
alert("An error occurred.");
},
success: function (data) {
$("#".concat(contentDiv)).html(data);
}
});
}
I highly recommend you don't couple your server-side and client-side code like:
$.ajax({
type: "GET",
url: '#Url.Action(functionName, "AdminTools")', //THIS
It will turn into a maintenance nightmare. Instead:
<div id="#contentDiv" data-url="#Url.Action(functionName, "AdminTools")">
#* content *#
</div>
then
var getManager = function (functionName, contentDiv) {
console.log("aircraft manager refresh called");
var url = contentDiv.data("url");
$.ajax({
type: "GET",
url: url,
// .....
if you decide later to have multiple contentdivs each can have it's own url, and your code is reusable.

how to use ajax response data in another javascript

I am working with google map.My map data come from php using ajax response.
My ajax code:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
Now I have need to put my response data in my map var location
function initialize() {
var locations = [
//Now here I put my ajax response result
];
How can I do that?
You'll have to refactor your code a little. I'm assuming you call initialize from the success callback.
Pass the locations array as an argument to initialize.
function initialize(locations) { ... }
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
Then you can cut down even more and just do success: initialize, as long as initialize doesn't expect other parameters.
Here is a fiddle with an example using $.when but its for SYNTAX only not making the call
http://jsfiddle.net/2y6689mu/
// Returns a deferred object
function mapData(){ return $.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text'
});
}
// This is the magic where it waits for the data to be resolved
$.when( mapData() ).then( initialize, errorHandler );
EDIT** function already returns a promise so you can just use
mapData().then()
per code-jaff comments
This is done using callbacks, http://recurial.com/programming/understanding-callback-functions-in-javascript/ , here's a link if you want to read up on those. Let's see your current code here:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
As you noticed, the 'result' data is accessible in the success function. So how do you get transport it to another function? You used console.log(result) to print the data to your console. And without realizing it, you almost solved the problem yourself.
Just call the initialize function inside the success function of the ajax call:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
</script>
Is expected dataType response from $.ajax() to mapajax.php call text ?
Try
$(function () {
function initialize(data) {
var locations = [
//Now here I put my ajax response result
];
// "put my ajax response result"
// utilizing `Array.prototype.push()`
locations.push(data);
// do stuff
// with `locations` data, e.g.,
return console.log(JSON.parse(locations));
};
$.ajax({
type: "POST",
url: "mapajax.php",
dataType: 'text',
success: function (result) {
initialize(result);
}
});
});
jsfiddle http://jsfiddle.net/guest271314/maaxoy91/
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Two Ajax onclick events

So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}

jQuery parse xml from restful web service?

I have a code for pulling data from careerbuilders api. The link works well when tested on the browser, but I can't seem to parse anything from it. Care to tell me what is wrong?
html code:
<div class="main">
Companies:
</div>
jQuery code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: "xml",
success: xmlParser(xml)
});
});
function xmlParser(xml) {
$(xml).find("JobSearchResult").each(function () {
$(".main").append(
$(this).find("Company").text()
);
});
}
Here is a jsfiddle live example: http://jsfiddle.net/Cc4SY/
In your case xml won't be defined. You have to wrap the success callback in another function which in turn will call your xmlParser function.
What you are doing is calling the xmlParser function and assigning the return value as the success callback, which is not intended. So you have wrap it in another function and call xmlParser from that function and in that case the xml response will be properly passed to the xmlParser and you will able to parse it.
The code might look like this:
$(document).ready(function () {
$.ajax({
method: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: 'xml',
success: function (response) {
xmlParser(response);
}
});
});
function xmlParser(response){
var xml = $.parseXML(response);
$(xml).find("JobSearchResult").each(function () {
$(".main").append(
$(this).find("Company").text()
);
});
}
I think now it's working:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: "xml",
success: function(xml)
{
xmlParser(xml);
}
});
});
Fiddle here: http://jsfiddle.net/Cc4SY/2/
Console response: XMLHttpRequest cannot load http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
It's a jsfiddle restriction.

Categories