Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing json serialized form data in php

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()
                    )");
     }
like image 462
Mark Henry Avatar asked Jun 16 '13 11:06

Mark Henry


People also ask

How can I access serialized form data in PHP?

To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.

What is JSON serialization PHP?

The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function. Syntax: mixed JsonSerializable::jsonSerialize( void ) Parameters: This function does not accept any parameters.

How do I PHP Unserialize a jquery serialized form?

Your answer something like this is probably all you need: $params = array(); parse_str($_GET, $params); $params should then be an array modeled how you would expect. Note this works also with HTML arrays.

How do you serialize form data?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.


1 Answers

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);
like image 148
Hashem Qolami Avatar answered Sep 29 '22 14:09

Hashem Qolami