Andy C
Andy C

Reputation: 119

Unable to get data returned from PHP via AJAX

I'm trying to get data returned from a function in a PHP file via AJAX (using Chrome)

The JS:

    $.ajax({
            url: 'http://www.site.co.uk/api/file.php',
            data: data, 
            dataType: 'json', 
            type: 'POST', 
            contentType: 'application/json',
            async: false,
            success: function (jsonData){
                console.log("SUCCESS");
                var responseText = jQuery.parseJSON(jsonData.responseText);
                console.log(responseText);
            },
            error: function (jsonData){
                console.log("ERROR");
                var responseText = jQuery.parseJSON(jsonData.responseText);
                console.log(responseText);
            }
        });

Relevant part of the PHP:

public function post_method()
{
    $data['error_message'] = "Error message text";
    return json_encode($data);
}

In the console I'm getting:

POST http://www.site.co.uk/api/file.php 500 (Internal Server Error)
ERROR
Object {status: "{", message: "{"}

In the PHP, if I replace

return json_encode($data);

with

return $data;

the console shows

SUCCESS
Uncaught SyntaxError: Unexpected token u jquery.js:3 

Not sure why I can't get 'error_message', and not sure why using 'json_encode' appears to produce a 500 error.

@Johannes Reuter - It's slightly complicated but I'm calling post_method() like this:

public function route_method()
{
   switch($this->resource['request_method'])
    {
        case 'POST':
            return $this->post_method();
            break;
        default:
            return FALSE;
            break;                
    }

}

This is part of some api framework code that I didn't write. '$this->resource' is essentially being passed into the class constructor. The same method is used successfully in other PHP files.

@Rory McCrossan - how should I define it? I thought it was OK just to create it as an array.

Upvotes: 1

Views: 622

Answers (3)

Juan de Parras
Juan de Parras

Reputation: 778

If you inform dataType as json in the request, just dont need use jQuery.parseJSON function because it's json.

Upvotes: 1

Suresh Vaishnav
Suresh Vaishnav

Reputation: 101

use echo json_encode($data);die; instead of return json_encode($data);

Upvotes: 0

Alpesh
Alpesh

Reputation: 1

you will try.

echo json_encode($data);exit;

Upvotes: 0

Related Questions