简体   繁体   中英

Posting JSON to php script server side fails

This is my jquery code:

var jsObj = {"user_id":5, "login":"hsm"};
var str_json = JSON.stringify(jsObj);
$.post("json_handler.php", str_json)
    .done(function(){
        alert('data sent successfully');
        window.location = "http://localhost/quranMapping/php/json_handler.php";
    })
    .fail(function(){
        alert('fail');
    });

NOTE: I made the redirection to check out where is the problem.

And this is my php code ( json_handler.php file):

<?php

//create a DB connection
$con=mysqli_connect("127.0.0.1","root","","my_db");

$input = file_get_contents('php://input');
$result = json_decode($input);

echo $result->user_id;
mysql_close($con);
?>

As error have a look to the attached picture,

How can i correct such problem?

在此处输入图片说明

UPDATE: when I used $input = $_POST['str_json'] the error was undefined index

The json_decode probably failed, returning a NULL value. Do var_dump($result) and var_dump($input) to see what you're getting from the client and from json_decode.

Why dont you try using

JS:

var jsObj = {"user_id":5, "login":"hsm"};
var str_json = JSON.stringify(jsObj);
$.post("json_handler.php", {"str_json" :str_json})
            .done(function(){
                alert('data sent successfully');
                window.location = "http://localhost/quranMapping/php/json_handler.php";
            })
            .fail(function(){
                alert('fail');
            });

PHP:

<?php

//create a DB connection
$con=mysqli_connect("127.0.0.1","root","","my_db");

$input= $_POST['str_json']
$result = json_decode($input);

echo $result->user_id;
mysql_close($con);

?>

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