简体   繁体   中英

ajax request issue when sending post request to db mysql

i have a problem with an ajax request and a read/write froma database.

I have this code to submit a form to a database:

$(document).ready(function(){
    $('#myForm').on('submit',function(e) {
        $.ajax({
            url:'save.php',
        type:'POST',

        });
        e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
    });
});

and i have the save.php file into the same fold with this code:

<?php
include('dbconnection.php');

$Name= $_POST['Name'];
$surname= $_POST['surname'];
$Value= $_POST['Value'];

$sql = "INSERT INTO `results`(`Name`, `surname`, `Value`) VALUES('$Name', '$surname','$Value')";

$retval = mysql_query( $sql );

if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}   
?>

the only problem is that the values is not saved inside the db.. What am i doing wrong?

First of all you should know that the Mysql php extension is deprecated, you may consider using mysqli or PDO instead.

To solve your problem, you should send the data with your Ajax call. For example:

$(document).ready(function(){
    $('#myForm').on('submit',function(e) {
        $.ajax({
            url:'save.php',
        type:'POST',
        data: {'Name':'John', 'surname': 'Jonny', 'Value':'foo'}
        });
        e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
    });
});

To see if it works, you may debug your PHP with this:

var_dump($_POST);

You need to serialize your form data and send it to the database -

$(document).ready(function(){
    // var myData = $('#myForm').serialize();
    $('#myForm').on('submit',function(e) {
        $.ajax({
            url:'save.php',
            type:'POST',
            data: $(this).serialize()
        });
        e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
    });
});

You should also start using mysqli_ or PDO to handle your database with as the mysql_ functions are deprecated. More importantly you should always validate and cleanse your data - you're asking for a SQL Injection attack otherwise.

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