Pararera
Pararera

Reputation: 372

Run PHP code with return value

I want to make code which will run PHP code in background. I made code which will run PHP script, but I don't Know how to get return value from PHP script(does iten exist in MySQL database).

            $.post("/* PATH TO THE .PHP FILE */", $("#_hsync_reg_form").serialize(), function(response) {
            if(response)
            {
                // SOME CODE GOES HERE
            }
            else //ERRORS

I Know PHP side.

Upvotes: 1

Views: 980

Answers (4)

George Pant
George Pant

Reputation: 2117

If you want to have a non empty response your php script must OUTPUT something...(not just return something).

In your example the callback function is function(response) {...}

So response variable in your example holds the response data.

Whatever the php file located in "/* PATH TO THE .PHP FILE */" outputs using php's echo,print,html outside php tags etc will be returned in response variable and you can access it with javascript.

Upvotes: 0

user3170450
user3170450

Reputation: 405

You can set the request/response headers as application/json. And then from PHP script send back the response as JSON. Something like following:

{
    "success": true,
    "data": [
        "item1",
        "item2"
    ]
}

<?PHP
$data = /** data to be serialized **/;
header('Content-Type: application/json');
echo json_encode($data);
?>

Upvotes: 2

Sankar Ganesh
Sankar Ganesh

Reputation: 61

using the print,echo statement to return values from php.

example : echo "hello"; print_r($arrays);

http://www.tutorialspoint.com/jquery/ajax-jquery-post.htm

Upvotes: 1

azngunit81
azngunit81

Reputation: 1604

Because you didn't show any PHP code, this will be a generic answer:

in jQuery style, the ajax request gets back an "output" which can be a single value or an entire json object if you want.

so you could echo $value; and it will work because the "response" in your ajax call is the output that any given ajax is listening to (could be any given backend..or even a 3rd party API)

Now if you have an issue and the output is not returning correctly, you will need to post your php code

Upvotes: 0

Related Questions