1

So basically, I wrote an AJAX call that runs a PHP script that echoes hello world in response to a button click (handled by JS). I get status 200 and in the response section of my browser's "inspect element" function, I get "Hello world", but it doesn't display it on the page. I know that "echo" should work because I've used it to indicate that my site has connected to a MySQL database correctly. So the response section shows "Connected SuccessfullyHello World" (sic) but the page only displays "Connected Successfully". So for some reason, it's not actually showing that Hello World bit.

PHP

function test() {
echo "Hello World"; 
die();
}

JS

function yes(){
   jQuery.ajax({
   url: ajaxurl,
   data: {
        'action':'test_function'            
         },
   });
};

Apologies in advance if the answer is ridiculously simple - I'm new to web development

Further info: using X theme (WP)

1

Your are on the right track but have to tweak a few things. Your javascript needs (in best case) an object as result and if you want to see the result comming from PHP your js has to handle that. A quick test would be to make a console log - just to check if it works.

Try editing your code like this and check in your browser console:

// PHP file:
function test() {

$result = array(0 => 'Testresult from Ajax 1', 1 => 'Testresult from Ajax 2');
header('Content-Type: application/json');
die (json_encode($result));
}

Then in your js:

// JS file:
function yes() {

var obj = {
    url: ajaxurl,
    type: 'POST',
    data: {
        action: 'test_function'
    },
    dataType: 'JSON',
    cache: false
};

jQuery.ajax(obj)
    .done(function( data ) {
        console.log('result is: ', data);
    });
};

If it works you can handle you results in the done() function, for example write stuff into the dom or whatever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.