0

Currently I am experiencing a frustrating bug in my code. It seems that I can't echo an ajax call within php.Below is the code for the call. Any suggestions would be much appreciated Thanks.

echo'
<script>
$.get("fxn.php", { r: ""+result, id:""+'.$id.' } ).
    success(function(){ 
       alert("FXN"); 
    });
</script>';

Note:

  1. Result is a javascript variable.
  2. $id is a php variable.
  3. The success function is never called.
3
  • 1
    indent your code and you will find a solution in less than a minute Commented Aug 7, 2011 at 21:44
  • If $id is not a number it won't work. I mean... id: "' . $id . '" Commented Aug 7, 2011 at 21:50
  • Can you explain what you need a + before result? Is this to force a String? Make sure you have no whitespace being passed if you're using something like a switch in your request page. Commented Aug 7, 2011 at 21:58

3 Answers 3

3
// For those who come after, put a space after echo.
echo 
     // put type into your script tag. Be kind to the older browsers.
     '<script type="text/javascript">'.
     // are you sure jQuery has loaded at this point? Does `$` reference jQuery
     // or is there another framework that's nastying up $? (Liferay? Prototype?)
     '$.get("fxn.php", '.
     // I always prefer explicit casting, but is this defined?
     '{ r: ""+result, id:""+'
     // is $id a string? Then you need to quote it.
     .$id.' } ).'.
     // not necessary, but good practice, use the third parameter of `$.get`
     // instead of defining it externally.
     'success(function() { alert("FXN"); });</script>';

Proposed alternate:

echo '<script type="text/javascript">
         $.get("fxn.php", { r: String(result), id:"'.$id.'" }, function() { 
            alert("FXN"); 
         });
     </script>';

Oh, and are you sure that PHP is returning anything? What happens if you use get manually on fxn.php?

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

Comments

1

Use heredoc to avoid a lot of qouting

echo <<< JS
    <script>$.get("fxn.php", { r: ""+result, "id":"$id" } ).success(function() { alert("FXN"); });</script>
JS;

Comments

0

You need to make sure to escape the " characters in your echo. Like below

echo '<script>$.get(\"fxn.php\", { r: \"\"+result, id:\"\"+'.$id.' } ).success(function() { alert(\"FXN\"); });</script>';

1 Comment

Double-quotes within single-quotes needs not be escaped.

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.