简体   繁体   中英

jQuery AJAX POST to allow form data sending without page redirect- how to then insert data into mysql

I have followed three tutorials, one on submitting form data to a php file, one on writing that data to a mysql table, and then one on jQuery AJAX to do all this without page redirects.

The jQuery AJAX tutorial is here, by the way, as it seems a lot of people on this site have asked how to send forms without POST redirects:

POST a form without page redirect

I have got everything set up correctly in terms of getting the data to the php file via AJAX, but the php mysql statement won't write the data to the database. I have used firebug to check that the data is getting to the php, and it is what I think it is.

I am certain the issue is not one of database connectivity, I think it is due to format of the data being passed to the php file. Mixing and matching the tutorials was difficult for me. Do I need to unpack the string data that I created in the jQuery function?

As an aside, in the jQuery AJAX tutorial he mentions 'There are more advanced things you can do here, other than sending an email and giving a success message. For example you could send your values to a database, process them, then display the results back to the user'. It sounds like he is saying that you can use something other than the POST to the php file to do all this. I thought the whole point of the php file was to do the database storage?

Thankyou for your time.

The jQuery AJAX sending the data:

  jQuery(function() {  
  jQuery(".button1").click(function() {  

    var txtRow1 = jQuery('#txtRow1').val();
    var tickerRow1 = jQuery('#tickerRow1').val();

    var dataString = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1;  
    //alert (dataString);return false;  
    jQuery.ajax({  
    type: "POST",  
    url: "form_action.php",  
    data: dataString
    });  
            return false;  
        });  
});  

And form_action.php:

<?php

$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'pass';
$dbname = 'dbname';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

$txtRow1 = $_POST['txtRow1'];
$tickerRow1 = $_POST['tickerRow1'];

$sqlinsert = "INSERT INTO stock_port (name, ticker) VALUES ('$txtRow1', '$tickerRow1')"; 

?>

first of all, make sure you escape the data from post:

$sqlinsert = "INSERT INTO stock_port (name, ticker) VALUES ('".mysql_real_escape_string($txtRow1)."', '".mysql_real_escape_string($tickerRow1)."')";

second thing, you are not executing the query (or is some code missing here?)

mysql_query($sqlinsert, $conn);

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