Manish
Manish

Reputation: 3521

Error while using valiable in Jquery.val() funciton

I got no output when I use variable in val() function instead of fixed value. How can I fix this error.

Example: In the below example, when I use variable ($data="Glenn Quagmire"), I get no output.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    <?php $data="Glenn Quagmire";  ?>
    $("input:text").val($data);
  });
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>

</body>
</html>

Regards

Upvotes: 0

Views: 140

Answers (4)

CompanyDroneFromSector7G
CompanyDroneFromSector7G

Reputation: 4517

Use <?= $variable ?> to embed variable values in HTML, e.g.:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        <?php $data="Glenn Quagmire";  ?>
        $("input:text").val("<?= $data ?>");
    });
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>

</body>
</html>

Upvotes: 1

Quentin
Quentin

Reputation: 943605

JavaScript running in the browser cannot access variables from a PHP program (which has finished running on another computer before delivering the page to the browser so the variable does't even exist any more).

You have to make PHP output the data to the JavaScript.

You can encode it using json_encode (because JSON is (more or less) a subset of JavaScript literal syntax). This will add quotes as needed and escape any special characters in your data (you don't have any in your example, but this is a safe, general approach that protects you from XSS).

$("input:text").val(<?php echo json_encode($data); ?>);

Upvotes: 1

Priyank
Priyank

Reputation: 3868

Just use like this:

$("input:text").val("<?php echo $data; ?>");

Full code

<script>
 $(document).ready(function(){
 $("button").click(function(){
 <?php $data="Glenn Quagmire";  ?>
 $("input:text").val("<?php echo $data; ?>");
 });
 });
</script>

Upvotes: 1

Carlos M. Meyer
Carlos M. Meyer

Reputation: 446

Don't use "$" for variables (that's PHP) in jQuery.

<?php echo 'data="Glenn Quagmire";';  ?>
$("input:text").val(data);

Upvotes: 1

Related Questions