Houssam Badri
Houssam Badri

Reputation: 2509

Undefined index in PHP post with AJAX

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

Upvotes: 2

Views: 4650

Answers (1)

Orangepill
Orangepill

Reputation: 24665

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.

Upvotes: 3

Related Questions