0

I feel as if I'm making a noob mistake here, but it's annoying the hell out of me so I guess I'll post!

I'm trying to get message in the php array to be logged to the console. What actually happens is, data returns nothing, message returns 'success' and data.message is undefined.

JavaScript:

var message = '';
jQuery.ajax({
    url: '/dir/myfile.php',
    type: "POST",
    dataType: "json",
    data: { message : message },
    error: function(xhr, text, thrown){
        console.log('error');
    },
    success: function(data, message, text, xhr){

        if(data.message){
            console.log('data exists');
        } else if(message){
            console.log(message);
        }else{
            console.log('no data');
        }
    },
})

PHP:

$output = array(
    'code' => 1,
    'message' => 'Please work!'
);
echo json_encode($output);
8
  • 3
    What do you expect to happen, and what happens instead? Commented Apr 16, 2014 at 15:32
  • what is your error? "If it's not obvious" ,. How is this obvious? Commented Apr 16, 2014 at 15:32
  • 2
    In addition to the above questions, when you navigate directly to *yourdomainhere*/dir/myfile.php, do you see the JSON output you're expecting it to hand back to the AJAX request? Commented Apr 16, 2014 at 15:34
  • use jQuery.post to post your data Commented Apr 16, 2014 at 15:34
  • 1
    you may also need to set the content type of the php script: header('Content-type: application/json') Commented Apr 16, 2014 at 15:39

1 Answer 1

2

According to https://api.jquery.com/jQuery.ajax/, the prototype of the success callback should be :

Function(PlainObject data, String textStatus, jqXHR jqXHR)

Anyway, you should not do a test like this :

if (data) { ... } else if (msg) { ... }

Because your message is your data !

What you want looks like that :

if (data) { console.log(data.code) ; console.log(data.message) ; }
Sign up to request clarification or add additional context in comments.

4 Comments

well, data returns nothing. So the alert for data doesn't get output. msg exists though and returns 'success'.
you should also be using the Promise object returned by .ajax call. Scroll down on api.jquery.com/jQuery.ajax to see how to use done() and fail() and always()
If data returns nothing, but success is call, it means the PHP script is called but output no data (or no json data). Check what your script outputs when you go to /dir/myfile.php, if you see something try to set the header content type with a header('Content-type: application/json').
okay, tried that. Changed to POST and it returned the JSON fine inside the PHP file. I then turned the JS back on and it went back to returning data.

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.