简体   繁体   中英

Wordpress ajax call is returning an entire page of html

I have the following piece of javascript which runs in my wordpress site :

var PostData = "Action=refresh-cart";
                     jQuery.ajax({
                       dataType: "text",
                       type: 'POST',
                       url : location.href,
                       cache: false,
                       data : PostData,
                       complete : function() {  },
                       success: function(data) {
                         //   jQuery("#loading-img").hide();

                           // jQuery("#join-class-div-3").html(data);

                        }           
                });

The php is :

<?php 

  if(isset($_POST['Action'])) {
        $Action = $_POST['Action'];
        if($Action == "refresh-cart") {


           echo '<div id="stuff"><p> done LOL </p></div>'; 
            }
        }

    ?>

So I expect to be sent back :

<div id="stuff"><p> done LOL </p></div>

But instead I receive an entire page of html!? Why!?

It will return all contents from the page rendered at your url "location.href"

Try adding a exit() to your php code to stop it after your echo.

<?php 
if(isset($_POST['Action'])) {
    $Action = $_POST['Action'];
    if($Action == "refresh-cart") {
         echo '<div id="stuff"><p> done LOL </p></div>';
         exit;
    }
}
?>
<div>html content here will not be displayed</div>

The problem was occuring because location.href was a high level URL, so wordpress was injecting loads of html around the ajax request.

Through altering location.url to a call to plugins.url() which is part of the wordpress PHP API - the AJAX call goes directly to my PHP page and I get the correct response :)

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