woocommerce ajax call using a template part - ajax

I have set up a filter for products using ajax. It works fine when using a string as response but not when using a template part.
See below the part of the query
$qry = new WP_Query($args);
$responses = '';
if ($qry->have_posts()) :
while ($qry->have_posts()) : $qry->the_post();
$responses .= wc_get_template_part( 'content', 'product' );
//$responses .= '<h2 class="entry-title">'.get_the_title().'</h2>';
endwhile;
$response = [
'status'=> 200,
'found' => $qry->found_posts
];
else :
$response = [
'status' => 201,
'message' => 'No posts found'
];
endif;
$response['content'] = $responses;
die(json_encode($response));
and below is the ajax call
function get_posts($params) {
$container = $('#container-async');
//$content = $container.find('.content');
$content = jQuery('.products');
$status = $container.find('.status');
$products = $('.products');
$status.text('Loading posts ...');
$.ajax({
url: ajaxurl.ajax_url,
data: {
action: 'do_filter_posts',
nonce: ajaxurl.nonce,
params: $params
},
type: 'post',
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {
if (data.status === 200) {
$content.html(data.content);
console.log(data.content);
}
else if (data.status === 201) {
$content.html(data.message);
}
else {
$status.html(data.message);
}
},
error: function(MLHttpRequest, textStatus, errorThrown) {
$status.html(textStatus);
console.log(MLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
},
complete: function(data, textStatus) {
msg = textStatus;
if (textStatus === 'success') {
msg = data.responseJSON.found;
console.log(data);
}
$status.text('Posts found: ' + msg);
console.log(data);
console.log(textStatus);
}
});
}
In the inspect mode is see the following feedback
SyntaxError: Unexpected token '<', "<li class="... is not valid JSON
Am I calling the template wrong? or do i need to do anything else first?
The ajax function is working when using the return string $responses .= '<h2 class="entry-title">'.get_the_title().'</h2>';
How do I make it work when using the template part?
Thanks in advance!

Related

Get post meta in the Ajax not working in Wordpress

I am doing an Ajax call and return the value. The post id is coming. But when i tried with this code, It is return blank
function visa_status() {
$postid = $_POST['appid'];
// args
$args = array(
'numberposts' => 1,
'post_type' => 'cpt_15',
'meta_key' => 'application_number',
'meta_value' => $postid
);
$metaarry = array();
// query
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$posti = get_the_ID();
endwhile;
//echo $posti;
echo get_post_meta( $posti, 'given_name');
exit();
}
In the above code, $posti is coming. But get_post_meta() is not working.
This is my JS part
onStepChanging: function (event, currentIndex, newIndex) {
if ( newIndex === 1 ) {
jQuery('.wizard > .steps ul').addClass('step-2');
appId = jQuery('#appid').val();
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: my_ajax_object.ajax_url,
data: {
'action': 'visa_status',
'appid': appId,
},
success: function (msg) {
console.log(msg);
}
});
} else {
jQuery('.wizard > .steps ul').removeClass('step-2');
}
if ( newIndex === 2 ) {
jQuery('.wizard > .steps ul').addClass('step-3');
} else {
jQuery('.wizard > .steps ul').removeClass('step-3');
}
return true;
},
Is there any mistake i have done. Please help me in this.
Try this
$given_name = get_post_meta( $posti, 'given_name', true );
echo $given_name;
OR Try this
echo get_post_meta( $posti, 'given_name', true );
Check here what get_post_meta function returns based on 3rd parameter.

Ajax submission triggers Error = True by default even at success

Laravel ajax submission.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '{{URL::to('expense_bill/store2')}}',
method: 'POST',
data: $("#expense_create").serialize(),
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
},
error: function (xhr) {
$('#validation-errors').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
});
},
});
});
Controller:
public function store2(Request $request)
{
if($request->ajax()){
//return response()->json($request);
$validator = Validator::make($request->all(), [
'supplier' => 'required',
]);
if ($validator->fails()) {
$returnArray['error']=true;
$returnArray['err_msg']=json_decode(json_encode($validator->errors()), true);
return $returnArray;
}
if ($validator->passes()) {
$request->merge(['total' => $request->total*100]);
$request->merge(['tax_value' => $request->tax_value*100]);
$expensebillheader = ExpenseBillHeader::create($request->all());
$expense_bill_no = $expensebillheader->id;
$count = $request->input('count');
for ($i = 0; $i <= $count; $i++){
//checks if input with this name exists (incase if any middle row was deleted)
if (isset($request->input('amount')[$i]))
{
$line = new ExpenseBillBody;
$line->bill_no = $expense_bill_no;
$line->description = $request->input('description')[$i];
$line->amount = $request->input('amount')[$i];
$line->account = $request->input('account')[$i];
$line->save();
}
};
$successArray = ['success'=>'true','msg'=>"Expnese No".$expense_bill_no." Created"];
return response()->json($successArray);
}
}
}
When validator fails, it's all fine. When validator passes it is supposed to give success=" true" message. But along with that it also gives error="true" as well. Not sure what am I doing wrong. See in the screenshot, the highlighted portion should not come.
Larave returns correct response. You have error here
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
}
...
if(data['success'] = true) and if(data['success'] = true) isn't comparasion, these are assigning values
Try to write comparasion operators ==
success:function(data){
console.log(data)
if(data['success'] === true){
}
if(data['error'] === true){
//Clear Valdiation Errors
console.log('hi');
}
}
...

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

Code igniter validation- Ajax, error:function work while validation->run is true

Hi I try to make validation form with ajax. When Textbox is empty, There is no problem everything works fine and give right errors. But when I fill in form Ajax else is not working and it goes to error:function . Please could you help!
When I enable dataType:"JSON",
I see output
false
Basvuru:1379 {isim: " İsim Zorunludur!", soyad: " Soyad Zorunludur!", emailadresi: " Email Adresi Zorunludur!", ilce: "", il: "", …}
When I disable dataType:"JSON", ı could see console.log(data) of post datas otherwise goesto error:function
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo $data=json_encode(array("status" => TRUE));
}
}
View Ajax:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success:function (data) {
// var obj = $.parseJSON(data);
// $('#data1').html(data);
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
console.log(data.status);
// alert(data.sonuc);
if(data.status){
console.log("false");
}
else{
console.log("true");
console.log(data);
}
},
error:function(data){
console.log("error");
}
});
}
model:
function basvuru_ekle($data)
{
print_r($data);
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
Remove print_r() in insert function and try this:
function save() {
var url;
if (save_method == 'add') {
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
} else {
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
}
},
error: function(data) {
console.log("error");
}
});
}
I checked to find the exact problem.As Alex said problem was because of Print_r() in modal. After I erased it ,now it works fine.
After fixed the problem.
view:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
$('#modal_form').modal('hide');
location.reload();// for reload a page
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 404) { alert('AJAX page not found.');
}
else {
alert('AJAX Error: ' + textStatus + ': ' + errorThrown); }
}
});
}
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo json_encode(array(
"status" => TRUE,
));
}
}
model:
function basvuru_ekle($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}

stop page reloading when using ajax

I've created a wordpress plugin to vote on a post, using ajax.
When you click the 'vote' link the jquery popup works, your vote is added but then the page reloads
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$user_id = get_current_user_id();
date_default_timezone_set('GMT+2');
$dateVoted = get_user_meta($user_id, 'date');
$today = date('d M Y');
if ($dateVoted === $today){
//Already Voted
echo '<script language="javascript">';
echo 'alert("already voted")';
/*
echo 'alert("User ID: ' . $user_id . '")';
echo 'alert("Date Voted: ' . $dateVoted . '")';
echo 'alert("Today: ' . $today . '")';
*/
echo '</script>';
}else{
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
update_user_meta( $user_id, 'date', $today );
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/video-of-the- day/my_voter_script.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
I also have a jquery file:
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
}
else {
alert("Your vote could not be added")
}
}
});
})
});
why is the ajax not working?
Try this
jQuery(".user_vote").click( function(e) {
e.PreventDefault();
});

Resources