Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to do a commenting system with Jquery, AJAX and PHP. I am able to store the comments on the database, but I am having problems when I want to show them from the database. I believe I am doing something wrong when reading the data that is send from the .php file in JSON format.

Here is the code I am using.

index.html

<form id="form" method="post">
    Name: <input type="text" name="name" id="name">
    Comment: <textarea rows="5" cols="115" id="text"></textarea>
    <input type="submit" id="submit" value="submit">
</form>

events.js

$('#form').on("click",'#submit',function(){
    var name = $("#name").val();
    var text = $("#text").val();
    var dataString = 'name='+ name + '&text=' + text;

    $.ajax({
        url:'comments.php',
        type:'POST',
        cache: false,
        data: dataString,
        success: function(data){
            alert("success");  
            $(".comment-block").append(data);       
        },
        error:function(){
            alert("failure");
        }
    });

comments.php

<?php

$name=$_POST['name'];
$text=$_POST['text'];

$conexion=mysql_connect("localhost","user","pass");
mysql_select_db("db_1",$conexion);

mysql_query("insert into comments (name,text) values ('$name','$text')");

$sql=mysql_query("SELECT * FROM comments");

$data=array();
$i=0;

while ($row=mysql_fetch_array($sql))
{ 
    $data[$i]["name"]=$row[name];
    $data[$i]["texr"]=$row[text];
    $i++;
}

echo json_encode($data)

?>
share|improve this question
1  
what's the error ? –  Eric Apr 14 at 14:33
1  
So what are you getting, what isn't working and what are you expecting ? –  adeneo Apr 14 at 14:33
1  
Danger: You are using an obsolete database API and should use a modern replacement. You are also vulnerable to SQL injection attacks that a modern API would make it easier to defend yourself from. –  Quentin Apr 14 at 14:38
    
Im not getting any updates in the index.html file, instead the "failure" alert appears. I am not even able to show the "succes" alert –  dandy Apr 14 at 14:38
    
If the failure alert pops up, the ajax call obviously fails. Open the console and log the arguments of the error function to see what the problem is. –  adeneo Apr 14 at 14:43

3 Answers 3

up vote 1 down vote accepted

Try changing

$data[$i]["name"]=$row[name];
$data[$i]["texr"]=$row[text];

for

$data[$i]["name"]=$row['name'];
$data[$i]["text"]=$row['text'];

and as mentioned on other solutions and jQuery API pass the post data as an object better than a properly formatted string:

data Type: PlainObject or String Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

Also, use PDO or mysqli

Also, set

contentType: "application/x-www-form-urlencoded;charset=UTF-8",

or the proper charset on $.ajax parameter if necessary (and urldecode appropriately).

And don't forget to validate and sanitize your data (filter input may be a good starting point).

jQuery will perform an intelligent guess so it's not necessary to set the dataType or json decode the response on success as mentioned, but you can do it anyways for clarity. From jQuery API again:

dataType (default: Intelligent Guess (xml, json, script, or html))

share|improve this answer
    
Thanks! But keeps showing the failure alert –  dandy Apr 14 at 14:45
    
use PDO or mysqli and the alert is gone. It should work anyway though –  elcodedocle Apr 14 at 14:50
    
Many thanks. It's my first time working in AJAX and PHP, so will research about PDO –  dandy Apr 14 at 14:57
    
PDO will save you a lot of time an effort on building queries. It's not as simple but it's definitely worth the steeper learning curve :-) –  elcodedocle Apr 14 at 15:06

Use object to pass for data in $.ajax.

var dataString = {'name':name,'text':text};

Also use mysqli_* as mysql_* is depreciated.

share|improve this answer

you should try to handle json encode data on event.js file as-

success: function(data){
  var test = jQuery.parseJSON(data);
   var test1=test.data[0]['name'];
},
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.