简体   繁体   中英

json_decode() is not working correctly

Here I am using simple html+jquery+ajax file the ajax code is here

var email = "am3042208007@gmail.com";
var username = "ankur_07";
var password = "pass07";
var phone_no = "7676715797";
var datastring = {
    "email": email,
    "username": username,
    "password": password,
    "phone_no": phone_no
};

            $.ajax({ 
                type: "POST",
                url: "../test/testreg.php",
                data: {datastring : JSON.stringify(datastring)}, //with the page number as a parameter
                dataType: 'html', //expect html to be returned
                async: false,
                success: function (data) {
                    alert(data);
                    /*if(data=="hello"){
                        message = "Mail Sent Successfully";
                    } else {
                        message = "Oops, mail doesn't send.!!!";
                    }
                    alert(message);*/
                }
            });
            return false;

I am sending json from this file and ant to get in another testreg.php file but it is not decoding json its showing as below line using in echo {\\"email\\":\\"am3042208007@gmail.com\\",\\"username\\":\\"ankur_07\\",\\"password\\":\\"pass07\\",\\"phone_no\\":\\"7676715797\\"}

if(isset($_POST['datastring']))
{
           $data = $_POST['datastring'];
           $data = json_decode($data);

           print_r($data);
   }

please help me out of this stuck..

Replace

data: {datastring : JSON.stringify(datastring)},

by

data: {datastring : datastring},

Explanation:

You are not sending JSON. You send an escaped string (removed JSON formatting) because you use JSON.stringify .

Don't you expect the result as php associative array by chance? Didn't you forget to supply second parameter (true) in json_decode function? Since if you did, json_decode would return the result as object.

You have to strip the slashes \\ from the post data and decode the json.

Please try using this

$data = json_decode(stripslashes($data), true);

Note: Please make sure that in this case stripslashes() will also remove your escaped sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM