0

I have a loop in javascript file to get variable, i send it in php to insert in SQL. The problem is that javascript doesn't wait that all informations are insert in SQL db. Is it possible to sync Javascript and php ?

Part of Js file :

while(i<myRoute.steps.length){

var path = myRoute.steps[i].path;

var trajet = path + ''; 

        var data = {
        var2: trajet    
  };  

  $.post("proc.php", data);

  i++;

}

proc.php :

<?php 

$var2 = $_POST['var2'];

$db = mysql_connect('127.0.0.1:3306', '***', '****')  or die('Erreur de connexion '.mysql_error());

mysql_select_db('tc',$db)  or die('Erreur de selection '.mysql_error()); 

$sql = "INSERT INTO ligne(Route) VALUES ('$var2')";

 mysql_query($sql) or die('Erreur SQL !'.$sql.'<br>'.mysql_error()); 

?>

1 Answer 1

1

You can use the third argument of $.post, which is a callback function once a response from the server is received.

var i = 0;
var sendData = function(){
   var path = myRoute.steps[i].path;

   var trajet = path + ''; 
   var data = {
        var2: trajet    
   };  

   $.post("proc.php", data, function(){
      if(i < myRoute.steps.length){
         i++;
         sendData();
      }
   });
}
sendData();
Sign up to request clarification or add additional context in comments.

Comments

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.