morty346 morty346 - 2 months ago 13
Ajax Question

jquery not being called when switched from ajax

I had an ajax function, that needed to be converted to being called with Jquery for wordpress - but now the function doesn't get called?

function getCategories()
{

alert('getCategories test');
var fData = new Object();
fData.val = '';

jQuery(document).ready(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
alert('Success');
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);


for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});

}


I get my 'getCategories test' alert but I don't get the 'success' or the 'error' alert

So I do not think the jquery is running.

Before I started integrating this with wordpress I was using ajax like this

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
$('#loadingmessage').hide();
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);


for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});


I would get an erorr that ajax was unknown, and it appears I should be using jquery for this instead...?

I get no errors in the console

Answer

Well, there are some different method for calling Ajax in WP. For instance, one way would be like

FOR JS Piece

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

    // We'll pass this variable to the PHP function example_ajax_request
    var fruit = 'Banana';

    // This does the ajax request
    $.ajax({
        url: ajaxurl,
        data: {
            'action':'example_ajax_request',
            'fruit' : fruit
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });   

});

and PHP piece

function example_ajax_request() {

        // The $_REQUEST contains all the data sent via ajax 
        if ( isset($_REQUEST) ) {

            $fruit = $_REQUEST['fruit'];

            // Let's take the data that was sent and do something with it
            if ( $fruit == 'Banana' ) {
                $fruit = 'Apple';
            }

            // Now we'll return it to the javascript function
            // Anything outputted will be returned in the response
            echo $fruit;

            // If you're debugging, it might be useful to see what was sent in the $_REQUEST
            // print_r($_REQUEST);

        }

        // Always die in functions echoing ajax content
       die();
    }

    add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

    // If you wanted to also use the function for non-logged in users (in a theme for example)
    // add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

Thanks to wptheming

In your case, first try to follow template for JS part and secondly always remember in WP to prevent conflict, you must always use

jQuery(document).ready(function($) {
     // You JS functions 
});

So I tried to modify your code now on the fly, hope it works for you.

  jQuery(document).ready(function($) {
    var fData = new Object();
    fData.val = '';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "php_scripts/getdeals_php.php",
        data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
        dataType: "json",
        success: function (msg)
        {
            $('#loadingmessage').hide();
            var offerList = msg;
            var Cats = document.getElementById('CategoriesSelect');
            document.getElementById("CategoriesSelect").options.length = 0;
            var optn    = document.createElement('option');
                optn.text   = "Select Category";
                optn.value  = "Select Category";        
                Cats.add(optn);


            for(var i=0;i<offerList.length;i++)
            {
                var optn    = document.createElement('option');
                optn.text   = offerList[i];
                optn.value  = offerList[i];     
                Cats.add(optn);
            }
        },
        error: function (xhr, ajaxOptions, thrownError)
        {
            alert("ERROR:" + xhr.responseText+" - "+thrownError);
        }
    });
 });

RF: AJAX in Plugins ( WP DOCS )