I’m trying to do some basic stuff but my php code seems not to be called.
I have a button with an onclick
event with points to a js function
<button type="button" onclick="tryphp()">go!</button>
and this is in my index.php file.
Then I have a subfolder called js with inside my js file and the function is as follows
function tryphp() {
jQuery.ajax({
url: 'php/try.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert('success!!!!');
}
});
}
finally, I have another subfolder “php” with inside my try.php
<?php
echo 'hello';
?>
I expect the button to fire a “success!!!!” when clicked but nothing happens.
I’m trying to figure out if the error is in the “url” paramether of the ajax call?
The file structure is as below
/main/index.php
/main/js/file.js
/main/php/try.php
Any help would be great!
Last but not least, my functions.php file is as follows
<?php
function newtheme_script_enqueue() {
wp_enqueue_style('style1', get_template_directory_uri() . '/css/newtheme.css', array(), '1.0.0', 'all');
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array(), '1.0.0', TRUE);
wp_enqueue_script('script1',get_template_directory_uri() . '/js/jquery.js', array(), '1.0.0', TRUE);
}
add_action('wp_enqueue_scripts','newtheme_script_enqueue');
and inside jquery.js I have downloaded the compressed version of jquery.
thanks in advance!
———–UPDATE————
SOLVED!
There were 2 mistakes:
-i did not specify the dependency in the script enqueue
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array('jquery'), '1.0.0', TRUE);
-the path to the php file was missing the “template directory” part
Thanks everybody!
First of all you have to know that WordPress integrate
ajax
as well.On file
functions.php
you must have the function that fires out results to ajax callsAnd on your
javascript
file there should be something like:Please read reference at this link that’s made for plugins but works for themes as well.
If you make a lot of ajax requests, you might want to use something like this to help find problems:
If you have an error somewhere in your php file you should see it after “Success” response in your console.log. If your url is incorrect you should see the error somewhere in the “Error” response – it’s usually towards the end of the responses. (Unless you love the sound of your browser’s alert, I would give your responses to console.log as the error response will produce quite a few alerts.)