what should I write in the script to make javascript asynchronously implement firstly ajax method GET and then another simple function(in the order of my script)?
because here while debugging I see that getCategories() is implemented before WriteCategories(categories)
$.ajax({
url: '/api/ListingAPI/GetCategoriesById?id=1',
type: 'GET',
dataType: 'json',
success: function WriteCategories(categories) {
// ...
}
});
var test = getCategories();
Actually you want synchronous execution,
you need to add async: false in ajax request, (But be aware of this it will freeze your UI until your request completes, actually it is not recommended)
$.ajax({
url: '/api/ListingAPI/GetCategoriesById?id=1',
type: 'GET',
async: false,
dataType: 'json',
success: function WriteCategories(categories) {
// ...
}
});
var test = getCategories();
or either you can call your function on ajax success callback,
$.ajax({
url: '/api/ListingAPI/GetCategoriesById?id=1',
type: 'GET',
dataType: 'json',
success: function WriteCategories(categories) {
var test = getCategories();
}
});
For your knowledge, You can pass your query string params in data option in ajax rather than query string itself,
var queryStringData = {id : 1}
$.ajax({
url: '/api/ListingAPI/GetCategoriesById',
type: 'GET',
dataType: 'json',
data: queryStringData,
success: function WriteCategories(categories) {
var test = getCategories();
}
});
Try this code.
$.ajax({
url: '/api/ListingAPI/GetCategoriesById?id=1',
type: 'GET',
dataType: 'json',
success: function WriteCategories(categories) {
var test = getCategories();
}
});
You can call this function after ajax success. By this way AJAX get will be executed first.
Related
I am trying to insert the value of parent into the "getFaculties()" function when i call the function using Ajax.
function ajaxfunction(parent)
{
$.ajax({
type: 'GET',
url: 'Connection.php?getFaculties('+parent')',
success: function(data) {
$("#selFaculty").html(data);
}
});
}
please use a proper way to pass data from ajax to php
function ajaxfunction(parent)
{
$.ajax({
type: 'GET',
url: 'Connection.php',
data: {method:'getFaculties', value:parent}
success: function(data) {
$("#selFaculty").html(data);
}
});
}
The correct syntax is
url: 'Connection.php?faculties='+getFaculties(parent),
Since that is query parameter, given a name to it.
use like this function Declaration was wrong
function ajaxfunction(parent)
{
$.ajax({
type: 'GET',
url: 'Connection.php?getFaculties='+getFaculties(parent),
success: function(data) {
$("#selFaculty").html(data);
}
});
}
Call your function first and get return value in variable and then send your ajax request.
function ajaxfunction(parent)
{
var data_in = getFaculties(parent);
$.ajax({
type: 'GET',
url: 'Connection.php?getFaculties='+data_in,
success: function(data) {
$("#selFaculty").html(data);
}
});
}
I am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);
This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});
I am trying to make two jQuery ajax calls, the second should be made from the success callback of the first. I have tried a couple variations of code e.g just messing with the brackets.
Here is what I tried.
$.ajax({
url: 'inc/grab_talk.php?name='+encoded_name+'&loc='+encoded_address+'&lat='+encoded_lat,
type: 'post',
success: function () {
$.ajax({
url: 'inc/talk_results.php',
type: 'post',
success: function (dat) {
alert(dat);
}
});
}
});
I am receiving '500 (internal server error) in console
Try this, you can use either POST or GET, but in your case GET seems to be more appropriate.
$.ajax({
type: "GET",
url: "some.php",
data: { name: "somename", location: "somelocation" },
success: function(){
$.ajax({
type: "GET",
url: "someother.php",
success: function(){
alert('test');
}
});
}
});
Check this example
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page='+btn_page,
success: function(data){
$.ajax({
var a=data; //edit data here
type: "post",
url: "example.php",
data: 'page='+a,
success: function(data){
});
});
I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?
AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.
Edit Callback version
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
You can now do the code inline using a callback function:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
or
getAjax(function(response) {
alert(response);
});
or whatever.
The code inside the anonymous function call will be processed when the AJAX request is complete.
There are two ways to taggle this. one is to use the success callback:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
the other is to set async to false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
Important note on non async:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Why don't you return the response to another function in the success callback. This should handle your need for different responses:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
That way you can create if statements / other alternatives to continue to use the same AJAX command for different results
You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}