0

i have try to perform select query from tag with JavaScript variable but it is not work.

What wrong with it

function method12()
{
    var value12=document.getElementById('period').value
    <?php
    $con=mysql_connect("localhost","root","");
                if(!$con)
                    {   
                    die('could not connect:'.mysql_error());
                    }

                    mysql_select_db("db_loan",$con);
                    $sqlstr="select bankcode from tbl_master where loanaccountnumber='".value12."'";
                    $result=mysql_query($sqlstr);
                    $row=mysql_fetch_array($result);
                    echo $row['bankcode'];
    ?>
    alert(value12);
}
Smit Saraiya
  • 391
  • 1
  • 5
  • 26

2 Answers2

2

PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.

What happens in a nutshell is this:

You click a link in your browser on your computer under your desk The browser creates an HTTP request and sends it to a server on the Internet The server checks if he can handle the request If the request is for a PHP page, the PHP interpreter is started The PHP interpreter will run all PHP code in the page you requested The PHP interpreter will NOT run any JS code, because it has no clue about it The server will send the page assembled by the interpreter back to your browser Your browser will render the page and show it to you JavaScript is executed on your computer In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.

The only way to do what you are looking to do is either:

do a redirect to a PHP script or do an AJAX call to a PHP script with the values you want to be insert into the database

Deepak
  • 1,373
  • 2
  • 10
  • 31
1

You can't use JS variables in PHP. JS code is run on the client and PHP code is run on the server.

To do what you want you have to send the JS value via a GET or POST request to the server and then get that value via $_POST["varname"] or $_GET["varname"]

coding-dude.com
  • 758
  • 1
  • 8
  • 27