简体   繁体   中英

Javascript Not Calling PHP function in wordpress

I am trying to get the following code to work:

//In Javascript

function updateContentEditable(){

var span = $(this);
var data = new Object();

data.pid = '1';

data.content = 'this is a test';

data.action = 'update_content'; //This should run update_content php function

$.post(ajaxPath, data, onContentSaved); //ajaxPath returns: /wp-admin/admin-ajax.php
}

//In PHP

function update_content(){

echo "<script>alert (\"php was reached\")</script>";

}

NOTE:

//onContentSaved is this:

function onContentSaved(data){ console.log(data); }

My problem is the the php function is not being run.

What I'm I doing wrong?

Assuming you are using jquery, try this:

function SendRequestCallBack(webMethod, parameters, callBack) {
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        success: function(results) {
            $(".ajaxImage").hide();
             eval(callBack(results.d));
        }
    });
}

function formatData(obj){
    alert(obj);
}
$(document).ready(function()
{
    SendRequestCallBack("http://url-to-php","{'any':'parameters'}",formatData);
});

Then all the PHP needs to do is echo valid JSON. Or if you like you can change the contentType: parameter to text/xml or text/plain etc depending on what you want it to return. Keep in mind that your PHP needs to output the matching content type as well. for example <?php header("Content-type: text/json"); echo {"d":[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Doe"}]} ?> <?php header("Content-type: text/json"); echo {"d":[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Doe"}]} ?>

If you want to pass data in to the PHP function, set it in the parameters, and make sure that your PHP will accommodate it using the $_POST array.

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