I created a JavaScript function that uses AJAX to call a CodeIgniter controller function that calls the model and retrieves data from the database and is returned as json.
I have successfully created it and have the data rendered using jQuery Template plugin, but I encounter errors when I move the View which renders the data from the index() function into a different function.
ajax goes into error and gives the status of 200.
below is the code:
<?php
class Scheduler extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Scheduler_model');
}
public function index() {
$this->load->view('templates/header');
$this->load->view('Rooms_view'); //data appears/gets rendered here
$this->load->view('templates/footer');
}
public function rooms() {
$this->load->view('templates/header');
$this->load->view('Rooms_view'); //error is encountered here
$this->load->view('templates/footer');
}
public function read($table) {
echo json_encode( $this->Scheduler_model->getAll($table) );
}
JavaScript/jQuery:
var readUrl = 'scheduler/read',
createUrl = 'scheduler/create',
updateUrl = 'scheduler/edit',
delUrl = 'scheduler/delete',
delHref,
delId,
updateHref,
updateId;
$(document).ready(function() {
var pathname = window.location.pathname;
if (pathname == '/MobileSchedule/scheduler/rooms'){ read('rooms'); }
//if i call read("rooms") here, it appears on index(), but errors on rooms()
}); //end Document ready
function read(table) {
$( '#ajaxLoader' ).fadeIn( 'slow' );
$.ajax({
url: readUrl + '/' + table,
dataType: 'json',
success: function( response ) {
for( var i in response ) {
response[ i ].updateLink = updateUrl + '/' + response[ i ].id;
response[ i ].deleteLink = delUrl + '/' + response[ i ].id;
}
//clear old rows
$( '.roomsList' ).html( '' );
//append new rows
$( '#roomsTemplate' ).render( response ).appendTo( '.roomsList' );
$( '#ajaxLoader' ).fadeOut( 'slow' );
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(thrownError);
}
});
}
Related
I'm trying to add jQuery to the javascript.js file for a child of woodmart theme, but I keep getting "javascript.js:131 Uncaught ReferenceError: jQuery is not defined".
javascript.js
(function($){
jQuery(document).ready(function($) {
//cart_actions parent container
//for POST requests when user saves a cart
clickparent = document.querySelector(".cart-actions");
clickparent.addEventListener("click", function(e) { // e = event object
let carts = JSON.parse(window.localStorage.getItem('yithPOS_carts'));
if (e.target && (e.target.className == "cart-action cart-action--suspend-and-save-cart cart-action--with-icon") || e.target.className == "cart-action__icon yith-pos-icon-saved-cart") {
// Use ajax to do something...
var postData = {
action: 'wpa_49691',
my_var: 'carts',
}
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
console.log("Cart saved to database.");
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
//pos_current_Cart_buttons parent container
//for GET requests when user views saved carts
viewcartparent = document.querySelector(".yith-pos-cart__buttons");
viewcartparent.addEventListener("click", function(e) { // e = event object
if (e.target && (e.target.className == "yith-pos-cart__buttons-saved-carts")) {
// Use ajax to do something...
var getData = {
action: 'wpa_49692',
my_var: 'my_data',
}
$.ajax({
type: "GET",
data: getData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
let total;
for(item in response){
total += item[lineTotal];
}
$(".yith-pos-cart__savedcarts").append('</div><i class="yith-pos-cart__savedcart"></i><div class="cart-saved__name"><div class="cart-saved__name__id">' + response['id'] + '</div><div class="cart-saved__name__customer">' + response['cartitems']['names'] + '</div></div><div class="cart-saved__num_of_items">' + response['cartitems'].size + '</div><div class="cart-saved__status">Pending Payment</div><div class="cart-saved__total">'+ total + '</div><button class="btn btn-primary"><i class="yith-pos-icon-refresh"></i> load</button></div>');
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
// Handler for .ready() called.
});
})(jQuery);
I've also tried enqueuing jquery with wp_enqueue_script and passing jquery in an array to the javascript file, neither changed anything.
functions.php:
wp_enqueue_script('jquery');
//First enqueue your javascript in WordPress
function save_cart_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'javascript.js', plugins_url('https://cigarchiefstg.wpengine.com/wp-content/themes/woodmart-child/yith-pos-additions/javascript.js', dirname(__FILE__) ), array( 'jQuery' ));
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'javascript', 'javascript_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'javascript_vars.ajaxurl' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'save_cart_enqueue_scripts' );
//This is your Ajax callback function
function cart_save_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
update_option('saved_carts', $my_var);
//Create the array we send back to javascript here
$return_array = array();
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $return_array );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49691', 'cart_save_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49691', 'cart_save_callback_function' );
function cart_view_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
//Create the array we send back to javascript here
$carts = get_option('saved_carts');
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $carts );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49692', 'cart_view_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49692', 'cart_view_callback_function' );
Edit: Issues with POS items:
first check if jquery is correctly loaded on you wp website.
I suggest using this syntax for jQuery:
(function($){
$(document).ready(function(){
//your code
})(jQuery);
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
This is my code at www.domain-a.de/external.search.js. I call it from www.domain-b.de/test.php:
(function ($) {
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
var frm = $('#embedded_search form');
// click on submit button
frm.submit(function (ev) {
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
});
})(jQuery);
After running this code I don't get any message in console. What is wrong with that code?
frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.
Your code is not calling the submit handler on the item, it is simply binding it. You should do the frm.submit(function binding outside of your $.getJSON callback; then inside the callback add
frm.submit()
Which triggers the event.
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload.
After the line
frm.submit(function (ev) {
Add
ev.preventDefault();
So your overall code should be
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);
I am building coupon website. I need to trigger ajax action based on url of page. Let me explain.
For example, if user goes to page website_url/?coupon_id=99 - he gets page website_url and popup with ajax action inside it (ajax gets data for coupon post type with id=99 and show it's values).
If user goes to page website_url/page1/?coupon_id=99 - he gets page website_url/page1/ and the same popup.
You can see this logic in action on some coupon websites, for example, coupondunia.in
I created ajax action, it's working
function coupon_get_code(){
$couponid = $_GET['couponid'];
$code = get_post( $couponid );
if( !empty( $code ) ){
$offer_coupon = get_post_meta( $code->ID, 'coupon', true );
$response .= '<div class="coupon_modal_coupon">'.$offer_coupon.'</div>';
}
else{
$response = __( 'Offer does not exists', 'textdomain' );
}
echo $response ;
die;
}
add_action('wp_ajax_ajax_code', 'coupon_get_code');
add_action('wp_ajax_nopriv_ajax_code', 'coupon_get_code');
Currently I made triggering ajax action based on click, like this
// Coupon Modal
$( '.offer_coupon.masked_coupon:not(.expired_coupon)' ).live("click", function(e){
var $this = $(this);
var couponid = $this.data('couponid');
$.pgwModal({
url: translation.ajax_url + "?action=ajax_code&couponid=" + couponid,
titleBar: false,
ajaxOptions : {
success : function(response) {
if (response) {
$.pgwModal({ pushContent: response });
} else {
$.pgwModal({ pushContent: 'An error has occured' });
}
}
}
});
});
But how to trigger this ajax request based on url?
You could get the last number characters from the URL on page load (equal to the coupon id), instead of getting it on click from the data attribute.
$(window).on('load', function() {
// Get the last numbers from the current page URL using Regex
var couponid = window.location.href.match(/\d+$/);
$.pgwModal({
url: translation.ajax_url + "?action=ajax_code&couponid=" + couponid,
titleBar: false,
ajaxOptions : {
success : function(response) {
if (response) {
$.pgwModal({ pushContent: response });
} else {
$.pgwModal({ pushContent: 'An error has occured' });
}
}
}
});
});
Put the jQuery in a file named ajax-coupon.js and conditionally enqueue the script.
// Conditionally enqueue your script only if the template coupons.php is used to display the page.
function my_scripts_method() {
// Register your script location, dependencies and version
wp_register_script('ajax-coupon', get_template_directory_uri() . '/js/ajax-coupon.js', array('jquery'), '1.0' );
// Check if the current page is using coupons.php, if so, load the script.
if ( is_page_template( 'coupons.php' ) ) {
wp_enqueue_script('ajax-coupon');
}
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
I think I found function which can help me. Testing now.
function GetURLParameter(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
So my ajax trigger can be like this
var coupontrigger = GetURLParameter("couponid");
if(coupontrigger){
$.pgwModal({
url: translation.ajax_url + "?action=ajax_code&couponid=" + coupontrigger,
titleBar: false,
ajaxOptions : {
success : function(response) {
if (response) {
$.pgwModal({ pushContent: response });
} else {
$.pgwModal({ pushContent: 'An error has occured' });
}
}
}
});
};
The question I am asking is a basic question because I am new in json and ajax.
so I have a json data of name , task , date and status I am getting data through ajax but it is not showing in on my page.
my ajax code is this:
$(document).ready(function(e) {
// Using the core $.ajax() method
$.ajax({
url: "getdata.php",
type: "GET",
dataType : "json",
success: function( json ) {
$( "<h1/>" ).text( json.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.task ).appendTo( "body" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
this is my json data:
[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
I don't know why It is not appending html data but it is showing complete alert.
I have added fiddle even if it is not working.
Fiddle
Ok, i see you actually getting results so i guess you do have a success. You do have a flaw though. You are trying to access properties directly, but your json is an array of objects and not an object.
You need to do a foreach itteration.
json.forEach(function (entry) {
$( "<h1/>" ).text( entry.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( entry.task ).appendTo( "body" );
});
Edit Your Json like
{
"jsontext":[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
}
and the ajax code should be as
$.ajax({
url: '/getdata.txt',
complete: function (data) {
if (data.responseText != "") {
var NewTxt = data.responseText;
NewTxt = NewTxt.replace(/\n/g, "");
NewTxt = NewTxt.replace(/\s/g, "");
obj = JSON.parse(NewTxt);
var NewStr = "";
for (var i = 0; i < obj.jsontext.length; i++) {
NewStr += obj.jsontext[i].name + "<br/>" + obj.jsontext[i].task + "<br/>" + obj.jsontext[i].date + "<br/>" + obj.jsontext[i].status + "<br/><br/>";
}
document.getElementById("demo").innerHTML = NewStr;
}
}
});
and the HTML as:
<div id="demo"></div>