load mypage.php via ajax into a div in wordpress - ajax

i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?

I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})

If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}

Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");

Related

WordPress API functions not working at AJAX functions.php call

I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories.
So far, I have the client-side code that works when not calling a WP function (this code is in a theme page):
jQuery('#cat-location-main').change(function () {
var optionSelected = jQuery(this).find('option:selected');
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
console.log(valueSelected);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'myajax-get-subcat',
category: valueSelected,
// send the nonce along with the request
categoryNonce: '<?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?>'
},
success: function(data, textStatus, jjqXHR) {
console.log(data);
},
dataType: 'json'
});
});
And I have this in the functions.php:
add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat');
function myajax_get_subcat() {
$nonce = $_POST['categoryNonce'];
$main_category = $_POST['category'];
if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce'))
die ( 'Busted!');
if(function_exists('wp_dropdown_categories')==true) {
echo 'true';
} else {
echo 'false';
}
wp_dropdown_categories('taxonomy=category&selected=1&echo=1&orderby=NAME&order=ASC&hide_empty=0&hide_empty=0&hierarchical=1&depth=1&id=cat-location-secondary&child_of='.$main_category);
exit;
}
Now I get a "true" on the client side when commenting wp_dropdown_categories line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup).
Also, not working even if I add require_once(__DIR__.'/../../../wp-load.php'); but it works if I use GET in browser (for the functions.php).
Any help would be greatly appreciated!
My problem was because I do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't.

Wordpress Ajax returns 0 from PHP data but the ajax is working

Everytime I click Submit the popup alert only ever gives me a value of 0, also the console never logs what I echo from the php function. The String "Monkey" below does appear in the html, but the data variable doesnt work. (note: I've omitted the full ajax URL from public display)
In my WP plugin I've put this code:
function register_bio_script(){
wp_register_script('bio-script',plugins_url('js/bio-script.js',__FILE__), false, '1.0.0', 'all');
}
add_action('init','register_bio_script');
function enqueue_bio_script(){
wp_enqueue_script( 'bio-script', plugin_dir_url(__FILE__) . 'js/bio-script.js' );
}
add_action('wp_enqueue_scripts', 'enqueue_bio_script');
add_action( 'wp_ajax_nopriv_ MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_ MyAjaxFunction', 'MyAjaxFunction' );
function MyAjaxFunction(){
$GreetingAll = $_POST['GreetingAll'];
echo "peanut";
$results = "<h2>".$GreetingAll."</h2>";
die($results);}
and then i have the JS:
jQuery(document).ready(function() {
var GreetingAll = jQuery("#GreetingAll").val();
jQuery("#PleasePushMe").click(function(){
jQuery.ajax({
type: 'POST',
url: '.../wp-admin/admin-ajax.php',//the full url goes here
data: {
action: 'MyAjaxFunction',
GreetingAll: GreetingAll
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#test-div1").html('');
jQuery("#test-div1").append("Monkey");
alert(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
solved! i had to use wp_localize_script() for frontend ajax. wp ajax only works for backend users unless the script is localized.
the actual coding is complex but all the answers are
in this tutorial http://www.benmarshall.me/wordpress-ajax-frontend-backend/

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

Ajax in Wordpress plugin

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();
}

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources