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

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
I think the word by ajax is wrongly stated. You probably mean how to create JavaScript Ajax query at from PHP. – Shamim Hafiz Dec 22 '10 at 14:29
It probably does not "work" without <?php. But the JavaScript engine won't throw an error. – Felix Kling Dec 22 '10 at 14:30
Why are you data keys in quotes? – Mikhail Dec 22 '10 at 15:33

4 Answers

up vote 3 down vote accepted

Wrap the value like this:

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

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

share|improve this answer
if the userid is numeric it'll work without outside quotation – Mikhail Dec 22 '10 at 15:32
 $.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.

share|improve this answer

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

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.

share|improve this answer
Wrong way round: JS is client side, PHP is server side :P – Kyle Hudson Dec 22 '10 at 14:34
Haha I failed :$ – Mark Dec 22 '10 at 15:50

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.