最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to send data from a PHP variable to JavaScript by Ajax? - Stack Overflow

programmeradmin2浏览0评论

Is the following code correct?

 $.ajax( {
             url: './ajax/ajax_addTerms.php',
             type: 'POST',
             data: {"fId" : $fId, "term" : $term, "alias" : $alias,
 "userId" : <?php  print $userId; ?>},

When I remove the PHP tags it works, but this way it doesn't.

Is the following code correct?

 $.ajax( {
             url: './ajax/ajax_addTerms.php',
             type: 'POST',
             data: {"fId" : $fId, "term" : $term, "alias" : $alias,
 "userId" : <?php  print $userId; ?>},

When I remove the PHP tags it works, but this way it doesn't.

Share Improve this question edited Apr 11, 2011 at 15:17 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Dec 22, 2010 at 14:27 Ahmad FaridAhmad Farid 14.8k45 gold badges98 silver badges138 bronze badges 3
  • I think the word by ajax is wrongly stated. You probably mean how to create JavaScript Ajax query at from PHP. – Shamim Hafiz - MSFT Commented Dec 22, 2010 at 14:29
  • It probably does not "work" without <?php. But the JavaScript engine won't throw an error. – Felix Kling Commented Dec 22, 2010 at 14:30
  • Why are you data keys in quotes? – Mikhail Commented Dec 22, 2010 at 15:33
Add a ment  | 

4 Answers 4

Reset to default 5

Wrap the value like this:

 "userId" : "<?php  print $userId; ?>"}

Otherwise JS will try to parse the PHP output which is wrong.

 $.ajax( {
             url: './ajax/ajax_addTerms.php',
             type: 'POST',
             data: {"fId" : <?php echo $fId ?>, "term" : "<?php echo $term ?>", "alias" : "<?php echo $alias ?>",
 "userId" : <?php echo $userId; ?>},
 // echo is faster than print
 // and I assume $fId and $userId are integers so quotes aren't required

PHP's interpreter will parse variables and then JS does the rest.

I would use json_encode additionally to the <?php ?> to make sure that " in a string gets escaped properly:

data: {"fId" : <?php echo json_encode($fId); ?>, "term" : <?php echo json_encode($term) ?>, "alias" : <?php echo json_encode($alias); ?>, "userId" : <?php echo $userId; ?>},

This way, you could also pass an array:

<?php $data = array('fId' => $fId, 'term' => $term, 'alias' => $alias, 'userId' => $userId); ?>
...
data: <?php echo json_encode($data); ?>, // Same result as above

JavaScript is client side, PHP is server side. Ajax works like this,

JavaScript HTTP request --> PHP --> return request that is catched by the Ajax handler.

You can't start Ajax from the server side.

发布评论

评论列表(0)

  1. 暂无评论