Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
Possible duplicate of Pass a PHP string to a Javascript variable (and escape newlines) and a gazillion others. – deceze Aug 15 at 10:51
1  
For that purpose you can use $.ajax in jquery – lord_linus Aug 15 at 10:52

3 Answers

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; ?>";
share|improve this answer
Note: even if php var doesnt belong here you can assign the SESSION variable similarly – Shadowfax Aug 15 at 11:00
idk why but it doesnt work for me, i mean when i use like; document.getElementById("namesurname").value = <?php echo $data['name']; ?>; value of text field with namesurname id doesnt change. – Burak KOÇAK Aug 15 at 12:02
Try with the php var in quotes. If not worked cross check that $data['name'] is valid – Shadowfax Aug 15 at 12:46

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));
}
share|improve this answer

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;?>";
            });
        }
    });
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.