0

How can I pass variables in loop to a PHP file using AJAX?

var lat;
var lng;
var array = [ 22.399602, 114.041176, 22.344043, 114.0168, 22.327529, 114.087181 ];
console.log(array);
for (var i = 0; i < 6; i += 2) {
    lat = array[i];
    console.log("lat" + i + "=" + lat);
    for(var j = i + 1; j <= i + 1; j++) {
        lng = array[j];
        console.log("lng" + j + "=" + lng);
    }
}

My array is here:

enter image description here

In this case I want pass each lat and long to my database. My database will looks like this:

username: Neo
lat=22.399602
long=114.041176
lat=22.344043
long=114.0168
lat=22.327529
long=114.087181

I also test this AJAX function but it isn't working for an array.

$.post('send.php', { latitude: lat, longitude: lng }, function(data) {
    $('#result').html(data);
});

What should I do now?

5
  • for(var j=i+1; j<=i+1;j++) what's this for Commented Nov 16, 2015 at 14:17
  • How do you populate the array initially? Commented Nov 16, 2015 at 14:19
  • it's get lat, long from array. Array included both lat and long. 1st loop get lat, and second loop is get only longitude. Commented Nov 16, 2015 at 14:20
  • what error did $.post() give you? Commented Nov 16, 2015 at 14:25
  • i didn't use array send to php file using $.post() how to pass it Commented Nov 16, 2015 at 14:30

2 Answers 2

0

if you are certain that array will contain latitude and longitude one after the other then you don't need a nested loop.

var lat;
var lng;
var array = [22.399602,114.041176 , 22.344043,114.0168 , 22.327529,114.087181];
//console.log(array);
for(var i=0;i<array.length;i+=2)
{
    lat=array[i];
    long = array[i+1];
    console.log(lat+"    "+long);
    $.post('send.php', {latitude:lat, longitude:long}, 
    function(data)
    {
        $('#result').html(data);
    });
}
0
0

If you were to structure your initial array in a more logical manner the problem would be much simpler for you. Consider:

function sendlatlng(lat,lng){
    var http=new XMLHttpRequest();
    http.onreadystatechange=function(){
        if( http.readyState==4 && http.status==200 ) console.info( http.response );
    };
    var headers={
        'Content-type': 'application/x-www-form-urlencoded'
    };
    http.open('POST', '/send.php', true );
    for( header in headers ) http.setRequestHeader( header, headers[ header ] );
    http.send( 'lat='+lat+'&lng='+lng );
}



var array = [ [22.399602, 114.041176], [22.344043, 114.0168], [22.327529, 114.087181] ];

for( i=0; i < array.length; i++ ){
    lat=array[ i ][ 0 ];
    lng=array[ i ][ 1 ]
    console.log( 'lat: %s lng: %s',lat,lng );
    sendlatlng.call( this, lat, lng );
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.