-5

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.

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
Burak KOÇAK
  • 1
  • 1
  • 1
  • 3

3 Answers3

6

If 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; ?>";
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
2

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));
}
kryoz
  • 87
  • 4
1

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;?>";
            });
        }
    });
});
Dipendra Gurung
  • 5,720
  • 11
  • 39
  • 62