0

I am new to jquery and ajax. Is it possible to use ajax in a php script which is returning value?

$.ajax({
         url:'ajax.php',
         method:'post',
         dataType:'json',
         success:function(response) {
            alert(response);
         }
      });

In my php script

<?php
  $sum = 1+5;
  return $sum; //usually echo(json_encode(array("$sum"))); is used
?>

Is this even possible?
P.S I am using return because in the main script this function is called from another function. But for ajax i need only this function.

0

1 Answer 1

3

return only means something in context of the PHP script, and would need to have something else calling that and echoing the results. The AJAX request can only handle things that are actually sent to it, so in the context of a result only being returned, and not echoed, the AJAX request doesn't see anything. As a very general, non-encompassing way to check, if you can't see it when you navigate to it in a browser window, the AJAX request won't either.

If you're wanting to not wrap this code within the main function, you'll likely have to write an additional function that simply echos it.

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

Comments

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.