jQuery Ajax call for wordpress plugin

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:

1 Like

should i add even.preventDefault(); or without ;?

@m3g4p0p and if it is sent on dev tools, how or what can i do to make it show normal on browser or my website

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.

Am still looking for the data in console, more over apart from the misplaced eveny.preventDefault() is thereanything else wrong with the code?

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):

$.post(myobject.ajaxurl, data, console.log).fail(console.error)
1 Like

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)?

it got full html form data and some reports that i don’t know much about but with a status text that said 0 success

but my code when parsed in jquery says
SyntaxError : JSON.parse: unexpected character at line 1 column 1 of the JSON data

Do you get that data as an object or as a string? Have you tried just to not parse it?

PS: If you have a look at the jQuery.post() documentation, it says that the first argument of the success callback is indeed a plain object:

https://api.jquery.com/jQuery.post/

I just got my errors some how.

  1. am using jquery version 5.5 and so $.parseJSON() is deprecated.

  2. 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?

1 Like

nop i just want to get response as Json.

so based on what you said it means wordpress dataType is json by default

and if it is json i don’t need to parse it again as the returned response has been decoded already into an array.
so i can just do response. paul