I want to pass 'user_data' stored in local storage in $.getJSON and perform a php mysql query. Code I am using is:
<script>
data = localStorage.getItem("user_data");
$(document).ready(function(){
$.getJSON("query.php" , {user: data},
function(data){ /*do something*/
});
});
</script>
Query.php
<? php
if( $_REQUEST["user"] )
{
$user = $_REQUEST['user'];
$user_data = json_encode($user).id;
$userid = $user_data.id;
$username = $user_data.name;
/*Database connection*/
include_once("php_includes/db_conx.php");
$sql = /*database query*/;
?>
Basically I am passing the user_data as string in $.getJSON and then using json_encode to change it to JSON data and use it to get different attributes of user. However I am not getting $userid and $username correctly inside query.php? Can anyone tell me how to send JSON type data and use it in php.
Add var_dump($user_data);
to query.php to see what is available,
You should be referencing PHP arrays as $user_data['id']
You also need to json_decode($user)
not encode, If using json_decode you need to reference variables as $user_data->id
read more on how to change the output of json_decode()
Also <? php
is incorrect should be <?php
Your if
statement is still open as well.
As @Adriano mentioned
<script>
data = JSON.parse( localStorage.getItem("user_data") );
$(document).ready(function(){
$.getJSON("query.php" , {user: data},
function(data){ /*do something*/
});
});
</script>
Basically when you read from localStorage you have to deserialize the data before gets it passed to PHP:
<script>
data = JSON.parse( localStorage.getItem("user_data") );
$(document).ready(function(){
$.getJSON("query.php" , {user: data},
function(data){ /*do something*/
});
});
</script>