I have a ajax function in index.php which calls on the page thread.php which returns a JSON response(array). I basically want to parse through that array, display it in a particular html format, take the last value of the last row of that array and send it back in the same ajax call previously mentioned. So that ajax is basically a loop.
function returnValue()
{
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
var dateposted = results[5];
}
}
}
}
});
}
The stored value dateposted needs to be sent as an input when making the ajax call. The default value of dateposted will be 0.
I am not sure if this can be done. I am open to suggestions.
You can make this a lot simpler, you don't need to use the extended GET syntax:
var returnValue = (function() {
var dateposted = 0;
return function() {
$.get("thread.php", { "lastposted": dateposted }, function(result) {
// display your chats
dateposted = result[result.length-1][5];
}, "json");
}
})();
One simple way to your problem is declaring dateposted with a default value outside the function call and use it in the loop to store to store the last value. And have a new Ajax function call. I hope this is want you want.
function returnValue()
{
var dateposted=0;
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
dateposted = results[5];
}
}
}
}
});
}
Related
I want to send an array in Ajax data request, but I the output that I get display items[..], How to get rid of it, so I can only fetch variable inside it?
var columnName = 'accountLedgerID';
var gridDataArray = $('#grid').data('kendoGrid').dataSource.data();
var items = {
method: "updateSequence",
this_propertyID: $('#thisPropertyID').val(),
this_length: gridDataArray.length,
};
for ( var i=0; i < gridDataArray.length; i++ ) {
items["sequence_" + i] = i;
items["accLedgerID_" + i] = gridDataArray[i][columnName];
}
$.ajax({
url: "./getLedgerManagement.php",
type: "POST",
data: {
//items - display a same result as below
items:items
},
sucess: function(data){
console.log('success')
}
});
I expect it return data like this.
method: "updateSequence"
this_propertyID: "1"
this_length: 23
sequence_0: 0
accLedgerID_0: "LA26"
sequence_1: 1
accLedgerID_1: "LA8"
sequence_2: 2
accLedgerID_2: "LA29"
sequence_3: 3
accLedgerID_3: "LA2"
.....
I have
var prosjeci = [];
var parametar = $("#parametar1").val();
Function for getting data from server:
function podatciPrethodniDan()
{
$.ajax({
type: "POST",
url: "php/getPreviousDayData.php",
dataType: "json",
data: {parametar: parametar },
success: function(data)
{
obradiPodatkePrehtodnogDana(data);
}//end of success
});//end of ajax
}
Function which fill array with data:
function obradiPodatkePrehtodnogDana(data)
{
var stanica1Prosjek = 0;
var stanica2Prosjek = 0;
var stanica3Prosjek = 0;
var stanica4Prosjek = 0;
console.log(data);
for(i=0; i<data.length; i++)
{
if(i<24)
{
stanica1Prosjek = stanica1Prosjek + parseFloat(data[i].par);
}
else if(i>=24 && i<48)
{
stanica2Prosjek += parseFloat(data[i].par);
}
else if(i>=48 && i<72)
{
stanica3Prosjek += parseFloat(data[i].par);
}
else
{
stanica4Prosjek += parseFloat(data[i].par);
}
}
prosjeci.push(stanica1Prosjek/24);
prosjeci.push(stanica2Prosjek/24);
prosjeci.push(stanica3Prosjek/24);
prosjeci.push(stanica4Prosjek/24);
}
Results of console.log(data):
(only first elment)
Array[96]
0:Object
datum:"2016-10-31"
par:"60"
stanica"1"
Call function
podatciPrethodniDan();
Print out array:
console.log(prosjeci);
console.log(prosjeci[0]);
I get all data succesfull and i fill array sucessfull but i can't to access array element.
Results of first console.log:
Array[4]
0:60.44999999999999
1:76.41666666666667
2:85.3875
3:82.47083333333335
length:4
Results of second console.log:
undefined
I cant access arrays element?
I have a script, below, and when the page loads I get an error message: Cannot read property 'length' of undefined, so I researched the error and found that the AJAX request wasn't executed. If I execute the same code in the browser console, the script works fine. What's wrong with my code?
<script>
function getCitiesList() {
var country_id = '189';
return $.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
});
}
function getCitiesList2() {
var bla = getCitiesList();
console.log(bla['responseJSON']);
var i = 0;
var data = [];
while (i < bla['responseJSON'].length) {
data[i] = {};
data[i]['id'] = bla['responseJSON'][i]['id'];
data[i]['text'] = bla['responseJSON'][i]['title'];
i++;
}
console.log(data);
}
$('#city').select2({
data: getCitiesList2(),
width: "100%"
});
</script>
Since JavaScript is asynchronous language, it just keeps running and doesn't wait for AJAX to return result.
In your code, the first line of getCitiesList2 function assigns the return value of an AJAX call. The AJAX returns later, and var bla doesn't yet have the response. To solve this, you can pass a callback to your AJAX function getCitiesList and execute it on AJAX success.
function getCitiesList(callback) {
var country_id = '189';
$.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
success: function(result) {
callback(result);
}
});
}
function getCitiesList2() {
getCitiesList(function(result) {
var i = 0;
var data = [];
while (i < result['responseJSON'].length) {
data[i] = {};
data[i]['id'] = result['responseJSON'][i]['id'];
data[i]['text'] = result['responseJSON'][i]['title'];
i++;
}
});
}
The problem is that console.log(bla['responseJSON']); in getCitiesList2 is executed before the ajax response is received. And after var bla = getCitiesList(); assignment, bla basically holds a deferred object. All you need to do is to assign a callback function that is going to be executed once the ajax call returns.
<script>
function getCitiesList() {
var country_id = '189';
return $.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
}).done(function(data){
$('#city').select2({
data: processCitiesResponse(data),
width: "100%"
});
});
}
function processCitiesResponse(data)
{
console.log(data);
var i = 0;
var options = [];
while (i < data.responseJSON.length) {
options[i] = {};
options[i].id = data.responseJSON[i].id;
options[i].text = data.responseJSON[i].title;
i++;
}
console.log(options );
}
</script>
first and second answer doesn't help, the same problem.
This work:
<script>
var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');
function Blabla(){
var country_id = '189';
$.ajax({
type: 'get',
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
success: function(bla){
var i = 0;
var data = [];
while (i < bla.length) {
data[i] = {};
data[i]['id'] = bla[i]['id'];
data[i]['text'] = bla[i]['title'];
i++;
}
$('#city').select2({
data: data,
width: "100%"
});
}
});
}
Blabla();
</script>
Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});
I have a following javascript program:
function jQueryFunction(url, callback)
{
$.ajax
({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
return callback(json);
}
});
}
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(url[i], function(json){
jsonArray[i] = json;
});
}
//process jsonArray
However, when I check jsonArray after the for loop, it is null. So my question is that how to store the return value from jQueryFunction to jsonArray in for loop and then process it?
I have tried $.when.apply($,jsonArray).done(function) but still the same, it is null.
A simple way:
function doTheAjax(url, callback) {
return $.ajax({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler"
});
};
var reqs = [];
for(var i = 0; i < 10; i++) {
reqs.push(doTheAjax(url[i]));
}
// send the array of requests to when, which will fire `done`
// when it's, well, done
$.when.apply($.when, reqs).done(function() {
$.each(arguments, function(data) {
// process the data
});
});
alternatively, make a bunch of requests and put them into jsonArray, but keep
track of how many you're making. When they all complete, you have the array. Create your
own deferred, resolve it yourself when the counter is up, and return the promise.
var getJSON = function(url) {
var dfd = $.Deferred();
var count = 0;
var total = 10;
var jsonArray = [];
for(var i = 0; i < total; i++) {
doTheAjax(url[i]).done(function(json) {
jsonArray.push(json);
count++;
if ( count >= total ) {
dfd.resolve(jsonArray);
}
});
}
return dfd.promise();
};
getJSON().done(function(theCreatedJsonArray) {
// do stuff
});
I'm not sure why the answer to your previous question (using deferreds) didn't work. But the cause of your problem is that you are checking the array before any of the ajax responses arrived. You also have a problem with i referencing the same value on all callbacks.
One simple workaround, if you know how many responses you're expecting:
var arr = [];
for(var i = 0; i < 10; i++){
jQueryFunction(url[i], function(json){
arr.push(json);
if(arr.length == 10) {
// All 10 responses arrived!
// DO STUFF FROM HERE
// e.g., call another function
console.log(arr);
}
});
}