1

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.

3
  • I think the word by ajax is wrongly stated. You probably mean how to create JavaScript Ajax query at from PHP. Commented Dec 22, 2010 at 14:29
  • It probably does not "work" without <?php. But the JavaScript engine won't throw an error. Commented Dec 22, 2010 at 14:30
  • Why are you data keys in quotes? Commented Dec 22, 2010 at 15:33

4 Answers 4

5

Wrap the value like this:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

if the userid is numeric it'll work without outside quotation
2
 $.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.

Comments

1

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

Comments

1

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.

1 Comment

Wrong way round: JS is client side, PHP is server side :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.