Wordpress FrontEnd Ajax return 0 using Theme - ajax

Hi I know this has been asked a few times but I have been through every answer and tried them all with no luck.
I am trying to use Ajax in a Wordpress front end page, I have security in the page to ensure the user is logged in before they can view this page too.
No matter what code i enter my ajax call always returns 0.
function ajaxfoodlookup()
{
echo "ajax fired";
die();
}
add_action('wp_ajax_nopriv_ajaxfoodlookup','ajaxfoodlookup');
add_action('wp_ajax_ajaxfoodlookup','ajaxfoodlookup');
This is what I have in my functions.php (i have also tried exit(); and die($results) where $results = 'ajax fired'; nothing seems to work.
This is what I have in the page to call the ajax;
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: { action:'ajaxfoodlookup'},
success: function (data) { alert(data);}
});
The only thing that I have different to the other questions/answers on here is that I am using a bought Theme which does have some code added, is that theme able to hijack my ajax calls? I thought wordpress would execute the ajax call depending on the 'action' in the data supplied?
Please help its driving me crazy?
Thanks

Official WordPress recommendation is to use the ajaxurl variable instead of hard coded one. Insert this before your JS code and change the url of your jQuery.ajax to use ajaxurl.
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
You can also use wp_localize_script to define the ajaxurl

Related

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

KNP Paginator and sortable with ajax

Is it possible to simply run the knp paginator with ajax? Is it possible at all and what is the best way to do it ?
Greetings Michael
Not sure if this is best solution, but I did it this way:
$(function(){ $('#dish-select-component-canvas').on('click', "ul.pagination a" , function(e){
$.ajax({
type: "GET",
url: $(this).attr('href'),
})
.done(function( msg ) {
$('#dish-select-component-items').html(msg);
});
e.preventDefault();
});
});
#dish-select-component-canvas is container for page. When somebody click on this canvas on link in ul.pagination (pagination is class used by knpPaginator by default as wrapper for pagination), I take href attribute of that link, and send it with ajax GET request.
Result of that request goes to appropriate div (here to #dish-select-component-items). Of course you must remember to add e.preventDefault() to prevent browser from reloading the page.

I need some help about ajax in wordpress always return 0

This is the first time I try ajax in wordpress. I need some help.
in my theme's functions.php, I have:
function returnRandomPosts(){
echo '123';
die();
}
add_action('wp_ajax_returnRandomPosts', 'returnRandomPosts');
add_action('wp_ajax_nopriv_returnRandomPosts', 'returnRandomPosts');
and in my single.php file, I have
<script type="text/javascript">
jQuery(document).ready(function($){
$.post("<?php echo admin_url("admin-ajax.php"); ?>", {"action": "returnRandomPosts"}, function(response) {
alert('response: ' + response);
});
});
</script>
When I run the web page, it always alert "response: 0",
I hope you can give me some hints or tips, thank you.
update:
I checked the has_filter function,
the new wp_ajax_XXXXX has successfully add into $wp-filters,
BUT when I call AJAX into wp-admin/admin-ajax.php, has_filter function return false with wp_ajax_XXXXX
Anyone can give me some hint?
Finally, I solved the problem.
I have a plugin, the function is, to preview another theme by adding "theme=name_of_theme" argument to url.
( For example, preview my homepage with "xxx.xx.xx/?theme=name_of_theme" )
The ajax failed in preview.
While I add the same ajax function code to the online page (ie. activated theme), it successes.
I hope my experience may help somebody.

ajax submit form using cakephp

this is my ajax script which i used in codeigniter to send form data without page refresh
now i want to know how can i submit form in cakephp 2x using ajax.. i dont want to use cakephp helper or other difficult methods which i find difficult ... please do some changes in this script or if is possible to send data through changes of this script little bit because i find this easy ...
$('#submit').click(function() {
form = $("#form").serialize();
$.ajax({
type: "POST",
url: "<?php echo site_url('categoryController/addCategory'); ?>",
data: form,
success: function(data){
$(".success").fadeIn(500).delay(2000).fadeOut(500);
$("#form")[0].reset();
}
});
event.preventDefault();
return false;
});
here i have posted my answer ... i did it on my own and it works.. hope it helps others
Can't get ajax to work in CakePHP

jQuery(document).ready() won't work on AJAX loaded jQuery-UI widgets

I am loading some code with the jQuery.ajax() method. In this code I want to have some jQuery-UI Widgets (sliders and calenders) but they won't appear in IE.
Here some example code where you maybe can help me to understand where I am going wrong.
The Code which will load the jQuery-UI Widgets
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
}
});
});
</script>
The Code which is loaded and SHOULD initialize the jQuery-UI Widgets
<script>
jQuery(document).ready(function(){
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
});
</script>
<div class="datepicker-div">
<div class="slider-div">
You can see that it should be very simple. For FF it works fine but not for IE.
Maybe it has nothing to do with the document-ready statement?
Just call the initializers in the success event:
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
}
});
});
</script>
Of course, you should refactor that by having a function for initializations:
function Initialize(){
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
}
Then have your success call it, as well as the ready() ebent:
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
Initialize();
}
});
});
</script>
Update
I have read your question more carefully and now I fully understand it. Your ready() is in the loaded code. Then you should be using jQuery's load():
Script Execution
When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed. An example of both cases can be seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
Try removing the scripts prior to appending the html, then adding them back.
var outHTML = data.replace(/<script>/ig,"<div class='script'>").replace(/<\/script>/ig,"</div>");
outHTML = $(outHTML);
var script = outHTML.find("div.script").detach();
$(".somediv").html(outHTML);
var s = document.createElement("script");
s.textContent = script.text();
document.body.appendChild(s);
Edit:
.find("div.script") may need to be changed to .filter("div.script") based on what your ajax request is returning.
Ok, I didn't found out how i can solve the Problem, but i found a work around.
The work around is very simple. Because in every browser except for the IE the loading of the script via ajax works fine, we have to identify the IE and change the behaviour to not loading the script but redirect to the site I wanted to load. I am doing this all in Joomla 2.5, so there was a bit work to do but basically it was the following code wich solved the problem.
// preparing the url
// check for ie
if (jQuery.browser.msie) {
window.location(url);
} else {
// do the ajax
}

Resources