Reputation: 746
I have code like this
<select onchange="getval(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
And my script like this
function getval(sel){
//alert(sel.value);
<?php $sql = "SELECT * FROM tbl_table WHERE id="?>+(sel.value)
}
I want select data from table where id values from javascript but I don't know how to write php in javascript tag and how to add javascript's variable (sel.value)
after PHP
How can I correct this syntax?
Upvotes: 0
Views: 317
Reputation: 873
May this will help you. You can use with ajax...
mainfile.php
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function getval(x){
var data_arr="id="+x;
$.ajax({
type:"POST",
url:"anotherfile.php",
data:data_arr,
success: function(response){
// here your response will come now you have to deside how to maintain this response...
}
});
}
</script>
<select onchange="getval(this.value);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
and your another file which contain ajax code is here...
anotherfile.php
<?php
mysql_connect("hostname","username","password");
mysql_select_db("database_name");
$sql = "SELECT * FROM tbl_table WHERE id=".$_REQUEST['id'];
while($row = mysql_fetch_array($sql)){
// here your out put data code...
}
// and finally write all data in echo statement they will return as response
hope you got it...
Upvotes: 5
Reputation: 1605
Php is server side scripting language and JavaScript is client side language so it seems to be impossible! Further Explanation.
PHP is a programming language. It is often used for server side programming, but has uses in general programming too.
JavaScript is a programming language. It is the only language that has a decent level of native support for running in a browser.
Similarity:
Differences:
Solution:
AJAX = Asynchronous JavaScript and XML.
AJAX is not a new programming language, but a new way to use existing standards.
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
Upvotes: 3
Reputation: 221
If I understood you correctly, you cannot write PHP in this way. PHP stays on the server, and never gets shown on the page. You need to either POST the page or use AJAX. The most basic way is to use a 'Submit' button and handle the result with PHP. Look at this basic example: http://www.tizag.com/phpT/forms.php?
Upvotes: 1