0

I want to add into mysql database the data from a javascript function:

for (var j=0; j < data.length; j++) {

        ......
        Cars[car.owner] = owner;

       <?php
        $sql = "INSERT INTO Cars (owner, year)
        VALUES 

    ?>
    }

I want to add into the DATABASE (Cars table), the owner and year that I receive from a "for cicle". Every time I do this "for cicle" I want to add the data into the database. Can you tell me how to do it using PHP?

1 Answers1

0

Create a PHP file where you have all the code to interact with the database. Then from your JS file make an AJAX call using POST or GET method.

Example:

This can be in your JS code

parameters = "url=" + yourJSObject;
    request = new XMLHttpRequest();
    request.open("POST", "yourPHPFile.php", true)
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded")
    request.setRequestHeader("Content-length", params.length)
    request.setRequestHeader("Connection", "close")
    request.onreadystatechange = function()
        {   
            if (this.readyState == 4)
            {
                 if (this.status == 200)
                    {
                     if (this.responseText != null)
                        {
                            ///You can use this responseText from your PHP file
                        }                       
                    else alert("Ajax error: No data received")
                    }
                else alert( "Ajax error: " + this.statusText)
             }
        }
 request.send(parameter)

And this is yourPHPFile code:

<?php 
 if (isset($_POST['url']))
 {
    $js_object = $_POST['url']
     /*use this object as you want */
 }
?>

EDIT: please refer to this example I wrote here

Sahil Lakhwani
  • 108
  • 2
  • 11