Ajax call within jquery each loop - javascript

Here is a function that I have to write to an xml file through an ajax call. The code works fine the first time the ajax call is made. On the second each loop, the ajax call isn't made at all. I don't know why. I specified asyn to false. That did not help. That doesn't seem to be the problem anyway.
$('#'+divid).children('div').children('div').each(function () {
var url = $(this).find('a');
var urlname = url.text();
var urllink = url.attr('href');
var urlid = $(this).attr('id');
alert ("from javascript urlid: "+urlid+" urlname: "+urlname+" urllink: "+urllink);
$.ajax({
url: "add_url.php",
type: "POST",
data: { nodeid: divid, urlid: urlid, urlname: urlname, urllink: urllink },
cache: false,
async: false,
success: function (response) {
if (response != '')
{
alert(response);
}
}
});
});

This really works for me
http://jsfiddle.net/genesis/DTjZQ/4 (3 POST request sent with response status 404)
be sure that your html is good and with same structure as in my fiddle

Instead of making multiple AJAX requests, I suggest appending the data to an array and then sending the entire array of objects.
(Basically the literal object you're using for data would be appended to an array instead of used in a request, and then once the each is done, you would send the array as the data.)

Related

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

Issues passing form data to PHP using Ajax

I originally had a regular HTML form that submitted the data entered through a button, which redirected the user to the PHP code page ran the code and everything worked.
Since everything now is confirmed working I need to pass the variables in the form to PHP using Ajax instead to keep the user on the original page.
All of my code checks out everywhere except for any Ajax request I use in the below function. The function correctly grabs all the variables from the form but no matter what form of Ajax or $.post that I use it fails to pass anything.
I am trying to pass all data to http://localhost/send-email.php and respond to the user with a pop up including the echo response from the PHP code.
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
function capacity(){
var fullname = document.getElementById("fullname").value;
var time = document.getElementById("time").value;
var aux = document.getElementById("aux").value;
var issue = document.getElementById("issue").value;
var issueid = document.getElementById("issueid").value;
var reason = document.getElementById("reason").value;
}
Like I said I read all documentation on Ajax and followed many examples on here but i could not get anything to work. Any help on what my Ajax call should look like is appreciated.
There are a couple of different ways you can POST in the backend.
Method 1 (POST Serialize Array from Form) -
jQuery.post()
$.post('/send-email.php', $('form').serializeArray(), function(response) {
alert(response);
});
Method 2 (Structure Object and POST Object) -
jQuery.post()
var formObject = {
fullname: $('#fullname').val(),
time: $('#time').val(),
aux: $('#aux').val(),
issue: $('#issue').val(),
issueid: $('#issueid').val(),
reason: $('#reason').val()
};
$.post('/send-email.php', formObject, function(response) {
alert(response);
});
Method 3 (Use AJAX to POST Serialize Array from Form) -
jQuery.ajax()
$.ajax({
method: 'POST',
url: '/send-email.php',
data: $('form').serializeArray(),
}).done(function(response) {
alert(response);
});
Method 4 (Use AJAX to POST Form Data) -
jQuery.ajax() - FormData Objects
var formData = new FormData();
formData.append('fullname', $('#fullname').val());
formData.append('time', $('#time').val());
formData.append('aux', $('#aux').val());
formData.append('issue', $('#issue').val());
formData.append('issueid', $('#issueid').val());
formData.append('reason', $('#reason').val());
$.ajax({
url: '/send-email.php',
dataType: 'json',
contentType: false,
processData: false,
data: formData,
type: 'POST',
success: function(response) {
alert(response);
}
});
Virtually, there are many different methods to achieving what you are attempting.

how to send data from one web page to another?

I don't how to ask this question but if their are duplicates send me that. Their are several .php files i have made
content.php, show.php and showFilteredResult.php .
content.php sends the start date and end date to the show.php and it returns the the orderIds which are of that date
$(document).ready(function () {
var srt = $("#cal1Date1").val();
var end = $("#cal1Date2").val();
$.ajax({
url: "http://localhost/show.php",
data: {
srt: srt,
end: end
},
type: "POST",
dataType: "json",
complete: function (response) {
$rtndata = response.responseText;
var dat1a = jQuery.parseJSON($rtndata);
var result = dat1a.OrderID;
console.log(result[0]); // send this result
}
});
});
now I want to send this $result with orderids to showFilteredResult.php where then i can make tables etc.
I'd skip the AJAX and just use request parameters (GET or POST).
cal1Date1 and cal1Date2 are input fields I assume. Wrap them in a form and post the values to a PHP form handler that could handle the lookup and display. No need for the AJAX middle-man here.
Just make a similar Ajax request to showFilteredResult.php I would have them in a separate function.
function showFilteredResult($result){
$.ajax({
url:"http://localhost/showFilteredResult.php",
data: {
result:$result
},
type:"POST",
dataType: "json",
complete:function(response){
$rtndata=response.responseText;
var dat1a=jQuery.parseJSON($rtndata);
var result=dat1a.OrderID;
console.log(result[0]);// do something with the data returned from showFilteredResult.php
}
});
}
and from the request that you have just call that funciton like
... $rtndata=response.responseText;
var dat1a=jQuery.parseJSON($rtndata);
var result=dat1a.OrderID;
console.log(result[0]);// send this result
showFilteredResult(result[0]);
}
});
Instead making another request to server , you have another option to do that. Let's say you get orderId from show.php before sending back , right ? Then you can use this orderId to do what u want such as query which u have written in showFilteredResult.php . then return back to client for final result . In that way you can eliminate the unnecessary http request.

Waiting for a function to return a value before firing jQuery Ajax request

I'm trying to fire an Ajax request with some data being returned by a function call and, as far as I can tell, the Ajax call isn't waiting for my function call to return.
I'm calling getSelectedMessages to get the values of a variable number of checkboxes before firing an Ajax request with an array of the values returned by getSelectedMessages.
getSelectedMessages looks like this:
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
And the Ajax request that's invoking it looks like this:
$.ajax({
type: "POST",
url: "/api/messages/",
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
I've done a little bit of searching around and all I'm turning up are answers on how to return a value from a call and to it.
use
beforeSend attribute with ajax
try
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
$.ajax({
type: "POST",
url: "/api/messages/",
beforeSend : function () { return jQuery.isEmptyObject(getSelectedMessages); }
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
Reference
beforeSend
isEmptyObject
Call getSelectedMessages() outside the ajax function of jquery (?)
The function is executed before the request is sent.
The real problem is that the getSelectedMessaged() returns an array.
This results in undefined=undefined after serialization in jQuery's internals.
And that gets ignored by the $.ajax(), so it looks like it's not sending in your vars but it's ignoring them because they're undefined.
If you concatenate a string with the values and make it a query string parameter yourself it should work.
I assume you want to send something like ?var[]=something&var[]=somethingelse to the server, so it ends up in PHP as an array?
Than you'll have to build up the string yourself in the getSelectedMessages function.
Hope it helps,
PM5544

Javascript function not returning properly?

function IsSwap()
{
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>";
var id =
{
id : GetGUIDValue()
}
$.ajax({
type: "POST",
url: urlString,
data: id,
success: function(data) {
if (data.toString() == 'SwapModel')
{
return true;
}
}
});
Expected result is true. I can alert right before the return so I know it's getting to that point fine. In another function, I tried to get my bool and use it like this:
var isSwap = IsSwap();
if (isSwap)
and it keeps saying isSwap is undefined. Why?
You are using ajax requests, which are asynchronous. You can't return value from an ajax request. Try this instead:
function IsSwap()
{
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>";
var id =
{
id : GetGUIDValue()
}
$.ajax({
type: "POST",
url: urlString,
data: id,
success: function(data) {
if (data.toString() == 'SwapModel')
{
ResultIsTrue(); // call another function.
}
}
});
After execution, instead of using this:
var isSwap = IsSwap();
if (isSwap){
// Do Somethinh
}
Try that:
IsSwap();
function ResultIsTrue(){
// Do Same Thing
}
You can't return from an ajax call like that.
Essentially what you're doing is returning true from the inner function.
You should just call whatever code you need in the success method as that's the only time you can guarantee that the ajax call has completed.
The AJAX request is asynchronous, meaning that IsSwap will return before the response to the AJAX request.
Whatever you need to do based on isSwap, you should do in the success handler of your AJAX request.
UPDATE: This last paragraph is incorrect about it working, but worth noting about synchronous not being recommended:
Alternatively, you could make the AJAX request synchronous (by adding async:false to the AJAX options) and keep it how you have it - however I wouldn't recommend this as your browser will 'freeze' whilst it waits for the response.
Check this line:
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>";
Try using single quotes like so:
var urlString = '<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>';
Your double quotes inside double quotes is most likely your problem.

Categories