I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.
Related
Trying out AJAX request for the first time and facing problem. I want to load a php file on button click in Wordpress site. So far after researching, I got this code:
index.php file:
<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>
ajax.php file (the file i want to be loaded):
<?php echo "Hello!" ?>
functions.php file:
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script('menu_toggle', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
// Grab php file output from server
ob_start();
include(get_template_directory_uri() . '/ajax.php');
$result['content'] = ob_get_contents();
$result = json_encode($result); // use wp_send_json instead to make this shorter
echo $result;
die();
}
menu_toggle.js file (js file with ajax code):
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(response.content);
}
});
});
I can actually get alert('Load was performed.'); and $('#ajax').append("hello"); displaying, so that means that ajax was connected right way and ajax request is working correctly. But $('#ajax').load(response.content); loading whole same index page in #ajax div instead of loading the content of ajax.php file i actually want. I probably got the wrong code either in function tablo() of functions.php file, or in ajax code of menu_toggle.js file. Can someone please help with this one?
You need to convert/parse the json data in JS coming from PHP. Like :
var res = JSON.parse(response);
The full code look like :
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
var res = JSON.parse(response);
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(res.content);
}
});
});
Chetan Vaghela just helped with this problem on wordpress.stackexchange.com. If someone encounters with same problem as i had, please check Chetan Vaghela's answer below:
Solution provided by Chetan Vaghela on wordpress.stackexchange.com
I am created a external js file for plotting a graph in codeigniter. My controller is reached in js file. but the ajax in that file is not supported. here i am attaching the ajax code.`
$(document).ready(function () {
var baseurl = "<?php echo base_url(); ?>";
$.ajax({
url : baseurl + "Welcome/pidiagram",
type : "GET",
success : function (data) {
alert("data");
console.log(data);
}
)};
});
the control is reached inside the document ready function but not inside the ajax.
so please help me.....
most likely your js File won't get parsed by PHP since you outsourced it in an own file
the only thing i'd suggest here is, to add your base URL as an attribute to the html tag e.g.
<html data-base-url="<?php echo base_url(); ?>">
and after that its pretty simple
$(document).ready(function ()
{
var baseurl = $('html').attr('data-base-url');
$.ajax({
url : baseurl + "Welcome/pidiagram",
type : "GET",
success : function (data) {
alert("data");
console.log(data);
}
)};
});
i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>
I am trying to show the value of ajax response inside a div and for that I have the following code in my view file.
<script type="text/javascript" src="MY LINK TO JQUERY"></script>
<script type="text/javascript">
$(function(){ // added
$('a.vote').click(function(){
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id="+a_href,
success: function(server_response){
if(server_response == 'success'){
$("#result").html(server_response);
}
else{
alert('Not OKay');
}
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
<a href="1" title="vote" class="vote" >Up Vote</a>
<br>
<div class="result"></div>
my Controller (to which the ajax is sending the value):
function hello() {
$id=$this->input->post('id');
echo $id;
}
Now what I am trying achieve is get the server_response value (the value that is being sent from the controller) in side <div class="result"></div> in my view file.
I have tried the following code but its not showing the value inside the div.
Could you please tell me where the problem is?
The problem is that you have mixed arguments of Ajax success handler. First goes data which your script gives back, then goes textStatus. Theoretically it can be "timeout", "error", "notmodified", "success" or "parsererror". However, in success textStatus will always be successful. But if you need to add alert on error you can add error handler. And yes, change selector in $("#result") to class. So corrected code may look like this:
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id=" + a_href,
success: function(data, textStatus) {
$(".result").html(data);
},
error: function() {
alert('Not OKay');
}
});
success: function(server_response) {
$(".result").html(server_response);
}
<div class="result"></div> // result is the class
The selector should be .result not #result
Try changing <div class="result"></div> to <div id="result"></div>, because that's what you're referencing in your ajax success function
$("#result").html(server_response);
I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won't find the callback function
Try to change :
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response)
To :
jQuery.post(ajaxurl, data, function(response)
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed.
Read this
Edit
admin-ajax always return default '0' as output.so while you alerting response you will 0 only.using die() in callback function will terminate that.
Had the same problem, it turned out that my callback was inside a php file which was only included to my "Theme Options" page.
To check if the function is able to trigger trougth admin-ajax.php try to add var_dump(function_exists("your_callback_name")); to the bottom of the wp-admin/admin-ajax.php (before die( '0' );) and then have a look to your ajax output.
Try the following code in your plugin file. or in function.php
jQuery(document).ready(function($){
var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
var dataString = 'action=mnd_news';
$.ajax({
type: "POST",
url: ajaxURL,
data: dataString,
cache: false,
success: function(response){
if(response != 'error') {
alert(response);
}
}
});
});
add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' );
function get_mnd_ajax() {
echo "test";
die();
}