1

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.

nyxem1
  • 179
  • 1
  • 4
  • 16

3 Answers3

5

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.

ChainFuse
  • 797
  • 2
  • 10
  • 26
  • i know about PDO and prepared statement in theory. Just trying my hands on the basics. Is the above valid on the same php page. – nyxem1 May 02 '14 at 20:34
  • tried it once more... got it right by making another test.php page and querying sql statement there. Also i used PDO. – nyxem1 May 03 '14 at 16:44
1

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:

  • cookie
  • hidden input

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.

Damon
  • 4,151
  • 13
  • 52
  • 108
0

Use Method Post in AJAX or Form!! To send js variable in Php and receive it in php using $_post[ name_of_obj ];

ashbuilds
  • 1,401
  • 16
  • 33