I need help in getting ajax to work in my custom wordpress plugins
These are the steps i followed
step one
// STEP ONE:
// I added the jquery script and localized it in my plugin base file
function add_js() {
wp_enqueue_script( 'front_script', plugins_url('assets/js/frontend.js', __FILE__), array( 'jquery' ) );
wp_enqueue_script( 'test_script', plugins_url('assets/js/test.js', __FILE__), array( 'jquery' ) );
wp_localize_script( 'test_script', 'myobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('test_script');
}
add_action( 'wp_enqueue_scripts', 'add_js' );
// STEP TWO:
// I created a php validation form - test.php
add_action( 'wp_ajax_validatetest', 'validatetest' );
add_action( 'wp_ajax_nopriv_validatetest', 'validatetest' );
function validatetest(){
if(isset($_POST['submit_testpost'])){
$value = !empty($_POST['testpost']) ? $_POST['testpost'] : '';
if(empty($value)){
$reply = array('paul' => 'test-error', 'message' => 'can not be empty');
print_r(json_encode($reply, true));
}
elseif($value != 'money'){
$reply = array('paul' => 'test-error', 'message' => 'Make more money');
print_r(json_encode($reply));
}
else{
$reply = array('paul' => 'test-success', 'message' => 'Your money has been paid into your account');
print_r(json_encode($reply, true));
}
}
}
// STEP THREE
// I ADDED THE HTML IN test.php
function formy(){
$value = !empty($_POST['testpost']) ? $_POST['testpost'] : '';
$milk = '<div class="testdiv"><form action="" method="post">
<input type="text" name="testpost" value="'.$value.'">
<input type="submit" name="submit_testpost" value="Submit" class="submit_testpost"></form></div>
';
echo $milk;
}
// STEP FOUR
// I ADDED THE JQUERY SCRIPT - in assets/js/test.js
jQuery(document).ready(function($) {
$(document).ready(function() {
$('.submit_testpost').on("click", function(){
var data = {
'action': 'validatetest'
};
jQuery.post(myobject.ajaxurl, data, function(response) {
var data = jQuery.parseJSON(response);
if(data.paul == 'test-success'){
alert(data.paul);
}else{
alert('wait guy');
}
});
});
e.preventDefault();
});
});
But for some unknown reason it seems not to be working, the alert or both success or error is not showing, as if the call was not made
What am i doing wrong, and secondly the page reloads once the submit button is clicked but i want to stop the page from reloading
I only want it to exit on success but echo error message on failure butnot reload page, which was what i thought preventDefault does.
Hi @pandglobal, first of all the variable e is not defined, and secondly youâre calling it from inside $(document).ready() (which you have 2x nested inside each other)⌠so it should look something like this:
$(document).ready(function () {
$('.submit_testpost').on('click', function (event) {
event.preventDefault()
})
})
BTW you can directly check if the request got sent from the network panel of the browser dev tools:
No thatâs just me writing standard style, which is making use of ASI to avoid visual clutter. In case of doubt, just use semicolons. :-)
Well does it get sent now? Then you might log the data to the console, or do whatever you like with it (not sure what you mean with âshow normalâ â it depends what parts of the data you want to present to the user, and how). You probably donât need to parse it BTW, jQuery will do that automatically when receiving a JSON response.
Are you actually logging it to the console though? You can check the network panel if the request is getting sent in the first place (see the link above), and if so, what the response is.
Not exactly wrong, but youâre not handling errors; so you might add a fail() callback to check if this is the case (which you should also see in the network panel though):
okay i will add the fail() but will the console.log be created as a log file with details of errors and where can i locate the console.log file to read it or is it a log only for dev tools browser?
when i did this i got something on the console log, am using Mozilla firefox console , and if there is an error in the code it shows, but using your code it shows 0 success in console meaning the data was posted.
but if i modify the code to serve my purpose it throws json.parse error on column 1
That is how i did it after i confirmed the ajax is now posting, i was expecting to get data.paul as value in the alert but is empty, and when i check console i found json.parse error in column 1
jQuery.post(myobject.ajaxurl, data, function(response) {
var data = jQuery.parseJSON(response);
alert(data.paul);
Well as I said, the response is most likely getting parsed as JSON already⌠and trying to parse a JS object will throw an error. What do you get when you console.log(response) right before attempting to parseJSON(response)?
am using jquery version 5.5 and so $.parseJSON() is deprecated.
my respons json data must be â{ âpaulâ: âmy message content hereâ }â
so i edited my js file and manually added this
var data = JSON.parse('{ "paul": "my message content" }');
alert(data.paul);
but my problem is how to use the json data returned from my php file.
because i check the json by echoing it in php and i have { âpaulâ: âmy contentâ }
but is missing â and â
so i want to experiment something like this
var data = JSON.parse(âresponseâ);
but am scared it may treat response as plain string not as a variable or object
I think i got it as an object, could it be wordpress ajax uses object as default? and there is no way to define my datatype to be Json instead of object
suppose is an object that is being returned from the response according to WordPress default admin ajaxurl method, how possible can i create a var for it and use it without parson as json?
You wonât get an object returned from PHP, a HTTP response is always a string. jQuery will then parse it for you⌠not sure what you want to achieve at this point, do you not want to get the data as an object?