user2850305
user2850305

Reputation: 397

use a global javascript variable in ajax php mysql

I have a variable 'user_cache' stored in local storage: Now I am doing a $.getJSON call

<script>

    user_data = JSON.parse(localStorage.getItem("user_cache"));

    $.getJSON("query.php",  { productId: productId}, function(data) { /*do something*/});

</script>

Query.php does a php_mysql database query:

<? php
if( $_REQUEST["productId"] )
{
    $productid = $_REQUEST['productId'];

    /*Database connection*/
    include_once("php_includes/db_conx.php");

    $sql = "DELETE FROM USERPRODUCTCOLLECTION WHERE  Product_ID = $productid";


    if ($db_conx->query($sql) === TRUE) {
        echo "Success";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $db_conx->close();

}
?>

My question is that I also want to use the object 'user_data' in the query.php file to do that database query but I dont want to pass 'user_data' in $.getJSON. Is it possible to use 'user_data' object inside 'query.php' file without having to pass it in the $.getJSON?

Upvotes: 0

Views: 60

Answers (1)

Mikel Bitson
Mikel Bitson

Reputation: 3627

Unfortunately that will not be possible. You must pass the data to the php file in order to utilize it. Are you leaning away from passing the user data because it is passing it as a GET variable (in the URL)? If so, consider using a jQuery.post() call instead. This way the data will be posted instead of in the URL.

See : http://api.jquery.com/jquery.post/

Upvotes: 1

Related Questions