简体   繁体   中英

How to use ajax in order to pass variables values to a php script?

I am trying to use ajax and pass varuables from js to php in order to insert them in a mysql table. the code below is successful in calling the php script but not passing the data

i would like to pass "num" from the following js function to "insertRow.php" - the function does activate "insertRow.php" but will not pass the data

function InsertToTable(num){
    var data=num;
    $.ajax({
        url: "insertRow.php",
        data: data,
        type: "POST"
        });

once the data is passed i would like to insert it in to a mysql table, the following will work if i don't use "$num" but just put a value instead

<?php
$num = $_Post['data'];
//print_r($_Post("data"));

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Schedule";   

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql ="INSERT INTO `temp1` (`column1`) VALUES ('$num')";

$conn->query($sql);     
?>

You can do this...

data: {data : num},

OR, since you set data = num; you could do this:

data: {data: data},

Where the first data is the identifier and the second is the value.

The will give you access to data in the POST (which is case sensitive) variable:

$_POST['data'] // should be equal to num

Seems like a typo,

Insead of

$num = $_Post['data'];

Try

$num = $_POST['data'];

Also, it's good practice to send AJAX a return, so in the end you can use

echo json_encode(true); 

Or set it to false in case of an error, with this you can see if the query worked or not in the success clause of AJAX.

Here's an example of a more complex AJAX call.

            $.ajax({
                url: 'scripts/AjaxHandler/Controller.php',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    action: 'doThis',
                    var1: var1,
                    var2: var2
                },
                success: function (data) {
                    if(data == true) {
                        alert('success');
                    }else{
                        alert('failure');
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM