I am sending Ajax request to php page using Javascript.
My main goals is to send ajax request to PHP page and get the response which I have done that already.
The problem is when the Ajax send back the response the Javascript cannot send this to HTML properly.
Look at my code so you can understand clearly.
Javascript code:
function get_rental_fee(){
var count_model = $('#count_model').val();
for(var i =0; i < count_model; i++){
var hours = $('#hours').val();
var modelid = $('#modelid_multi'+i).val();
var get_tax = $('#get_tax_multi'+i).val();
var get_counter = $('#get_counter_multi'+i).val();
var myData = "hours="+hours+"&modelid="+modelid+"&get_tax="+get_tax;
jQuery.ajax({
type: "POST", // Post / Get method
url: "get_rental_fee.php", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
var result = response.split('|');
document.getElementById('rental_price_multi'+i).value=result[0];
document.getElementById('tax_multi'+i).value=result[1];
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
}
}
The problem is here:
document.getElementById('rental_price_multi'+i).value=result[0];
document.getElementById('tax_multi'+i).value=result[1];
The loop runs 3 times and Php is sending me back the response 3 times. But in Javascript Theses 2 lines are only showing VALUES of 3rd Times not 1st and 2nd.
But I am receiving response of all 3 times.
Also when I run the code the javascript returns back an error:
Uncaught Type Error: Cannot set Property 'value' of null
Please help me where I am doing wrong
Problem is $.ajax is by default async: true, so the value of i in loop is not the desired value when it reaches success.
You can simply make the ajax sync:
$.ajax({
async: false,
...
})
Edited:
If you still want to it to be async, you need to use closures.
for(var i =0; i < count_model; i++){
(function(i){// closure `i`
$.ajax({
type: "POST",
...
});
})(i);//<-- for loop `i`
}
Your problem is that i inside the callback no longer has the value it did when you registered the callback. This is a very common problem.
A common solution is to "close over" the variable i so that it retains the correct value:
success: (function(i) {
return function(response) {
var result = response.split('|');
document.getElementById('rental_price_multi'+i).value=result[0];
document.getElementById('tax_multi'+i).value=result[1];
})(i)
The outer function is passed i as a parameter, at which point its value in the inner callback function becomes fixed.
Related
Basically, I am trying to debug a code that was written long back by someone.
I have a jsp which is calling a javascript function on click of a button. In the javascript there is an ajax call happening to the Struts Action class. The Action class returns an Array List of objects to the jsp. My Array List has an inner list of objects too. Everything works fine when the list is small. But when the returned list is big, the ajax variable "data" returns as empty after a long time.
i think it is something to do with handling large data in the response. When i googled a few forums, i think the size of the response is exceeding a maximum limit and then returned as empty. When the response is small the variable "data" returns with a html reponse. But when it is huge, the variable has nothing.
Below is the ajax call. Since this is happening in production right now, any quick help is really appreciated. BTW, i am using Websphere 8.5.5.
function submitCriteria(submitSrc) {
var nameOfFormToPost = "criteriaForm";
var spanId = "resultDataSpan";
var formAsString = getFormAsString(nameOfFormToPost, submitSrc);
$.ajax({
type: "POST",
dataType: 'html',
url: "matchReconcileHome.do?execute=viewMatchResult",
data: formAsString,
success: function(data, textStatus) {
idx = data.indexOf("<title>XXXXXXX- XXXXX - Login</title>");
if (idx > 0 && idx < 500) {
window.location = "/pdrWeb/Login.jsp";
}
//Split the text response into Span elements
spanElements = splitTextIntoSpan(data, spanId);
//Use these span elements to update the page
replaceExistingWithNewHtml(spanElements);
$("#matchResult").treeTable();
setPageNavigation();
setResultControls();
//alert("Ajax called back Done" );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Problem with server response:\n " + textStatus + ", Error: " + errorThrown);
}
});
return false;
}
I have the following array
var arrayOfResults = []; // Results after like statement
I make a call to the database which returns me a json result as shown here:
[{
"id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}",
"pid": "{34214CCB-90C3-4D75-958B-5A1D0FBDD971}",
"ttl": "Easter Bunny",
"img": "/~/media/Images/Recipes/Easter/Filled Pasta/LF_Baked-Spring-Vegetables-Ravioli_920.ashx?h=910\u0026w=910",
"url": "Some url",
"taggedwith": ["{3A54907D-4171-4F4E-8FE8-3A38DA1E874F}", "{6CD78C6B-F435-45EC-BE16-810E80311C23}", "{74528A6F-C40B-4030-A278-A4C9A2F46A47}", "{6DC82B78-61F6-45A0-A63C-EA590BB1057E}", "{E9EF1A41-51D0-403D-9373-37B7A880B251}"],
"articleddate": "2015-05-02",
"tname": "Recipe",
"rbrand": ["{1F6EDA5D-4681-40F0-B455-7C343AC25B72}"]
}, {
"id": "{2e4b04b6-334f-42e9-afd7-ddc4e08417ad}",
"pid": "{C611BAC8-E8E0-4693-920B-93BD5EE2386B}",
"ttl": "Latina Fettuccini \u0026 Summer Sauce with Prawns Recipe",
"img": "/~/media/Images/Recipes/Latina Fresh/Plain Pasta/LF_Fettuccini-Summer-Sauce-Prawns_920.ashx?h=910\u0026w=910",
"url": "Some url",
"taggedwith": ["{3A54907D-4171-4F4E-8FE8-3A38DA1E874F}", "{6CD78C6B-F435-45EC-BE16-810E80311C23}", "{74528A6F-C40B-4030-A278-A4C9A2F46A47}", "{6DC82B78-61F6-45A0-A63C-EA590BB1057E}", "{E9EF1A41-51D0-403D-9373-37B7A880B251}"],
"articleddate": "2015-05-02",
"tname": "Recipe",
"rbrand": ["{1F6EDA5D-4681-40F0-B455-7C343AC25B72}"]
}]
On the UI I have a text field, which the user can enter free text.
I call the following ajax method when the user has entered roughly 5 characters, what I'm trying to achieve is I want to perform a like statement on the ttl field within the above array, If the ttl field matches or is like the freeText the user has entered then I want to push that item in to the array 'arrayOfResuts' however I see the alert message found yet it doesn't push the item into the new array, I know this because I alert the length at the end of the ajax call and its 0;
var addItem = false;
var freeText = $('#searchKeywords').val();
$.ajax({
url: 'search?t=&s=DateDesc&type=globalsearch&q=',
type: 'GET',
dataType: 'json',
success: function (searchDataList) {
console.log(searchDataList)
for (var i = 0; i < searchDataList.length; i++) {
addItem = false;
if (freeText.length > 0) { // Filter on free text
if (searchDataList[i].ttl.indexOf(freeText) > -1) { // if title contains free text then we need to add it to the arrayOfResults[].
alert('found');
arrayOfResults.push(searchDataList[i]) // This doesn't seem to work.
addItem = true;
}
}
} // End of for loop
},
error: function (request, error) {
}
});
alert(arrayOfResults.length);
Now I'm not 100% sure what's actually going wrong, so any help would be appreciated.
Your alert is running before your AJAX request is complete.
Since the AJAX request is asyncronous the console.log() code runs before the success is called and so your not printing the result you want.
To print the results simply print within the success and error functions of the AJAX request. Doing so in the complete function will not help since it runs asyncronously from the others.
As the other answers mentioned you need to handle the data within the success block. You can do it directly like below, or for more complex cases call a new function to handle the data at the end of the success statement.
Update code:
var freeText = $('#searchKeywords').val();
$.ajax({
url: 'search?t=&s=DateDesc&type=globalsearch&q=',
type: 'GET',
dataType: 'json',
success: function (searchDataList) {
console.log(searchDataList);
for (var i = 0; i < searchDataList.length; i++) {
addItem = false;
if (freeText.length > 0) {
if (searchDataList[i].ttl.indexOf(freeText) > -1) {
alert('found');
arrayOfResults.push(searchDataList[i]);
addItem = true;
}
}
} // End of for loop
if (arrayOfResults.length > 1) {
alert(arrayOfResults.length);
console.log(arrayOfResults);
}
},
error: function (request, error) {
}
});
Your alert will always be 0 because AJAX is asynchronous (the A in AJAX stands for that) and you call your alert synchronously.
What happens is, the ajax request gets the data while the synchron code runs as usual. Now that the ajax request is done clearly after you call your alert it cannot log anything that makes sense.
If you want a function to be called when the asynchronous request is done, wheter it was successful or not, use done: additionally to success: and error:. This code will run when the request is done and show you the actual length.
I have an array noti_array which has two elements, noti_array[0]='meghan&3', noti_arra[1]='tylor&5', the username and number concatenated by '&', in each iteration, I want to send the username to a ajax request
for(var i=0;i<noti_array.length;i++)
{
var mesg_array = new Array();
mesg_array=noti_array[i].split('&');
who_sent=mesg_array[0]; //first iteration, meghan
sent_num=mesg_array[1]; //3
//send the user name to a ajax request
$.ajax({
url:'getLastCon.php',
method:'post',
data:{who_sent:who_sent},
success:function(data){
alert(who_sent);
}
});
}
this code above would not alert meghan and tylor, instead, it alerts twice tylor, and if I use a 'break' after the ajax request, it would alert meghan once only, I think it's probably the loop enter the next iteration even the ajax request have not completed
It looks like who_sent could be a global variable. In that case, because of the asynchronous nature of your AJAX calls, the alert would trigger for the last assigned value of who_sent. Make who_sent a local variable or add another variable by adding var: var who_sent = mesg_array[0];.
Edit:
The above is wrong on how variables persist in a loop. I'm sorry for the inaccurate info. The following code will do what you want:
for( var i=0 ; i < noti_array.length ; i++ ) {
var mesg_array = noti_array[i].split('&');
who_sent = mesg_array[0]; //first iteration, meghan
sent_num = mesg_array[1]; //3
(function(who) {
//send the user name to a ajax request
$.ajax({
url: 'getLastCon.php',
method: 'post',
data: { who_sent:who },
success: function(data) {
alert(who);
}
});
})(who_sent);
}
i have a recursive Ajax call that work properly (PhP script called do his job, recursion is working, everything is fine) EXCEPT that in between the ajax calls i try to update a input text value to show the progress and it only updates once the whole loop is done.
Why is the line
$('#start_'+code_regional).val(msg);
not executing ?
function addLeads(code_regional, phone_numbers_start)
{
var databases = [];
var file = document.getElementById('file_'+code_regional).files[0];
var formData = new FormData();
formData.append('selectedDatabases', JSON.stringify(databases));
formData.append('code_regional', code_regional);
formData.append('phone_numbers_start', phone_numbers_start);
formData.append('phone_numbers_end', $('#end_'+code_regional).val());
formData.append('filePath', file);
$.ajax({
type: 'POST',
url: 'execute.php',
data: formData,
processData: false,
contentType: false,
success: function(msg){
$('#start_'+code_regional).val(msg);
if(msg < $('#end_'+code_regional).val())
{
addLeads(code_regional, msg);
}
else
{
$('#start_'+code_regional).val($('#end_'+code_regional).val());
}
}
});
}
If msg is an integer, you should compare integers instead of strings:
if( parseInt(msg,10) < parseInt($('#end_'+code_regional).val(),10) )
If it's still failing, try to add a console.log(...) before and after the test to know what's going on.
What do you mean in between the ajax calls? The code tells me, "if msg is less than y, call addLeads again, otherwise update the start field". So that's not tracking progress, the start field is only updated at the end. If you want to always update, move the update line outside the conditional.
Can someone tell why my object img is not accepting its value outside the ajax call? I've also used a constructor function to create the object but that did not work as well. And the xml parsed values work, I've tested this. If i move the alert(img.location) inside the success event the correct value will show, but it will not outside the ajax function..
Help please...
function getImage(){
img = new Object();
$.ajax({
type: "GET",
url: "hvimage.xml",
dataType: "xml",
success: function(xmlData){
var randImageId = Math.floor(Math.random()*3);
$(xmlData).find("image").each(function(index, e){
if(index == randImageId){
img.id = $(this).attr("id");
img.location = $(this).find("location").text();
img.answer = $(this).find("answer").text();
}
});
},
error: function(xmdData){
alert("error");
}
});
alert("test");
alert(img.location); //Keep getting undefined here..
}
Thanks again,
Wenn
Because your AJAX request is asynchronous, so the code that comes after it does not wait for the response before it runs.
Any code that relies on the successful response needs to be placed in, or invoked from within the success: callback.
function getImage(){
img = new Object(); // 1. create object
// 2. send request
$.ajax({
type: "GET",
url: "hvimage.xml",
dataType: "xml",
success: function(xmlData){
// 4. response is received, and callback runs
var randImageId = Math.floor(Math.random()*3);
$(xmlData).find("image").each(function(index, e){
if(index == randImageId){
img.id = $(this).attr("id");
img.location = $(this).find("location").text();
img.answer = $(this).find("answer").text();
}
});
},
error: function(xmdData){
alert("error");
}
});
// 3. fire alerts
alert("test");
alert(img.location); //Keep getting undefined here..
}
The reason you've having problems is that the code doesn't run in the sequence it seems you think it will.
The success function runs when the async request returns, whereas the last two alerts are triggered immediately after the request is sent. The data you want to use in those last two alerts simply isn't available to the browser yet.