0

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)

?>
dandy
  • 13
  • 1
  • 1
    So what are you getting, what isn't working and what are you expecting ? – adeneo Apr 14 '14 at 14:33
  • 1
    **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Apr 14 '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 '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 '14 at 14:43

3 Answers3

1

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))

NotGaeL
  • 8,344
  • 5
  • 40
  • 70
  • use PDO or mysqli and the alert is gone. It should work anyway though – NotGaeL Apr 14 '14 at 14:50
  • Many thanks. It's my first time working in AJAX and PHP, so will research about PDO – dandy Apr 14 '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 :-) – NotGaeL Apr 14 '14 at 15:06
1

Use object to pass for data in $.ajax.

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

Also use mysqli_* as mysql_* is depreciated.

anwerj
  • 2,386
  • 2
  • 17
  • 36
0

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'];
},
shashank
  • 566
  • 3
  • 10
  • 31