Ajax PHP Class Structure WordPress data: { action : 'ds_calculators::myfunction', }, - php

It's been a while since I've worked with AJAX and Wordpress. The way I used to do things was pretty straight forward and using the function name where the function is created within functions.php then I add action using :
add_action('wp_ajax_nopriv_myfunction', 'myfunction');
add_action('wp_ajax_myfunction', 'myfunction');
I'm drawing a blank here as now I structure my PHP code a little different and my function is no longer located in my functions.php file. It's located within a class named:
ds_calculators
$.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: { action : 'ds_calculators::myfunction', },
success: function(data, textStatus, XMLHttpRequest)
{
//jQuery('#table_listing').html(''); // empty an element
jQuery('.changer').html(data); // put our list of links into it
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
if (typeof console === "undefined")
{
console = {
log: function() {},
debug: function() {},
};
}
if (XMLHttpRequest.status == 404)
{
console.log('Element not found.');
}
else
{
console.log('Error: ' + errorThrown);
}
}
});
I now add action like this
add_action('wp_ajax_nopriv_myFunction', 'ds_calculators::myFunction');
add_action('wp_ajax_myFunction', 'ds_calculators::myFunction');
For the above I'm hitting a 400(Bad Request). How does one include the function name when that function is within a class? Is that my issue or is something else my issue?

Related

Uncaught TypeError: a.split is not a function pagecontainer

Spend a couple of days now on trying to get swipe on a php website with dynamic content. I've been looking at jQuery mobile but there is no example out the how to get swipe to work with dynamic content. Anybody that can point in a direction how to accomplish this? Does not have to be jQuery mobile it could be anything as long as they have an example to work after. This is what I've accomplished with jQuery mobile and it of course doesn't swipe nice with animation but do load the content on swipe.
$(document).on('swipeleft', '.ui-page', function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
getartikel('1');
}
});
getartikel() is a function that runs an ajax request getting the data from mysql and put it in a div.
function getartikel(id) {
$.ajax({
url: "ajax/getartikel.php",
type: "post",
data: {id:id} ,
success: function (data) {
$("#artikel").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
It is a bunch of articles that I want to be able to swipe between. data from the database I just HTML.
Pagecontainer is what I understand I must use but I can't figure out how to get that to work with a ajax call.
done some change to my code but still no slide, now I get Uncaught TypeError: a.split is not a function. It comes up when I add
$.mobile.pageContainer.pagecontainer('change', "#"+sida, {transition: 'slide'});
here is my complete code
<script>
$(document).on("pageshow", function (event) {
getartikellist();
//this get the menue and put into a ul listview with the class artikel
});
$(document).ready(function(){
$(document).on("click", \'[class^=artikel]\', function(event, ui) {
$("#menyn").panel("close");
getartikel($(this).data(\'secid\'));
});
});
</script>
function getartikel(id) {
var sida;
if($.mobile.activePage.attr("id")=="1"){
sida="2";
}else{
sida="1";
}
$.ajax({
url: "ajax/getartikel.php",
type: "post",
data: {id:id} ,
beforeSend: function() {
$.mobile.loading("show");
},
success: function (data) {
$("#innehall"+sida).html(data);
},
complete: function() {
$.mobile.loading("hide");
$.mobile.pageContainer.pagecontainer('change', "#"+sida, {transition: 'slide'});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
Everything works fine until I add the pagecontainer row, It adds the content to the right page and all.

Codeigniter scripts loading twice/not being removed with partial views

So, I load partial views inside the "main" view, and put the content inside a div, like this:
<div class="page-content" id="inside_page"></div>
<script>
$("#myTab").click(function() {
location.hash="myTab";
App.blockUI({
boxed: !0
});
$.ajax({
type: 'POST',
url: "<?php echo base_url();?>"+"index.php/welcome/myTabContent",
data: {},
dataType: "html",
success: function(data) {
if (data.status == 2) {
window.location = "/";
}else{
window.scrollTo(0, 0);
App.unblockUI();
$("#inside_page").empty();
$("#inside_page").html(data);
}
},
error: function (xhr, status, errorThrown) {
App.unblockUI();
bootbox.alert("<p>Error</p>");
}
});
});
</script>
The partial view includes tags, and when I change tabs, or load the tab again, scripts that have been already loaded, will not be removed and will keep running until the user reloads the page. How can I stop that from happening?

How to call function written in main file into ajax file in php & jquery

Written a Jquery function in main file (index.php) & want to call same function in ajax file that is called from main file.
if the function in the main page and you inject ajax to container inside it, the function need to be available for calling, in the end of the ajax file add
function() //main function
you can also choose another approach after the ajax success you can call the function directly... by passing it as callback for example:
ajax(url,mainFunction,true)
function ajax(url, callback, async) {
var date = new Date();
var ticks = date.getTime();
if (url.indexOf('?') == -1)
url = url + "?tick=" + ticks;
else
url = url + "&tick=" + ticks;
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
async: async == undefined ? true : async,
success: function (data) {
if (data != undefined)
callback(data);
},
error: function (xhr, textStatus, errorThrown) {
//throw error
},
complete: function () {
}
});
}

Ajax Doesn't give me anything in the console?

Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.

jQuery AJAX loads twice

I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});

Categories