How can i assign value of a javascript variable using php variable
$(function(){
$("select[name=myselectlist]").change(function(){
var id = $(this).val();
if(id != 0) {
$.post("ajax.php", {"id":id}, function(){
var data = "somedatahere";
document.getElementById("namesurname").value = data;
});
}
});
});
the code above works perfectly without php.Yet, i need to assign "var data" from mysql everytime.
How can i assign value of a javascript variable using php variable
$(function(){
$("select[name=myselectlist]").change(function(){
var id = $(this).val();
if(id != 0) {
$.post("ajax.php", {"id":id}, function(){
var data = "somedatahere";
document.getElementById("namesurname").value = data;
});
}
});
});
the code above works perfectly without php.Yet, i need to assign "var data" from mysql everytime.
Share Improve this question edited Mar 14, 2014 at 4:28 Sahil Mittal 20.8k12 gold badges67 silver badges91 bronze badges asked Aug 15, 2013 at 10:49 Burak KOÇAKBurak KOÇAK 11 gold badge1 silver badge3 bronze badges 3- Possible duplicate of Pass a PHP string to a Javascript variable (and escape newlines) and a gazillion others. – deceze ♦ Commented Aug 15, 2013 at 10:51
- 1 I wonder why they spent hours/days making the manual? – Niet the Dark Absol Commented Aug 15, 2013 at 10:52
- For that purpose you can use $.ajax in jquery – Rohitashv Singhal Commented Aug 15, 2013 at 10:52
3 Answers
Reset to default 6If your php var is in the scope of the file where you have this function, you can do it like this:
var data = "<php echo $myvar; ?>";
1) You can do as Shadowfax wrote but more simple:
var data = '<?=$dbResult?>';
2) More correct. Pass your result to AJAX response with json_encode
function in PHP so you can rewrite your JavaScript code block as follows:
...
$.post("ajax.php", {"id":id}, function(response){
$("#namesurname").val(response.data);
});
For example your PHP code block in backend may look like this:
....
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')) {
echo json_encode(array('data' => $dbResult));
}
If this javascript code is in the php file, then you can simply use php variables as updated in the code:-
<?php
// assign a value
$data = 'your data here';
?>
$(function(){
$("select[name=myselectlist]").change(function(){
var id = $(this).val();
if(id != 0) {
$.post("ajax.php", {"id":id}, function(){
var data = "somedatahere";
document.getElementById("namesurname").value = "<?php echo $data;?>";
});
}
});
});