2

In my local machine, I am trying to save data from a json to my mysql database, I am using Wampserver.

In my html page (saveInfo.php), I have this jquery code:

<script type="text/javascript">
            var jsObj = {"user_id":5, "login":"hsm"};
            var jsonobj = JSON.stringify(jsObj);            
            $.ajax({  
                type: "POST",  
                url: "json_handler.php",  
                data: { 'jsonobj':jsonobj },      
                success: function(){  
                  alert('success');
                  window.location = "http://localhost/quranMapping/php/json_handler.php";
                } 
            });
</script>

In the other side, I have my server-side php code (json_handler.php) like that:

<?php

$input = file_get_contents('php://input');
$input = $_POST['jsonobj'];

$result = json_decode($input);

echo $result->user_id;

?>

But when I run that code, I get this error: enter image description here

11
  • this could mean that $_POST['jsonobj'] is not getting set. You need to make sure that the value of jsonobj is getting passed to the php page. Commented Aug 2, 2013 at 17:43
  • what is in var_dump($result) ? Commented Aug 2, 2013 at 17:44
  • It looks like the variable isn't making it as far as PHP. Can you var_dump($_POST) and output what comes out. Also, use Firefox or Chrome to get a dump of your outgoing POST request and post it up here too. Commented Aug 2, 2013 at 17:44
  • 2
    @Venkat It's not a deprecated error. And turning it off won't magically pass the POST value. Please people stop suggesting error silencing as a solution Commented Aug 2, 2013 at 17:46
  • 1
    data: { jsonobj:jsonobj } without quotes. Commented Aug 2, 2013 at 17:46

1 Answer 1

3

You should remove this:

var jsonobj = JSON.stringify(jsObj); 

and change

data: { 'jsonobj':jsonobj }, 

to

data: jsObj, 

On the php side to decode the data just use

$user_id = isset($_POST["user_id"])?$_POST["user_id"]:"";
$login   = isset($_POST["login"])?$_POST["login"]:"";

Also there is no need to do

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

Since the form is being posted with an object as data the value will be application/x-www-form-urlencoded so it don't be valid json.

Sign up to request clarification or add additional context in comments.

7 Comments

Named jsonobj on the client, but jsObj on the server?
array (size=0) : this was the output
@HoussemBdr that is the value of var_dump($_POST["jsonobj"]); ?
@HoussemBdr See updates ... there is no reason to wrap the two object in another object... this should give your the data you want right in the $_POST array
echo "user is : ".$user_id; gave empty result : (
|

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.