I have a script that makes two ajax calls - the second being contained within the success handler of the first.
However I need to use the data captured within the first success handler as a further variable to pass in the second ajax call and then use that variable within the php file that is undertaking the server side processing.
This is all very new to me, so I hope this makes some sort of sense. If anyone could assist that would be great.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id'+lead_id,
data: $('form').serialize(),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I think you lose a "=" sign in the code:
url: 'processtwo.php?lead_id='+lead_id,
You're going to want to split these into two separate functions and allow for a parameter to be passed to the second. Not really part of your question, but should make it much easier to read. The second process seems to be missing an equals sign in the url parameter which will cause it to not work
function processOne() {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function(data) {
//alert("success data from processone is " + data);
//console logs are better to use when debugging data
console.log('SUCCESS DATA', data);
var lead_id = data;
processTwo(lead_id);
}
});
}
function processTwo(lead_id) {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id=' + lead_id,
data: $('form').serialize(),
success: function(data2) {
alert("success data from processtwo is " + data2);
}
});
}
If you're still not getting anything make sure the data is directly returning the lead_id. AJAX calls commonly return JSON data, so it very well might be something like data.lead_id or something like that. Alerts aren't useful for showing this so you could use the console log, console.log('SUCCESS DATA', data) to dig into the return data.
Given the reply to my comment, and making the assumption that the data returned from the first AJAX call is a simple string value (if it's not, you can still use the code here to see how you need to do what you need to do). jQuery's serialize() returns a string (see https://api.jquery.com/serialize/) so you can just append to that.
Also, you are missing your = sign when making your URL, so if you are trying to get the lead_id as a GET var, that's why it's not working.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
// you are missing the equals sign here, which is why this doesn't work as a GET
url: 'processtwo.php?lead_id'+lead_id,
// here we tack on a lead_id variable to the serialized form and give
// it the value you got back from query 1
data: ($('form').serialize() + "&lead_id=" + lead_id),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
Related
Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
I would like to send a GET request with only one parameter from an input form via AJAX, using jQuery.ajax().
To simplify things, instead of
data: $("#the_form").serialize()
I tried to explicitly pass the value of the input:
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: {
tx_search_pi1['sword']: val
},
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
Now this breaks because of the brackets and quotes in
tx_search_pi1[sword]: val
(which is required by the recipient of the get request)
How do I escape the brackets (and maybe also single quotes inside= correctly?
I've tried-and-errored many combinations, eg. with
tx_search_pi1%5Bsword%5D
encodeURIComponent("tx_kesearch_pi1[sword]")
etc...
You can try this,
data: $("#the_form").serialize()+'&sword='val,
Full Code,
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: $("#the_form").serialize()+'&sword='val,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
And if you want to pass sword value then use,
data: {'sword':val}, // get using sword key
As per #Urs Comment the code should be,
// let it is initialised before,
// and it is an object like {}, tx_search_pi1 = {key:"1",...};
function lookupSearch(val){
tx_search_pi1['sword'] = val;
$.ajax({
type: "get",
url: "/search",
data: tx_search_pi1,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
try putting tx_search_pi1['sword'] this in a variable and pass it.
Like
var temp = tx_search_pi1['sword'];
And pass temp
I was hoping that someone may be able to give me a pointer on how to achieve the following.
Currently, I have:
A JS function: A jQuery AJAX query that will get items from a SharePoint custom list.
A JS function: it will put the list results in to a datatable.
A JS function, that can turn an InitatorId into the real name of a user (GetDisplayName).
function GetDisplayName(userid) {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : GetDisplayNameSuccess,
error : GetDisplayNameFail
});
}
function populateMyOutstandingItems() {
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function() {
SP.SOD.executeFunc("sp.runtime.js", "SP.ClientContext", function() {
var context = SP.ClientContext.get_current();
var queryUrl = "https://companyname.sharepoint.com/subsite/_api/Web/Lists/getbytitle('Read%20Requests')/GetItems"; //change the Url
var camlXML = "<Query><Where><And><Eq><FieldRef Name='ReaderId' LookupId='True' /><Value Type='Integer'>" + _spPageContextInfo.userId + "</Value></Eq><Neq><FieldRef Name='Read' /><Value Type='Text'>YES</Value></Neq></And></Where></Query>"
var requestData = { "query" :
{"__metadata":
{ "type": "SP.CamlQuery" }
, "ViewXml": camlXML
}
};
return jQuery.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
},
success: onQuerySuccessMyOutstandingItems,
error: onQueryErrorMyOutstandingItems
});
});
});
}
function onQuerySuccessMyOutstandingItems(data) {
var jsonData = data.d.results
console.log(jsonData)
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
{ data: "Document_x0020_Name" },
{ data: "Document_x0020_Library_x0020_Nam" },
{ data: "Request_x0020_Made_x0020_Date" },
{ data: "InitatorId" },
{ data: "Request_x0020_ReadBy_x0020_Date" }, ],
order: [[3, "asc"]]
} ); }
At the moment, in the datatable, I have the InitatorID (ie. 30) but I would like to have the real name of the user in the table.
I understand some type of recursive AJAX query will be needed, but I'm not sure what the best way forward would be to achieve this, and was hoping that someone would be able to point me in the right direction.
After reading a bit about chained requests, I tried the code below, but it's wrong I guess, since Chrome complains of an 'unexpected ending':
var request = $.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
}
}),
chained = request.then(function( data ) {
return $.ajax( spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + data.InitatorId + ")",
{ data: { user: data.Title }} )
});
chained.done(function( data ) {
console.log(data)
});
In short, what is the best to achieve what I'm trying to do?
Many thanks
Glen
I am not sure I completely understand what you're asking, so here's my best guess at the scenario (please correct me if I am wrong)
Make an AJAX call to get a list of items from a SharePoint custom
list, but alas, one of the columns in this list has an InitatorID instead of a user name.
To fix this, we want to make another AJAX call that will get a list of usernames for a matching set of InitatorIDs we just retrieved.
Once we have that, we want to put the data in a dataTable for display.
Without knowing the details, I would just do nested AJAX calls. Basically, once the first call is done, call the second AJAX function. Once that one is done, update the dataTable. Something like:
$.ajax({
url: MY_FIRST_URL,
data: myFirstData
}).done(function (data) {
// The first call gets completed after some time and the 'done' function is called.
// here, extract the various InitatorID values, and pass them to the
// second AJAX call, so you can then get the usernames for those Ids
var initatorIds = // ... do data massaging here to get the initatorIds
// into the format you want from the 'data' variable
// passed in the done function...
$.ajax({
url: MY_SECOND_URL,
data: initatorIds
}).done(function (data2) {
// once the SECOND call is complete, populate the dataTables
var jsonData = // ... some manipulation of data and data2 results
// to get the combined output you want.
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
....
....
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the second call fails
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the first call fails
});
And at the risk of over-complicating the solution, I'd personally look to load the data directly into the table via the ajax functionality found within the dataTable plugin (read more about that here). But definitely if it minimizes confusion to lay it out as above, do that first!
I'm passing in authorization headers elsewhere, so I've gotten past that problem. If I alert(data) I get an object[Object], but am at a loss as to how to extract the data from that object. Any help would be greatly appreciated! Thanks!
var albumAPI = "https://api.imgur.com/3/album/" + albumID + "/images";
$.ajax({
url: albumAPI,
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data[0].link);
},
error: function() { console.log("ERRORZ"); },
beforeSend: setHeader
});
If you look at the data, it contains a property called data which is an array - so get the link to the first image
alert(data.data[0].link);
I am trying to implement Repository pattern in JavaScript. I have ViewModel which i want to initialize with the data when i call Initialize method on it. Everything seems to be falling in places except that i am not able to return the data from my AJAX call. I can see that data is coming back from the ajax call but when i trying to capture the data in SomeViewModel's done function, it is null.
Can someone please point me out where i am going wrong here?
P.S: Please notice that i am not making Async call so the call chain is properly maintained.
This is how my Repository looks like:
function SomeRepository(){
this.LoadSomeData = function loadData()
{
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
return data;
},
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
}
};
This is how my ViewModel looks like:
function SomeViewModel(repository){
var self = this;
var def = $.Deferred();
this.initialize = function () {
var def = $.Deferred();
$.when(repository.LoadSomeData())
.done(function (data) {
def.resolve();
});
return def;
};
}
This is how i am calling from an aspx page:
var viewModel = new SomeViewModel(new SomeRepository());
viewModel.initialize().done(alert('viewmodel initialized'));
alert(viewModel.someProperty);
I have used successfully an auxiliar variable to put the ajax result, when ajax call is inside a function (only works if ajax is async=false) and i need the function does return the ajax result. I don't know if this is the best solution.
function ajaxFunction(){
var result='';
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
result=data;
},
error: ajaxFailed
});
return result;
}
Doesn't matter that it's synchronous (though it really shouldn't be). Returning a value from inside the ajax callback will not cause the value to be returned from the containing function.
Using asynchronous ajax is generally a much better idea anyway, but that will force you to create an API that allows its clients to pass in handlers to be called when the ajax request completes. To do that, you'd give your "LoadSomeData" function a parameter. A caller would pass in a function, and your ajax "success" handler would pass on the results (or some transformation of the results; depends on what it is that you're doing) to that callback. It's the same idea as the callbacks used in the ajax call itself.