Your code should work just fine, because there’s nothing wrong with it, but…
You use relative URL in it
You pass loaddata.php?id1=
as URL. It’s relative, so it will try to find loaddata.php file in current directory.
So if you’re at the home page, then it will try to load that file from root directory. But if you’re at some post (i.e. example.com/my-post/
), it will try to load that file from /my-post/
directory – and there is no such directory, so it won’t end good.
You should use absolute urls to avoid this problem.
You don’t use admin-ajax
But… We’re using WordPress, so… There is more wordpressy way of using AJAX.
All AJAX requests should use admin-ajax.php
file and you should use wp_ajax_{action}
and wp_ajax_nopriv_{action}
hooks to process such requests.
So your code should more like this:
function fun5() {
var mydata = {
action: 'loadmydata',
id1: document.getElementById('city').value
};
$.ajax({
url: LoadDataObject.ajax_url,
data: mydata,
complete: function(data) {
document.getElementById('show1').innerHTML=data.responseText;
}
});
}
And in PHP file you should:
- Define
LoadDataObject
object usingwp_localize_script
:
.
wp_enqueue_script( 'loadmydata-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'loadmydata-script', 'LoadDataObject',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
- Add your processing actions:
.
function loadmydata_callback() {
// ... put your loading code here
}
add_action( 'wp_ajax_loadmydata', 'loadmydata_callback' );
add_action( 'wp_ajax_nopriv_loadmydata', 'loadmydata_callback' );
You can read more on using AJAX in WP here: https://codex.wordpress.org/AJAX_in_Plugins