Reputation: 179
I am running a mysql select query in php like this
<?php
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
var1 and var2 are javascript variables on the same page. I know client side variable cannot be passed to server side. But is there any workaround as the variables are in the same page.
Upvotes: 1
Views: 21723
Reputation: 4484
In theory, you could pass the vars to php via some sort of ajax call. I think it would go something like...
JavaScript:
var data = {
'var1': $('selector').val(),
'var2': $('selector').val()
};
$.ajax({
type: 'post',
url: 'path-to-your-file.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response);
}).fail(function(error) {
// uh-oh.
});
php:
<?php
print_r($_POST['data']);
Otherwise, you could use:
php:
<?php
... column1='$_COOKIE["mycookie1"]' and column2='$_COOKIE["mycookie1"]'";
... column1='$_POST["hidden1"]' and column2='$_POST["hidden2"]'";
NOTE: you will want to sanitize the data. Using raw cookie and/or input values could lead to some less than desirable results.
Upvotes: 1
Reputation: 1422
Use Method Post in AJAX or Form!! To send js variable in Php and receive it in php using $_post[ name_of_obj ];
Upvotes: 0
Reputation: 827
In order for you to make this happen - I believe - you have to use AJAX.
The code will look like this:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
Your PHP will look similar to this (without keeping in mind the JSON encode:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.
Also, escape your data. Use prepared statements.
Upvotes: 5