7

I need to store the variable from the json string with name 'msg' in my database, but I am not able to catch it with $msg = $_POST['msg']; How do I catch it correctly?

Moreover I would like to echo the contents of $msg straightaway on the webpage.

HTML

<div id="addCommentContainer">
    <form id="addCommentForm" action="">
        <textarea name="msg" id="msg" cols="82" title="Your comment" rows="2">Your comment...</textarea>
        <br />
        <input type="text" name="author" title="name" value="<?php echo $_SESSION['username']; ?>" id="author" />
        <br />
        <div id="personal">
            <input type="text" name="city" id="city" title="city (optional)" value="" />
            <br />
            <input type="text" name="email" id="email" title="e-mail (optional)" value="" />
            <br />
            <input type="text" name="url" id="url" title="website (optional)" value="" />
            <input type="hidden" id="cam_id" class="hd" name="cam_id" value="<?php echo $cam_id ?>" />
        </div>
        <input type="submit" id="submit" value="Comment" />
    </form>
</div>

JavaScript

//if submit button is clicked
$('#submit').click(function () {
    //start the ajax
    $.ajax({
        //this is the php file that processes the data 
        url: "/comment/insert.php",
        type: "POST",
        data: $("#addCommentForm").serialize(),
        contentType: "json",
        //success
        success: function (html) {
            //if returned 1/true (process success)
            if (html == 1) {
                //show the success message
                $('.done').fadeIn('slow');
                //if process.php returned 0/false (send mail failed)
            } else alert('Sorry, unexpected error. Please try again later.');
        }
    });
    //cancel the submit button default behaviours
    return false;
});

PHP

 $msg = $_POST['msg'];
//  echo $msg;
 $author = $_POST['author'];
 $email = $_POST['email'];
 $url = $_POST['url'];
 $city = $_POST['city'];




    // include ("/home/sionvalais/domains/skiweather.eu/public_html/v3/functions/strip.php");

    if ($cam_id>1) {

    if ($author=='NAME') {
    $author='Anonymous';
    }

    $host = gethostbyaddr($ip);
    // mysql_query ("set character_set_results='utf8'");
    mysql_query("INSERT INTO sv_review (author,email,msg,cam_id,url,lud)
                    VALUES (
                        N'".$author."',
                        '".$email."',
                        N'".$msg."',
                        '".$cam_id."',
                        '".$url."',
                        NOW()
                    )");
     }
Mark Henry
  • 2,649
  • 7
  • 40
  • 48

6 Answers6

3

As far as I know, default value of contentType property is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases.

But It seems the data you are sending to the server is not JSON object, setting contentType doesn't convert data to JSON object, it just declares the type of data.

So, if data is just a serialized of name/value pairs, please remove contentType: "application/json", and try again.

and if it's a valid type of JSON, decode the posted JSON object at the server, using: $array = json_decode($json, true);


Getting access to JSON object

You can follow the approach below to get the JSON object on the server:

$json = @file_get_contents('php://input');
$array = json_decode($json, true);

// See what happens
print_r($array);
Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
  • This is incorrect, `dataType: 'json'` refers to the response data, not what you're sending. It tells jQuery to automatically decode the received JSON, nothing to do with what you send from client->server. It is the same as doing `$.getJSON()`. The content-type is what refers to data being sent. – MrCode Jun 16 '13 at 12:09
  • @sharif I'll appreciate if you explain your reason – Hashem Qolami Jun 16 '13 at 12:18
  • beacuse this not what the question says.the problem is sending post data to server. and i know that you can get the form variable in server if the method is 'PUT' like this.he has used post method.so is he still can do like yours .i dont know xactly . – sharif2008 Jun 16 '13 at 12:24
  • @sharif, What I said at the first is I don't think `data: $("#addCommentForm").serialize()` could be a valid JSON object, It seems to be a serialized pair of name/values. – Hashem Qolami Jun 16 '13 at 12:27
  • it needs not to be also because datatype:json means the response datatype not the serialized data he is sending .thanx @HashemQolami – sharif2008 Jun 16 '13 at 12:29
  • @sharif Firstly, I didn't mean `dataType` property, as @MrCode said, `dataType` refers to the response data which you assign a wrong value to it (in your anwser). Secondly, `php://input` allows us to read raw POST data, it is an alternative of `$HTTP_RAW_POST_DATA`. – Hashem Qolami Jun 17 '13 at 09:41
1

$POST['msg'] should be $_POST['msg']

Also to output your POST variables so you can inspect them use :

echo print_r($_POST);
Luc
  • 985
  • 7
  • 10
  • 2
    whats the point of `echo print_r($var)` print_r prints by default, unless you set print_r($var, true); – DevZer0 Jun 16 '13 at 11:50
1

Use must stringify the data to JSON: JSON.stringify($("#addCommentForm").serializeArray()). $("#addCommentForm").serialize() does not make JSON.

Donald T
  • 10,234
  • 17
  • 63
  • 91
0

try this changes -

//if submit button is clicked
$('input#submit').click(function () {
//start the ajax
$.ajax({
    //this is the php file that processes the data 
    url: "/comment/insert.php",
    //GET method is used
    type: "POST",
    data: $("form#addCommentForm").serialize(),
    dataType: "application/json",
    //Do not cache the page
    cache: false,
    //success
    success: function (html) {
        //if returned 1/true (process success)
        if (html == 1) {
            //hide the form
            $('.form').fadeOut('slow');
            //show the success message
            $('.done').fadeIn('slow');
            //if process.php returned 0/false (send mail failed)
        } else alert('Sorry, unexpected error. Please try again later.');
    }
});
//cancel the submit button default behaviours
return false;

});

sharif2008
  • 2,716
  • 3
  • 20
  • 34
0

.serialize forms a query string that could be sent to a server . It doesnt create a json, do an alert of $("#addCommentForm").serialize() you should see a query string and not a json so remove the setting contentType: "application/json", from $.ajax and you should be able to get the msg in $_POST['msg'] in php

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
Dipu
  • 21
  • 3
  • is it the case that you are not able to get $_POST['msg'] and all other fields like author,email,url ..you are able to get from $_POST ? – Dipu Jun 17 '13 at 16:22
0

Do not use: contentType: "json"

This is a POST, rigth? so, it will use:

contentType: "multipart/form-data" 

or

contentType: "application/x-www-form-urlencoded"

Or just to simplify do not use someone. Remove any contentType or dataType, jQuery choose one by default, because the type is POST.

Ravan Scafi
  • 6,382
  • 2
  • 24
  • 32