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!
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');
}
}
...
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();
}
Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached
I'm trying to handle the form and some extra data sent with ajax.
Here is my ajax post code :
$(document).on('submit', '#edit-entreprise', function (e) {
e.preventDefault();
var $entreprise = $("#liste-entreprises").val();
var $url = Routing.generate('load_edit_entreprise_form');
var $formSerialize = $('#edit-entreprise').serialize() + "&entreprise=" + $entreprise;
$(".panel-entreprise").empty().append('<div class="progress"> <div class="indeterminate"></div> </div>');
$.ajax({
url: $url,
type: 'POST',
data: $formSerialize,
success: function(html) {
console.log(html);
}
});
});
And here, my controler :
public function editAction(Request $request)
{
$entreprise = $request->request->get('entreprise');
$entreprise = $this->getDoctrine()
->getRepository('AvisClientsBundle:Entreprise')
->find($entreprise);
$editForm = $this->createForm('AvisClientsBundle\Form\EntrepriseType', $entreprise);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entreprise);
$em->flush();
return new Response(json_encode(array('status' => 'success')));
}
return new Response(json_encode($this->render('AvisClientsBundle:Admin/Entreprise:edit.html.twig', array(
'entreprise' => $entreprise,
'edit_form' => $editForm->createView(),
))->getContent()));
}
I don't know how to receive the form and the extra data :(
Can you explain me how to do this ?
Thanks !
I do it like this :
Ajax (I use FormData ):
$('#formId').submit(function (event) {
// Eviter le comportement par défaut (soumettre le formulaire)
event.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: $this.attr('method'),
data: new FormData($this[0]),
processData: false,
contentType: false,
error: function (request, status, error) {
callback(request.responseText);
},
complete: function () {
//
},
statusCode: {
//traitement en cas de succès
200: function (response) {
var message = response.message;
callback(response, event);
},
412: function (response, event) {
callback(response);
}
}
});
});
In sf2 here is the handler:
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testBundle:testEntity')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find entity.');
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
//envoi des données JSON en front
$response = new JsonResponse();
$response->setStatusCode(200);
//ajout de données éventuelles
$response->setData(array(
'message' => "Ligne buffer updated",
'form' => json_encode($this->getHtmlForm($entity))));
return $response;
} else {
//form non valide
//envoi des données d'erreurs JSON en front
$response = new JsonResponse();
$response->setStatusCode(412);
$response->setData(array(
'form' => json_encode($this->getHtmlForm($entity)),
'message' => $editForm->getErrorsAsString(),
));
return $response;
}
}