简体   繁体   中英

jQuery/Ajax/PHP - cant seem to figure out what is wrong

For some reason this ajax call I'm working on is returning the error state in the console log... I can't seem to figure out why, everything looks correct to me!

AJAX:

$(document).ready( function() {

    $('.load-more').click(function(e) {
        e.preventDefault();

        console.log('Starting AJAX');

        var $this = $(this);

        var load   = $this.data('current-page') + 1;

        var parent = $this.data('parent');

        var properties = {
            snippet: 'infiniteScroll',
               limit: 3,
               offset: 0,
               parents: 22,
               depth: 999,
               sortby: 'publishedon',
               showHidden: 1,
               debug: 1,
               tpl: 'infiniteHomePageTpl',
               };

          $this.data('current-page', load);

        $.ajax({
            type: "POST",
            url: "/ajax.processor",
            data: properties,
            cache: false,
               dataType: "json",

            success: function(response) {

                if(response.status == 'success'){

                    console.log('Success');

                }else if(response.status == 'error'){

                    console.log('data error');

                }else{

                    console.log('some other error');

                }

              },

              error: function(response){

                 console.log('an error has occurred' + response);

              },

        }); // ajax
    });

});// document ready

The processor being called:

<?php

// $modx->log(modX::LOG_LEVEL_ERROR,'Running ajax.processor, snippet = '.$_POST['snippet'].' formdata = '. print_r($_POST, TRUE));

$output = $modx->runSnippet($_POST['snippet'],array(
   'snippet' => $_POST['snippet'],
   'data' => $_POST
));

// set the header for the ajax call

$output =  json_encode($output);

header('Content-type: application/json');

$modx->log(modX::LOG_LEVEL_ERROR,'Should be json = '.$output);

echo $output;

The code that the processor execute:

<?php

    //$modx->log(modX::LOG_LEVEL_ERROR, 'Running infinitescroll snippet' . print_r($scriptProperties, TRUE));

    $output = array(
      'status' => 'success',
      'msg' => 'a message of some type',
      'whatever' => 'this is some data',
    );

    return $output;

The logging line in the processor will output json to the log:

Should be json = {"status":"success","msg":"a message of some type","whatever":"this is some data"}

so my javascript ~should~ be getting json back, but its not hitting the success condition, all I get in the console log is:

an error has occurred[object Object]

What am I doing wrong here?

You need to json_encode the php array, as Kaleb has already commented. http://php.net/manual/en/function.json-encode.php

So your code should be:

//$modx->log(modX::LOG_LEVEL_ERROR, 'Running infinitescroll snippet' . print_r($scriptProperties, TRUE));

$output = array(
  'status' => 'success',
  'msg' => 'a message of some type',
  'whatever' => 'this is some data',
);

$json = json_encode($output);

return $json;

I would also suggest that you use Firebug to monitor your javascript rather than logging console messages: http://getfirebug.com/

Try using an HTTP client such as Postman (or even cURL) to mock your AJAX call. This makes it easy to inspect the headers and contents of response.

Also, when the error handler is called the first argument will always be an XHR object. If you do console.log(response); (without the string casting) you should be able to inspect its contents. What might be of more use for you though are the other two parameters:

error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

More info is in the jQuery.ajax docs .

You actually need a json content type header and to encode the output:

<?php
header('Content-Type: application/json');

    //$modx->log(modX::LOG_LEVEL_ERROR, 'Running infinitescroll snippet' . print_r($scriptProperties, TRUE));
    $output = array(
      'status' => 'success',
      'msg' => 'a message of some type',
      'whatever' => 'this is some data',
    );
    echo json_encode($output);

And if you wanted to know why this is happening, you can expect the errorThrown by using $.ajax.fail() :

$.ajax({
    type: "POST",
    url: "/ajax.php",
    data: properties,
    cache: false,
    dataType: "json",

success: function(response) {
//your code
},

error: function(response){
//your code 
},

}).fail(function(jqXHR,textStatus,errorThrown) {
    console.log(errorThrown);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM