最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does AJAX json script return extra 0 (zero) - Stack Overflow

programmeradmin1浏览0评论

I have an AJAX function in WordPress that calls a PHP function to return the value of a transient record in the Database.

When I call the function using jQuery, I receive the result however it always has an extra 0 (zero) appended to the value.

Here is my jQuery function:

(function($) {
    $(document).ready( function() {

        var AdvancedDashboardWidget = function(element, options)
        {
            var ele = $(element);
            var settings = $.extend({
                action: '',
                service: '',
                countof: '',
                query:   '',
                callback:''
            }, options || {});
            this.count=0;
            var url='';
            switch(settings.service)
            {
                case 'facebook':
                    if(settings.countof=='likes' || settings.countof=='talks')
                    {
                        ajaxCall(action,ele,settings);  
                    }
            }
        };

    var ajaxCall = function(action,ele,settings){
        opts = {
            url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            data:{
                action: settings.action // Tell WordPress how to handle this ajax request
            },
            success:function(response) {
                //alert(response);
                ele.html(response);
                return; 
            },
            error: function(xhr,textStatus,e) {  // This can be expanded to provide more information
                alert(e);
                //alert('There was an error');
                return; 
            }
        };
        $.ajax(opts);
    };


        $.fn.advanceddashboardwidget = function(options)
        {
            return this.each(function()
            {
                var element = $(this);

                // Return early if this element already has a plugin instance
                if (element.data('advanceddashboardwidget')) return;

                // pass options to plugin constructor
                var advanceddashboardwidget = new AdvancedDashboardWidget(this, options);

                // Store plugin object in this element's data
                element.data('advanceddashboardwidget', advanceddashboardwidget);
            });
        };

    });
})(jQuery);

There are more helper functions involved however this is the main jQuery function that municates with WordPress and returns the value of the PHP function.

The issue is that if the value is returned as "99" for example it will be returned as "990"

Here is the PHP function that jQuery is calling:

/**
* Get Facebook Likes
*/

public function get_facebook_likes(){

    echo 99;
}

If I change the above to return 99; I receive plain 0

I have an AJAX function in WordPress that calls a PHP function to return the value of a transient record in the Database.

When I call the function using jQuery, I receive the result however it always has an extra 0 (zero) appended to the value.

Here is my jQuery function:

(function($) {
    $(document).ready( function() {

        var AdvancedDashboardWidget = function(element, options)
        {
            var ele = $(element);
            var settings = $.extend({
                action: '',
                service: '',
                countof: '',
                query:   '',
                callback:''
            }, options || {});
            this.count=0;
            var url='';
            switch(settings.service)
            {
                case 'facebook':
                    if(settings.countof=='likes' || settings.countof=='talks')
                    {
                        ajaxCall(action,ele,settings);  
                    }
            }
        };

    var ajaxCall = function(action,ele,settings){
        opts = {
            url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            data:{
                action: settings.action // Tell WordPress how to handle this ajax request
            },
            success:function(response) {
                //alert(response);
                ele.html(response);
                return; 
            },
            error: function(xhr,textStatus,e) {  // This can be expanded to provide more information
                alert(e);
                //alert('There was an error');
                return; 
            }
        };
        $.ajax(opts);
    };


        $.fn.advanceddashboardwidget = function(options)
        {
            return this.each(function()
            {
                var element = $(this);

                // Return early if this element already has a plugin instance
                if (element.data('advanceddashboardwidget')) return;

                // pass options to plugin constructor
                var advanceddashboardwidget = new AdvancedDashboardWidget(this, options);

                // Store plugin object in this element's data
                element.data('advanceddashboardwidget', advanceddashboardwidget);
            });
        };

    });
})(jQuery);

There are more helper functions involved however this is the main jQuery function that municates with WordPress and returns the value of the PHP function.

The issue is that if the value is returned as "99" for example it will be returned as "990"

Here is the PHP function that jQuery is calling:

/**
* Get Facebook Likes
*/

public function get_facebook_likes(){

    echo 99;
}

If I change the above to return 99; I receive plain 0

Share Improve this question edited Nov 23, 2012 at 22:46 Jason asked Nov 23, 2012 at 22:22 JasonJason 4,96712 gold badges48 silver badges58 bronze badges 2
  • Are you adding a number to a string when you should be adding a number to a number, either on the PHP end or the Javascript end? – JayC Commented Nov 23, 2012 at 22:28
  • Just to debug I have the the PHP function "return 99;". It still returns 990 – Jason Commented Nov 23, 2012 at 22:33
Add a ment  | 

3 Answers 3

Reset to default 10

Your function should use wp_send_json to encode the result as JSON and sent it back to the AJAX request handler. This will also stop the execution of any subsequent PHP too, so there is no need to use exit or die.

So, for your specific example, you would use:

/**
* Get Facebook Likes
*/

public function get_facebook_likes(){
   wp_send_json(99);
}

This is old question but I'm going to answer this. wp_send_json() function may help but not always. There could be some moments when you can't use this function. Like, when you load posts by ajax, you are getting some template part, you can use the function. That's why WordPress documentation suggests to make use of the die() function.

So in the end, your php function should look like this:

/**
* Get Facebook Likes
*/

public function get_facebook_likes() {
   echo 99;
   die();
}

Use Firebug and view the actual net data transmitted and received. Determine if the error is ing from the javascript side or the PHP side. Copy the net request and paste it into a separate browser window to see the raw result. If it is PHP, pursue that. if it is the javascript doing something, let us know.

发布评论

评论列表(0)

  1. 暂无评论