create loadmore for Wordpress with ajax and custom post type? - ajax

I am having some loadmore issues with ajax. Who can help me.
I have code
<button class="load-more">More</button>
Function
add_action('wp_ajax_loadmore', 'get_post_loadmore');
add_action('wp_ajax_nopriv_loadmore', 'get_post_loadmore');
function get_post_loadmore() {
$offset = isset($_POST['offset']) ? (int)$_POST['offset'] : 0;
$getposts = new WP_query(); $getposts->query('post_type=event&post_status=publish&showposts=5&offset='.$offset);
global $wp_query; $wp_query->in_the_loop = true;
while ($getposts->have_posts()) : $getposts->the_post(); ?>
<?php do_action('postthumb1')?>
<?php endwhile; wp_reset_postdata();
die();
}
js
<script>
$(document).ready(function(){
var offset = 4;
$('.load-more1').click(function(event) {
$.ajax({
type : "post",
dataType : "html",
async: false,
url : '<?php echo admin_url('admin-ajax.php');?>',
data : {
action: "loadmore",
offset: offset,
},
beforeSend: function(){
},
success: function(response) {
$('.list-new').append(response);
offset = offset + 5;
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( 'The following error occured: ' + textStatus, errorThrown );
}
});
});
});
</script>
Code working ok but, it load only post_type event. I want to set a variable that can be used for all custom post types.
I tried setting the variable but the code does not work. Does anyone who has experience with ajax can help me?

This will get you all custom post types on the site:
$args = array(
'public' => true,
'_builtin' => false,
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
$args = array(
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => 5,
'offset' => $offset
);
$getpost = new WP_Query( $args );
If you're looking for a certain post_type passed in by the ajax call:
<script>
$(document).ready(function(){
var offset = 4;
$('.load-more1').click(function(event) {
$.ajax({
type : "post",
dataType : "html",
async: false,
url : '<?php echo admin_url('admin-ajax.php');?>',
data : {
action: "loadmore",
offset: offset,
posttype: posttype //Where ever you want to get this from
},
beforeSend: function(){
},
success: function(response) {
$('.list-new').append(response);
offset = offset + 5;
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( 'The following error occured: ' + textStatus, errorThrown );
}
});
});
});
</script>
Function:
add_action('wp_ajax_loadmore', 'get_post_loadmore');
add_action('wp_ajax_nopriv_loadmore', 'get_post_loadmore');
function get_post_loadmore() {
$offset = isset($_POST['offset']) ? (int)$_POST['offset'] : 0;
$posttype = isset($_POST['posttype']) ? $_POST['posttype'] : 'post';
$args = array(
'post_type' => $posttype,
'post_status' => 'publish',
'posts_per_page' => 5,
'offset' => $offset
);
$getposts = new WP_query($args);
global $wp_query;
$wp_query->in_the_loop = true;
while ($getposts->have_posts()) : $getposts->the_post();
do_action('postthumb1');
endwhile;
wp_reset_postdata();
die();
}

Related

Q: how to make form validation codeigniter with ajax?

Hello guys i try to make form validation codeigniter with ajax server side but it still not working, i want to make error message 'required' display under form input. what is it wrong in my code.
this is my controller
function ajax_submit_kategori() {
$this->load->library('form_validation');
$data['nama'] = $this->input->post('kategori');
$data['id_legislator'] = $this->input->post('legislator');
$this->db->insert('galangsuara_has_categories',$data);
$return['status'] = '0';
echo json_encode($return);
}
this is my ajax
<script type="text/javascript">
$('#input').submit(function(event){
event.preventDefault();
Pace.track(function(){
var cate = $('#tim').val();
var dapi = $('#dapil').val();
var legi = $('#legislatif').val();
$.ajax({
url: "<?= site_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
$("#modal_tambah").modal('hide');
document.getElementById("input").reset();
var table = $('#table').DataTable();
table.ajax.reload();
window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});
});
return false;
});
anyone can help me? :(
Try This
Controller code:
function ajax_submit_kategori() {
$status = 1;
$error = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('kategori', 'Kategori', 'required');
$this->form_validation->set_rules('dapil', 'Dapil', 'required');
$this->form_validation->set_rules('id_legislator', 'Id_legislator', 'required');
if ($this->form_validation->run() == FALSE) {
$status = 0;
$error = validation_errors();
} else {
$data['kategori'] = $this->input->post('kategori');
$data['dapil'] = $this->input->post('dapil');
$data['id_legislator'] = $this->input->post('id_legislator');
$this->db->insert('galangsuara_has_categories', $data);
}
$return['status'] = $status;
$return['$error'] = jsone_encode($error);
echo json_encode($return);
exit();
}
ajax code :
$.ajax({
url: "<?= base_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
//here, first you need to check your data is perfect for error then do according to your wish
//$("#modal_tambah").modal('hide');
//document.getElementById("input").reset();
//var table = $('#table').DataTable();
//table.ajax.reload();
//window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});

A simple Ajax call in wordpress doesn't give the expecetd output

Here is my javascript file:-
jQuery(document).ready( function($) {
$('#test_button').click(function(e){
alert("test");
$.ajax({
url : my_ajax_object.ajaxurl ,
type : 'post',
dataType : 'json',
data : {
action : 'do_ga'
},
complete: function(res, status) {
if( status == 'success' ) {
console.log("success "+res);
} else {
console.log("fail "+res);
}
}
});
});
});
here is my php code in functions.php:-
function do_ga() {
die("test" );
}
add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
//this is the script en queuing
function my_enqueue() {
wp_enqueue_script( 'ga-loadmore', get_template_directory_uri() . '/pl-custom/front-end-assets/js/ga-loadmore.js', array('jquery') );
wp_localize_script( 'ga-loadmore', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
So,upon the click of the button with id "#test_button" , instead of outputting success [object][object] , it outputs fail [object][object]. What needs to be done here. Precisely , i want "success test". please add the json_encode and decode wherever required in the solution.Thanks
I've separated the PHP code in another file and included it in functions.php and also separated the enqueuing, and changed the syntax of the request a little. I hereby attach my code and it works:
function do_ga() {//server code
$x="test";
wp_die( $x);
exit;
}
add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
client side(already enqueued):-
jQuery(document).ready( function($) {
$('#test_button').click(function(e){
url = window.location.origin + '/wp-admin/admin-ajax.php?action=do_ga';
alert("test");
$.ajax({
async: true,
type: 'POST',
url: url,
data: {
'my_number':1 //you need not pass data
},
complete: function(res, status) {
if( status == 'success' ) {
alert("success "+ res.responseText);
} else {
alert("unable to process request");
}
}
})
});
});

Post 500 (Internal Server error) ajax in codeigniter

I have a problem to sending data with ajax, when i click button save to sending data to database. but when i push F12 the error show
POST http://[::1]/sys-web/admlogin/manufacture/addmanufacture 500 (Internal Server Error)
send # http://[::1]/sys-web/assets/js/jquery-2.1.4.min.js:4
ajax # http://[::1]/sys-web/assets/js/jquery-2.1.4.min.js:4
save # http://[::1]/sys-web/admlogin/manufacture:374
onclick # http://[::1]/sys-web/admlogin/manufacture:507
CI Controller
public function AddManufacture()
{
$data = array(
'manufacturing_name' => $this->input->post('manufacturing_name'),
'address' => $this->input->post('address'),
'email' => $this->input->post('email'),
'telephone' => $this->input->post('telephone'),
'join_date' => $this->input->post('join_date')
);
$insert = $this->m_manufacture->save($data);
echo json_encode(array("status" => TRUE));
}
CI Model :
function save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
CI View :
function save()
save_method = 'add';
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('admlogin/manufacture/addmanufacture')?>";
} else {
url = "<?php echo site_url('admlogin/manufacture/editmanufacture')?>";
}
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
url : url,
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}

Download maatwebsite excel using ajax in laravel

I'm trying to download an excel file using ajax method in laravel.
Controller function:
$myFile = Excel::create($name, function ($excel) use ($export) {
$excel->sheet('Data', function ($sheet) use ($export) {
$sheet->fromArray($export);
$sheet->cells('A1:N1', function ($cells) {
$cells->setBackground('#dbdbdb');
$cells->setFontColor('#000000');
$cells->setFontWeight('bold');
$cells->setFont(array(
'family' => 'Calibri',
'size' => '9',
));
});
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 9,
),
));
});
});
$myFile = $myFile->string('xlsx');
$response = array(
'name' => $name,
'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($myFile),
);
return response()->json($response);
Ajax function:
$(document).on('click', '.ExportJobs', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var ids = [];
$(".InvoiceCheckBox:checked").each(function(e) {
ids.push(this.value);
});
data = {
"ids": ids,
};
$.ajax({
method: "POST",
url: "/exportNew",
data: data,
success: function(response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
}
});
});
But using above controller method is not returning excel formatted file if I change string value from xlsx to csv then csv formatted file is getting downloaded.
How do we make the excel formatted file downloaded? Any suggestions, Please!
I know this is quite late, but posting for others who struggle with same issue like me
I also needed to download excel from using Maatwebsite excel library by using ajax post call.
added a button to fire the ajax call to download excel file
<button onclick="downloadExcel()" id="btn-download-payroll" class="btn btn-dark-success btn-md" style="transform: translateY(50%); top: 50%; font-size: 13px;"><i aria-hidden="true" class="fa fa-cog mr-10"></i>
Download
</button>
Used following js code to post ajax request
function downloadExcel() {
var salaryMonth = $("#dp-salary-month").datepicker("getDate");
var department = $("#cbox-department");
var month = new Date(salaryMonth).getMonth() + 1;
var year = new Date(salaryMonth).getFullYear();
$.ajax({
xhrFields: {
responseType: 'blob',
},
type: 'POST',
url: '/downloadPayroll',
data: {
salaryMonth: month,
salaryYear: year,
is_employee_salary: 1,
department: department.val()
},
success: function(result, status, xhr) {
var disposition = xhr.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'salary.xlsx');
// The actual download
var blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
in routes/web.php file set the reoute for my controller
Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController#downloadPayroll');
Here I used maatwebsite/excel library to generate excel file with FromQuery approach but due to library update Excel::create has been replaced by Excel::download in "maatwebsite/excel": "^3.1" I used download method in my case here is my HelperClass to generate records according to my requirement
PayrollHelper.php
namespace App\Http\Helpers;
use App\PayrollEmployee;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class PayrollHelper implements FromQuery
{
use Exportable;
public function forDepartment(int $department)
{
$this->department = $department;
return $this;
}
public function forMonth(string $month)
{
$this->month = $month;
return $this;
}
public function query()
{
// get the salary information for the given month and given department
return PayrollEmployee::query()->where(['salary_month' => $this->month,'department_id'=>$this->department]);
}
}
finally in my controller
class PayrollController extends Controller
{
public function downloadPayroll(Request $request)
{
$file_name = '';
try {
$requestData = $request->all();
$salary_month = $requestData['salaryMonth'];
$salary_year = $requestData['salaryYear'];
$department = $requestData['department'];
$is_employee_salary = boolval($requestData['is_employee_salary']);
$month = Carbon::createFromDate($salary_year, $salary_month);
$month_start = Carbon::parse($month)->startOfMonth();
$formated_month = Carbon::parse($month)->format('F Y');
$file_name = 'Employee_salary_' . $formated_month . '.xlsx';
// to download directly need to return file
return Excel::download((new PayrollHelper)->forMonth($month_start)->forDepartment($department), $file_name, null, [\Maatwebsite\Excel\Excel::XLSX]);
} catch (exception $e) {
}
}
}
After creating excel file return file to get as ajax response as blob
That's all
Just see the xhrFields to set responseType as blob and then see the ajax success part. Hope you everyone find the solution:
<script>
$(document).ready(function(){
$("#ExportData").click(function()
{
dataCaptureExport();
});
});
function dataCaptureExport(){
var FromDate = $('#dateFrom').val();
var ToDate = $('#dateTo').val();
var dataString = { FromDate: FromDate, ToDate:ToDate, _token: '{{csrf_token()}}'};
$.ajax
({
type: "POST",
url: '{{ route('invoice_details_export') }}',
data: dataString,
cache: false,
xhrFields:{
responseType: 'blob'
},
success: function(data)
{
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = `Invoice_details_report.xlsx`;
link.click();
},
fail: function(data) {
alert('Not downloaded');
//console.log('fail', data);
}
});
}
It's late but help for others
You can do this way
In Ajax
$(document).on('click', '#downloadExcel', function () {
$("#downloadExcel").hide();
$("#ExcelDownloadLoader").show();
$.ajax({
url: '{{ route("admin.export_pending_submitted_tasks") }}',
method: "GET",
cache: false,
data: {
search_partner,
search_state,
search_city,
_token,
},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
},
error: function (ajaxContext) {
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
alert('Export error: '+ajaxContext.responseText);
}
});
});
In Controller
// Get pending submitted tasks export excel
public function export_pending_submitted_tasks(Request $request){
$input = $request->input();
$pending_submitted_tasks = SubmittedTask::select('id', 'partner', 'se_id', 'description', 'created_at', 'status', 'updated_at');
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('partner_id', $input['search_partner']) : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('state', 'like', '%'.$input['search_state'].'%') : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('city', 'like', '%'.$input['search_city'].'%') : '';
$pendingTaskList = $pending_submitted_tasks->where('status', 'pending')->get();
if($pendingTaskList->count() > 0):
$myFile = Excel::raw(new ExportPendingTaskHelper($pendingTaskList), 'Xlsx');
$response = array(
'name' => "Pending-Task-List.xlsx",
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($myFile)
);
return response()->json($response);
else:
return back()->with('message', 'No Pending tasks available to download!!');
endif;
}
If you are using jquery:
// In controller:
return Excel::download(new SomeExport, 'Some_Report.xlsx', null, [\Maatwebsite\Excel\Excel::XLSX]);
// Ajax:
$.ajax({
type: 'GET',
url: '{{ route("some.route") }}',
data: {
"_token": "{{ csrf_token() }}"
},
xhrFields:{
responseType: 'blob'
},
beforeSend: function() {
//
},
success: function(data) {
var url = window.URL || window.webkitURL;
var objectUrl = url.createObjectURL(data);
window.open(objectUrl);
},
error: function(data) {
//
}
});

Istotope ajax content load

I'm stuck implementing load next set of posts in WordPress with isotope masonry layout.
It's just not triggered for appended elements and I can't figure out why.
If someone could point me in right direction I would appreciate.
jQuery AJAX function
function load_content( args ) {
$container = $('#container-async');
$status = $('.status');
$.ajax({
url: ajax_url,
data: {
action: 'do_load_posts',
nonce: nonce,
args: args
},
type: 'post',
dataType: 'json',
success: function( data, textStatus, XMLHttpRequest ) {
$items = data.posts;
if ( args.action === 'filter') {
/**
* Replace items
*/
$container.imagesLoaded( function() {
$container.isotope({
itemSelector: '.grid-item',
percentPosition: true,
masonry: {
columnWidth: '.grid-sizer'
}
});
$container.html( $items ).isotope( 'appended', $items, function() {
console.log('inserted');
});
});
}
else {
/**
* Append items
*/
$container.imagesLoaded( function() {
$container.isotope({
itemSelector: '.grid-item',
percentPosition: true,
masonry: {
columnWidth: '.grid-sizer'
}
});
$container.append( $items ).isotope( 'appended', $items, function() {
console.log('appended');
});
});
}
},
error: function( MLHttpRequest, textStatus, errorThrown ) {
$status.toggleClass('active');
}
});
}
WordPress AJAX:
function ajax_do_load_posts() {
// Verify nonce
if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'nonce' ) )
die('Permission denied');
$response = [
'status' => 500,
'posts' => 0,
];
$filter = $_POST['args'];
$type = get_post_type_object( $filter['type'] );
$args = [
'post_type' => sanitize_text_field($filter['type']),
'paged' => intval($filter['page']),
'posts_per_page' => $filter['qty'],
];
$qry = new WP_Query($args);
if ($qry->have_posts()) :
ob_start();
while($qry->have_posts()) : $qry->the_post(); ?>
<div class="grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3">
<?php get_template_part('templates/loop', 'card' ); ?>
</div>
<?php endwhile;
$response = [
'status' => 200,
'posts' => ob_get_clean(),
];
endif;
wp_reset_query();
wp_reset_postdata();
die(json_encode($response));
}
add_action('wp_ajax_do_load_posts', 'ajax_do_load_posts');
add_action('wp_ajax_nopriv_do_load_posts', 'ajax_do_load_posts');
Items are inserted or appended into container but masonry is triggered only on items that are already there on page load.
I have googled around and tried various solutions but none of them work, neither with isotope or masonry jquery plugin.
I was able to fix my issue, and kind of looks like the problem is because I was using jQuery default append/insert methods.
I have switched to isotope methods and now things look fine.
So basically instead of
$container.html( $items ).isotope( 'appended', $items, function() {
console.log('inserted');
});
I am now using:
$grid.isotope('insert', jQuery($items));
It looks logical actually that isotope cannot know items are appended if I don't use isotopes append/insert method. And notice that I also wrapped $items inside jQuery.
Anyhow my working JS for same PHP function is:
function load_content( args ) {
$container = $('#container-async');
$status = $('.status');
$.ajax({
url: ajax_url,
data: {
action: 'do_load_posts',
nonce: nonce,
args: args
},
type: 'post',
dataType: 'json',
success: function( data, textStatus, XMLHttpRequest ) {
$items = data.posts;
var $grid = $('.masonry').imagesLoaded( function() {
$grid.isotope({
itemSelector: '.grid-item',
percentPosition: true,
masonry: {
columnWidth: '.grid-sizer'
}
});
if ( args.action === 'filter') {
$grid.isotope('remove', $('.grid-item'));
}
$grid.isotope('insert', jQuery($items));
});
$grid.on( 'layoutComplete', function( event, laidOutItems ) {
$container.removeClass(data.action);
});
},
error: function( MLHttpRequest, textStatus, errorThrown ) {
$status.toggleClass('active');
}
});
}

Resources