I have designed a website that takes a users input as search parameters and uses them to search a database using an AJAX call to a PHP page. In this AJAX call, I obviously have some data (formatted as a JSON file) that I manipulate and use in the "success" section of the ajax arguments.
Here's the problem--I want to be able to analyze the data from the narrowed search the user puts in against the data from the entire database population. How can I do this?
I thought I would just do another AJAX call, but the data from that call seems inaccessible from the outside, and I can't find any ways to "export" it outside the call.
Here is a shortened version of the code:
$.ajax({
url: URL for the search .php,
cache: false,
data: {
Various search parameters by the user
},
dataType:"json",
success:function(data){
Data manipulation and reading the resulting JSON
$.ajax({
url:URL2 for the population .php,
cache: false,
dataType:"json",
success:function(data){
population data stuff here
},
error: error stuff
}
error: error stuff
}
That's the only way I know to access the database thus far. How can I somehow pull the data out of that second AJAX so that I can use it in the first one?
Since your working with asynchronous callbacks you can't "extract" the data from the second call and use it in the first. What you will have to do is make the two calls and use the data from each within the second calls success callback. You can do this if rename the variables you're using with the success callback functions to be unique.
$.ajax({
url: /**/,
success:function(response1){
$.ajax({
url: /**/,
success:function(response2){
/* use both response1 and response2 here */
},
error: /**/
})
},
error: /**/
})
If you aren't using data from the first ajax call to make the second ajax call you can use something like jQuery.when to wait for both request to finish.
Related
I want to get 3 values from a web service by providing current URL and current user. My webservice accepts 2 parameter URL and user. Web service works fine.
Now I want to put this 3 values in 3 different textboxes using jquery.in txtOrgCity = city, in txtPin = pin, in txtCountry = country
bellow is code for txtOrgCity
$(document).ready(function () {
$('#txtOrgCity').val({
source: function (request, response) {
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
when I run it gives me [object object] in text box.
How do I define to grab City for txtOrgCity, pin for txtOrgPin, country for txtOrgCountry in response(data.d).?
and do I need to duplicate the same code for other 2 text boxes or any better way.?
Given code is just for some txtbox autocomplete and it works perfectly so I just wanted it to modify a bit for my need. $('#txtOrgCity').val was $('#txtOrgCity').autocomplete
Any help would be appreciated.
--
Thanks
I recommend that you open this up in google chrome. Open up your developer tools (press f12) and, open up resources and select the page you are currently working on. Then use the find box to search for your javascript method which fires the ajax and put a break point inside the success part of your ajax call. Now run your code and wait to hit the break point. Now you can see what is inside your data.d object. Do not resume and keep debugging. Open up your console tab and type data.d. you should see an intelicence option box with all the variables inside your data.d object. You should see the variable for city, pin and country in whatever way you named them when you deserialized your data and returned it as json to your ajax call.
If, for example, you write data.d.city in your console it should write out the corresponding value. The same goes for any other json variable your service passed back to the browser.
With that information it is easy enough to use jquery and do what you want with the data. So in the succes part of your ajax call you can write:
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
p.s. im writting on a phone.
For your example you should not write out the same code two more times. Do not call ajax inside a jquery .val(), that is wrong. Make a new function which handles your ajax, call it from the page load or anywhere you need :
function loadData(//put your user parameter in here if you need){
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
},
error: function (err) {
//welldone for handling your error message. Many people neglect this. As a developer that is like coding blindly. At the very least you can console.log(err); if you don't want the user to see
alert(err);
}
});
}
Instead of $('#txtOrgCity').val({})
In your .ready function make the AJAX call first.
Store d.OrgCity, d.OrgPin & d.OrgCountry into some local JavaScript variables. In the Ajax call success use these values to deposit into textboxes like
$('#txtOrgCity').val(d.OrgCity)
You are after JSON.stringify(). So where you specify your .val() You want .val(JSON.stringify());
I have built a weather website that calls the flickr API 1st, then calls the yahoo API for the weather. The problem is that the data from the ajax call - from the yahoo API is not here in time for the page to load its content.
Some of the things I have used to try and slow the ajax call down:
setTimeout
wrapping the entire function that $.ajax(success: ) calls into another function, wrapping it in setTimeout
taking the callback function out of $.ajax(success: ), and putting into the $.ajax(complete: ) param
taking the data object that $.ajax(success: ) passes in, and copying that to another var, then going outside of ajax call and putting the function that handles the data inside of $.ajaxComplete(), passing new object var
There are more ways that I have tried to go about this, but I have been at it for 3 days and cannot find a solution. Can someone please help me here
Here is a link to the project
My Weather App On codeine.io
function RunCALL(url)
{
var comeBack = $.ajax({
url: url,
async: false,
dataType:"jsonp",
crossDomain: true,
method: 'POST',
statusCode: {
404: function() {console.log("-4-4-4-4 WE GOT 404!");},
200: function() {console.log("-2-2-2-2 WE GOT 200!");}},
success: function(data){
weatherAndFlickrReport(data);},
error: function(e) {console.log(e);}
});
}
Are you using jQuery? If so, you have to chain your callbacks. Which, at a high level, would looks something like:
//You might want to use .get or .getJSON, it's up to what response you're expecting...
$.getJSON('https://example.com/api/flickr', function(response) {
//This your callback. The URL would end up being https://example.com/api/yahoo/?criteria=lalalalala
$.getJSON('https://example.com/api/yahoo/', { criteria: response.propertyYouWant}, function(yahooResponse) {
//Do something with your response here.
});
});
Edit: I have updated your snippet with a working solution (based on the above AJAX requests) which now shows both your JSON objects ready for consuming. Looky here.
I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}
I get a list of users with an AJAX call, but within the AJAX I call another AJAX to get some information that I could not get with the first AJAX call.
This is basically the structure I'm using, I've removed some unneccesary code that would just clutter, it is possible that there is some syntax errors here and there.
But the code basically works but there are some issues.
function doAJAX(){
$(".loading").show();
$("#table").hide();
$.ajax({
type: "POST",
url: "#Url.Action("Action", "Controller")",
data: { variable: varVariable},
dataType: "json",
success: function (data) {
$.each(data, function (index, value) {
$.ajax({
type: "POST",
url: "#Url.Action("Action", "Controller")",
data: { variable: value.id},
success: function (data2) {
$.each(data2, function (index2, value2) {
$("#tableBody").append("<tr><td>" + value.test +"</td><td>" + value2.test +"</td></tr>");
});
}
});
});
}
});
}
I hide my table at the start, when the AJAX is complete I want to show it again. Where exactly should I place it? Even if I place it at the end of the first AJAX success function it does not work because it gets executed while the other AJAX is still running.
For some reason my list ends up in an odd order everytime the AJAX runs, my list is sorted by alphabetical order yet with this AJAX it ends up random everytime, sometimes the user Adam is at the start, sometimes in the middle and so on. The list itself is fine and in correct order
I do a lot of mathematics that is probably slowing down the second AJAX call which is probably why it ends up in a weird order
Both of these issues are happening because the two AJAXs aren't running "together" but individually, is there a way to make them sync with each other and is there a good way to be sure that the AJAX is completed and now I can show my table?
Sending ajax request inside a loop doesn't seem like a good idea. Why won't you send one ajax request with array of id's as a data, inside your serverside script just get "WHERE id IN (id_list)" array of user records and return them as json-encoded object, and then output it inside a double loop, first for <tr>, second for a list of fields.
I'm sorry i can't provide code, as i don't know what is being returned from your requests to server.
I hope this is not too much of a newbe question but I've been pulling my hair out for a while now so thought I'd give in and ask for my first piece of advice on here.
I'm trying to read an external xml file using javascript / jQuery / ajax and place the retrieved data into an array so that I can then reference it later.
So far I seem to be doing everything right upto the point I put the data into the array but then I'm struggling to to read the data anywhere other than inside the function where I create it. Why am I not able to access the Array from anywhere other than in that function?
Here is my code...
Please help!!
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser
});
function do_xmlParser(xml)
{
var myArray = new Array();
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
console.log("inside "+myArray); // This outputs the array I am expecting
return myArray; // is this right???
}
console.log("outside: "+myArray); // This does NOT output the array but instead I get "myArray is not defined"
You're defining do_xmlParser as a callback to an asynchronous function (success of the jquery ajax call). Anything you want to happen after the ajax call succeeds has to occur within that callback function, or you have to chain functions from the success callback.
The way you have it now, the actual execution of code will go:
ajax -> file being requested -> console.log ->
file transfer done -> success handler
If you're doing some critical stuff and you want the call be to synchronous, you can supply the
async : false
setting to the ajax call. Then, you should be able to do something like this:
var myArray = [],
do_xmlParser = function (xml)
{
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
};
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser,
async: false
});
console.log("outside: " + myArray);
The async option doesn't work for cross-domain requests, though.
NOTE
I don't recommend doing this. AJAX calls are supposed to be asynchronous, and I always use the success callback to perform all of the processing on the returned data.
Edit:
Also, if you're into reading... I'd recommend jQuery Pocket Reference and JavaScript: The Definitive Guide (both by David Flanagan).
look close and you will see. You are actually firing up an array that dosen't exist. You have declared myArray inside function. Try do something like this.
console.lod("outside :"+do_xmlParser(xml)); // I think that when you merge a string and an array it will output only string, but I can be wrong.