I'm trying to do a for loop 10 times and i wrote setInterval to call my function again but it does not work. My for loop turns only ten. So how can i do?
function randomThumbNews() {
for(var i=0;i<10;i++){
$.ajax({
type: "get", url: "Home/Oku", data: {},
success: function (data) {
$("#thumbNews_" + i).html(data);
}
});
}
}
setInterval(randomThumbNews, 3000);
Try something like:
$.ajax({
type: "get", url: "Home/Oku", data: {},
context: i, /* NEW - this value comes to your success callback as 'this' */
success: function (data) {
$("#thumbNews_" + this).html(data);
}
});
The problem is this -- when
function (data) {
$("#thumbNews_" + i).html(data);
}
Is called the loop has already finshed so i will always be 10.
You will only see results posted to one of your <div>s
This will fix it since function parameters don't have closure:
function ajaxAndSet(counter)
{
$.ajax({
type: "get",
url: "Home/Oku",
data: {},
success: function (data)
{
$("#thumbNews_" + counter).html(data);
}
});
)
function randomThumbNews()
{
for(var i=0;i<10;i++)
{
ajaxAndSet(i);
}
}
setInterval(randomThumbNews, 3000);
Related
I am a bit stuck with the below issue, my code is similar to this:
function (){
var myVar = myFirstAjaxFunction()
$.ajax({
url: myUrl + myVar
....
})
}
My first ajax function is returning a string that I would like to use in the end of my function, but I do not know how to wait for the first function to be done.
I hope this is clear, thanks for your help!
Here is an example:
$.ajax({
success: function (data) {
var a = data;
$.ajax({
data: 'data=' + a,
success: function (data2) {
}
});
}
});
Or you pass callback :
function myFirstAjaxFunction (callback){
$.ajax({
success: function (data) {
callback(data);
}
});
}
and usage :
myFirstAjaxFunction(function(data){
//call 2nd ajax
});
$.post(url1,{ params:myVar}, function(result) {
$.post(url2,{params:result}, function(final_result) {
//use final_result here... :)
});
});
I think you should take help of callback function, please look at the below code. will help you.
function myFirstAjaxFunction(callback){
$.ajax({
url: "demo_test.txt",
success: function(result){
return callback('your-string');
}
});
}
function (){
myFirstAjaxFunction(function(myVar){
$.ajax({
url: myUrl + myVar
....
})
})
}
Return the promise from the ajax call. Example snippet for your reference
function (){
myFirstAjaxFunction()
}
function myFirstAjaxFunction() {
$.ajax({
url: '',
success: function(response) {
//response of the first api call
secondApiCall(responseoffirst);
}
});
}
function secondApiCall(value) {
$.ajax({
url: '',
success: function(response) {
console.log(response);
}
});
}
You can use Async/Await:
async function (){
var myVar = await $.ajax({
url: firstAjaxCallUrl
....
})
$.ajax({
url: myUrl + myVar
....
})
}
what am I missing? I want to get a variable which is incremented in JavaScript and pass it to PHP via AJAX. Maybe you can help me with my code?
function increase()
{
var k=1;
k++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:k}),
success: function(response) {
content.html(response);
}
});
}
function decrease()
{
var k=1;
k--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:k}),
success: function(response) {
content.html(response);
}
});
}
This function should be triggered when I am pressing the button on an "onclick" event.
This variable which is "k" should be passed to inc/functions.php
$page = $_POST['page'];
echo $temp;
What am I doing wrong?
I need the variable because for use in the following MySQL statement.
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
The idea is : the user presses "next" then the JS is incrementing the variable by 1 passing it to my function where the "table" is getting to the next "site".
your increment variable should be outside the function, otherwise k is always 2
var ki = kd = 1;
function increase()
{
ki++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {'page':ki},
success: function(response) {
content.html(response);
}
});
}
function decrease()
{
kd--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {'page':kd},
success: function(response) {
content.html(response);
}
});
}
Try the below snippet for increment
var k = 1
function increase() {
var dataForAjaxCall = { page: k++ };
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: dataForAjaxCall,
success: function(response) {
content.html(response);
}
});
}
Similarly you can write for decrement also.
NB: Make sure you initialize the decrement counter variable outside of the function like given above
I am looking to store a value which is return by the AJAX function, here is the my code, in the AJAX success it is showing well, but when am storing that data which is saying undefined.
The following serviceNumber, which I am storing the enCrypt return value
var serviceNumber = enCrypt(typeofServiceNumber);// when am catching the function data which is saying "undefined"
the following code is my ajax function
function enCrypt(id) {
if (id > 0) {
$.ajax({
url: $("baseUrl").html() + "JobProfiles/Encryption",
type: "POST",
dataType: "json",
data: { Id: id },
success: function (encdata) {
return encdata;
},
error: function (data) {
$('#loading').hide();
}
});
}
}
Can you help me to know what is wrong in my code? Thanks in advance.
You can't use return like this, because the function is async + it's a function in a function...so actually yeah you cant return there xD
Just do something like:
enCrypt(typeofServiceNumber);
//and in your ajax:
success: function (encdata) {
go_on(encdata);
},
//and then
function go_on(serviceNumber)
{
//here you can use it :D
}
just add the
cache: false,
async: false,
to you ajax function
function enCrypt(id) {
var encnum;
$.ajax({
url: $("baseUrl").html() + "JobProfiles/EncodeIds",
type: "POST",
cache: false,
async: false,
dataType: "Json",
data: { Ids: id },
success: function (encdata) {
encnum = encdata;
},
error: function (data) {
$('#loading').hide();
}
});
return encnum;
}
The alert at the start shows "undefined", why?
The alerts come in this order:
"success!"
"Data" (what it should be)
"undefined"
I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!
Very grateful for any help!
I got this code
var data = getData("");
alert(data); <<<<<<< UNDEFINED
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
function processData(data) {
var arrData = CSVToArray(data);
dimensions = arrData[0];
var objects = [];
objects[0] = dimensions;
for (var i = 1; i < arrData.length; i++){
objects[i] = new Object();
for (var j = 0; j < dimensions.length; j++){
objects[i][dimensions[j]] = arrData[i][j];
}
}
return objects;
}
To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.
Your getData function doesn't return anything.
You need to return it from the function itself.
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.
function getData(fileName) {
var ourData = "";
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
ourData = arrData;
},
});
return ourData;
}
This returns the data from getData to whatever calls that function.
edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.
Preface: Don't use async: false. But answering the question:
getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.
To change it so getData returns something, you'd do this:
function getData(fileName) {
var arrData;
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
arrData = processData(data);
},
});
return arrData; // <=== Now `getData` returns something
}
But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
});
}
...called like this:
getData(function(data) {
alert(data);
});
...or a promise ($.ajax returns one, of sorts):
function getData(fileName) {
return $.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
}).then(data) {
return processData(data); // <== Becomes the resolution value of `getData`'s promise
});
}
and then
getData().then(function(data) {
alert(data);
});
data is undefined because the function getData doesn't return anything. You should have a look at promises.
I found this question which is almost exactly the same: Return value from nested function in Javascript
The problem is that the function is passed to jQuery's $.ajax function. Here's what i have:
function doSomething() {
// Do some stuff here
console.log(getCartInfo());
}
function getCartInfo() {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
return data; <------------- This
}
});
}
I need to return data to the doSomething function, if that makes sense. I tried to return the entire $.ajax function but that returned the whole object. Any ideas?
Send a callback function:
function getCartInfo(onSuccess) {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
onSuccess(data);
}
});
}
getCartInfo(function(data) {
console.log(data);
});
try this
function doSomething(date) {
........your data
}
function getCartInfo() {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
doSomething(data);
}
});
}