abouletcouture
abouletcouture

Reputation: 71

send data to MySQL with AJAX + jQuery + PHP

I've been looking all day to find a way to insert some data into my database and then show the new data in the list of already existent data on my webpage.

I know that some of the points I can't get done may be basics but I just started learning Javascript/ AJAX so I have a limited knowledge.

I think that 70% of the job is done, I can display the data on my webpage using AJAX/jQuery/PHP but I can't figure how to send data from a "textarea" to my database using again AJAX/jQuery/PHP.

So far this is what I've done :

index.php
In this page, I figure that I need to put an onClick: function() on the button but I don't know where to put that function and what it should exactly do.

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>TP2</title>
    <script src="jquery-1.10.2.min.js"></script>
</head>

<body>

 <script src="javascript.js"></script>




    Message: <input type="text" id="message-content">
    <input type="button" id="message-submit" value="Envoyer">


    <div id="output" align="center">    
    </div>    

</body>  
</html>

javascript.js
This page contain the AJAX code that display my data in the #output div. I just don't know what to put in "data: {}" so the content of my textarea is sent to my php file.

$.ajax({
    url: "messages.php",
    type: "POST",
    async: true, 
    data: { WHAT GOES HERE ? },
    dataType: "html",

    success: function(data) {
        $('#output').html(data);    
    },  
});

messages.php
I know that the INSERT query will go here but I can't figure how to get the value from the POST of my textarea.

<?php

$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "myDataBaseName";
$tableName = "comments";  

$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);

$result = mysql_query("SELECT * FROM $tableName ORDER BY date DESC LIMIT 0 , 10 ");            
$data = array();

while ($row = mysql_fetch_array($result)) 
{
echo $row['message']." - ".$row['date'];
echo "<br />";
}

?>

Upvotes: 4

Views: 32264

Answers (6)

CodeBreaker
CodeBreaker

Reputation: 403

Try this.Its working

 <script>
    $("#message-submit").click(function() {
                    var senddata = $('#message-content').val();
                    console.log(senddata);
                    $.ajax({
                        type: "post",
                        url: "messages.php",
                        dataType: 'json',
                        data: {message:senddata},//for multiple data you can use
                                                         //{message:senddata,id:user_id}etc
                        success: function(data) {
                            console.log(data);
                        }
                    });
                    });
            </script>

Upvotes: 0

JustinM151
JustinM151

Reputation: 744

you can use an onclick, or use a jQuery .click function for the button...

you would put this in script tags, usually in your head or inside the document.ready

    $("#message-submit").click(function() {
        //in here we can do the ajax after validating the field isn't empty.
        if($("#message-content").val()!="") {
            $.ajax({
                url: "messages.php",
                type: "POST",
                async: true, 
                data: { message:$("#message-content").val() }, //your form data to post goes here as a json object
                dataType: "html",

                success: function(data) {
                    $('#output').html(data);    
                },  
            });
        } else {
            //notify the user they need to enter data
        }
    });

for messages.php, the value of your AJAX POST will now be available to your PHP in the variable $_POST['message']

$sql = "INSERT INTO tableName (messages) VALUES ('".$_POST['messages']."')";

EDIT/UPDATE: Six years later my original answer received another up vote so I feel it is probably relevant to post an update that the above is now globally accepted as being incredibly insecure. The jQuery used should be placed at the end of your document in the $(document).ready() method or preferably loaded in from a single minified app.js file. That aside, you will likely want to incorporate some form of CSRF (Cross Site Request Forgery) token system to help keep bots from slamming your form with spam and potentially malicious data, which leads to the next point.

The SQL listed here takes the raw data from the post data and places it in the insert statement. At the bare minimum you should be sanitizing that data. If you are using mysqli you can use the mysqli::real_escape_string($str) static method (http://php.net/manual/en/mysqli.real-escape-string.php) to sanitize any user provided data being placed in the query.

However, a much better method now would be to use prepared statements with PDO so that the data provided gets bound to query in such a way that it can only be used as intended. http://php.net/manual/en/pdo.prepare.php

Upvotes: 3

Ricardo G
Ricardo G

Reputation: 97

I was able to get the above code working with a link instead of a input type text box and button with those adjustments:

<script type="text/javascript">
    function msg(intValue) {
    var x = intValue;
    $.ajax({
       url: "messages.php",
        type: "POST",
        data:  'message=' + x, 
        success: function(data) {
          $('#output').html(data);
        },
    });
}
</script>

on the link I had:

<a href="#" id="message-content" onclick="msg('fl')">Florida</a>

Upvotes: 0

Raja Amer Khan
Raja Amer Khan

Reputation: 1519

You can send anything in that property. Try this: js

$.ajax({
    url: "messages.php",
    type: "POST",
    data: 'show=content',
    success: function(data) {
        $('#output').html(data);    
    },  
});

messages.php

if(isset($_POST['show']) && $_POST['show']=='content') {
 // rest of your code goes here..
}

One more thing. Use MySQLi instead of MySQL as it's a deprecated extension now.

Upvotes: 3

KennyPowers
KennyPowers

Reputation: 5015

Here's what Doc says:

data Type: PlainObject or String

A plain object or string that is sent to the server with the request.

Here's some infor about Plain Object: http://api.jquery.com/Types/#PlainObject

See the next example of usage:

var  formData = "name=ravi&age=31";  //Name value Pair

or

var formData = {name:"ravi",age:"31"}; //Array  

$.ajax({
    url : "messages.php",
    type: "POST",
    data : formData,
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
    },
    error: function (jqXHR, textStatus, errorThrown)
    {

    },
});

Upvotes: 2

Krish R
Krish R

Reputation: 22711

 data: {'messagecontent': $("#message-content").val()},

Upvotes: 3

Related Questions