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);
}
Related
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!
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
My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced
I checked if file exists using Input::hasFile('File'), and it returns true and successfully got file's binary.
But Input::file('File')->getClientOriginalExtension() returns empty string.
Here's my controller
public function ConfirmWrite()
{
if (!Session::has('id')) {
return '0:Please log in.';
}
$Data = Request::all();
$Data['uid'] = Session::get('id');
$Data['mid'] = 0;
var_dump(Input::file('File')->getClientOriginalExtension());
return '1';
if (Input::hasFile('File')) {
$file = Input::file('File');
$rules = ['File' => 'mimes:jpeg,bmp,png,jpg|max:10000'];
$validator = Validator::make(['File' => $file], $rules);
if ($validator->fails()) {
return '0:Check your File.';
}
$Data['Thumbnail'] = $file->getClientOriginalExtension();
$destinationPath = 'images/post/thumbnail/';
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
$upload_success = $file->move($destinationPath, $Content . '.' . $Data['Thumbnail']);
echo "asdfasdfasdf : ".$Data['Thumbnail'];
if ($upload_success) {
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 320, 'small');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 700, 'medium');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 1920, '');
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
} else {
return '0:Somethings wrong';
}
} else {
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
}
}
And below code is Front-end Ajax code.
var fData = new FormData;
GlobalVar.Thumbnail == '' ? '' : fData.append('File', DataURLtoBlob(GlobalVar.Thumbnail));
fData.append('Title', $('.contents-details').find('h1').html());
fData.append('Subtitle', $('.contents-details').find('h2').html());
fData.append('Content', $('#post-editor').froalaEditor('html.get'));
fData.append('Align', EditorAlign);
fData.append('Tag', Tag);
fData.append('Share',GlobalVar.FBShare);
$.ajax({
url: '{{ URL::to('/post/write') }}',
type: 'post',
processData: false,
enctype: "multipart/form-data",
contentType: false,
cache: false,
data: fData,
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function (result) {
var Check = $.trim(result).split(':');
$('.submit-loading').css('display', 'none');
if (Check[0] == '1') {
checkUnload = false;
location.href = '{{ URL::to('post') }}/' + Check[1];
} else {
console.log(result);
Warning(Check[1]);
}
},
});
I can't find where is bug code and mistake I made. Please help me. This make me mad.
The getClientOriginalExtension method returns the extension of the actual file uploaded some-image.pdf, this is not considered a safe value. Instead you could best use guessExtension.
The guessExtension method uses the actual mime type and returns the related file type.
i'm using codeigniter and select2 plugin for displaying my data.. but i have a problem, that plugin not display anything, just display searching... there is my code
/*------------- JS -----------------*/
$("#nm_peg").select2({
placeholder: "Masukkan Nama Pegawai",
width:'element',
ajax : {
url : "<?php echo site_url('pegawai/getAllData'); ?>",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
this is my controller
/*-------------- Controller ---------------*/
public function getAllData()
{
$this->load->model('pegawaimodel');
$d = $this->pegawaimodel->get_all_pegawai();
$rows = array();
foreach ($d as $a) {
$rows[] = $a;
}
header('Content-Type:application/json');
return json_encode($d);
}
and this is my model.
/*--------------Model-----------------*/
public function get_all_pegawai()
{
$this->db->select('peg_id, peg_nama');
$this->db->from('master_pegawai');
$query = $this->db->get();
return $query->result();
}
thank's for any help..