0

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?

enter image description here

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

12
  • Do you get any errors from json_decode? php.net/manual/en/function.json-last-error.php
    – JimL
    Commented Aug 2, 2013 at 15:17
  • Take the Post parameters as: $input = $_POST['str_json'];
    – Aditya
    Commented Aug 2, 2013 at 15:17
  • Which line ist line 17?
    – Sindhara
    Commented Aug 2, 2013 at 15:20
  • json_last_error(); gave me 0 as output so JSON_ERROR_NONE Commented Aug 2, 2013 at 15:21
  • did you dump the $result yet? I suspect it was null and the error raised when you access property user_id Commented Aug 2, 2013 at 15:22

2 Answers 2

1

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.

1
  • Same problem with it, bytheway, it is not who downvoted ur answer: ) Commented Aug 2, 2013 at 15:18
0

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

?>
1
  • You're missing a { and }
    – Kevin B
    Commented Aug 2, 2013 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.