I'm beginner to the JSON with PHP if you can please help me. the code repeat the same output in 3 times. I include the require codes here. The code details are given below.
../Controller/controller.php has the MySQL code to retrieve data from database
donnerdata.js:
function member_note(){
var tableData;
$.post("../Controller/controller.php", {loading_donnerdata: 'table'}, function(e) {
if (e === undefined || e.length === 0 || e === null) {
tableData = 'noData';
$('#orders-datatable').html('').append(tableData);
} else {
$.each(e, function() {
tableData += '<div class="row comment">';
tableData += '<div class="col-sm-10">';
tableData += '<div class="message clearfix">';
tableData += '<div class="note">';
tableData += '<p>';
tableData += 'something';
tableData += '</p>';
tableData += '</div>';
tableData += '</div>';
tableData += '</div>';
});
//Load Json Data to Table
$('#orders-datatable').html('').append(tableData);
}
}, "json");
}
viewStudent.php:
<div class="comments">
<div class="" id="orders-datatable">
<?php require_once '../../Common/all_js_links.php'; ?>
<script src="js/donnerdata.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
member_note();
});
});
</script>
</div>
</div>
Try this instead of your doubly-nested callback.
$(document).ready(function() {
member_note();
});
Related
how to get dynamic data from database in Wordpress ajax if their is already a query is running inside a function in Wordpress
<script type="text/javascript" >
var ajaxurl = "<?php echo admin_url('admin-ajax.php');?>";
jQuery(document).ready(function($) {
var data = {
'action': 'wa_action'
};
$.post(ajaxurl, data, function(result) {
var contactList = JSON.parse(result);
console.log(contactList);
var contents = '<ul id="whatsapps" class="list" >';
contactList.forEach(contact => {
contents += '<li class="child">';
contents += '<a href="https://wa.me/+91'+contact.contact_number+'" target="_blank">';
contents += '<img src="<?php echo PLUGIN_URL."/CustomPlugin/assets/images/whatsapp.png" ?>" class="img-fluid" target="_blank" alt="logo" />';
contents += '<span>'+contact.name + '(' + contact.designation +')' + '</span>';
contents += '</a>';
contents += '</li>';
});
contents += '<li class="parent"><a><img src="<?php echo PLUGIN_URL."/CustomPlugin/assets/images/whatsapp.png" ?>" class="img-fluid" target="_blank" alt="logo"></a></li>';
contents += '</ul>';
$('body').append(contents);
$("#whatsapps .parent").click(function () {
$("#whatsapps").toggleClass("show");
});
});
});
</script>
How to add CSS for positioning here
I am trying to fetch data using data and it is returning json in whole page.
This is my code on Controller to fetch products:
public function products(){
$allProducts = $this->product->has('Sizes')->has('Images')->paginate(9);
$prodCategories = $this->products_categories->get();
return response()->json( $allProducts);
}
And in the ajax, I have the following code:
$( document ).ready(function() {
$.ajax({
url: "{{ route('displayProduct') }}",
dataType: 'json',
method: 'get',
data: { _token:"{{ csrf_token() }}"},
success(response){
let array = response.data;
if(array == 0){
html += '<div class="block"><h2 class="aside-title">Product not found!</h2><p class="errorProduct">Sorry! There is no product in this category. Please search products on other categories</p></div>';
$('#productClick').html(html);
}
$.each( array, function( key, value ) {
let image = jQuery.makeArray(value.images);
html += '<div class="product-layout product-layout-table col-lg-4 col-md-4 col-sm-6 col-xs-6 col-12">';
html += '<div class="product-box clearfix">';
html += '<div class="product-image">';
html += '<a href="/product/'+value.slug+'" class="c-img link-product">';
html += '<img src="'+image[0]['image']+'" class="img-responsive" alt=""></a>';
html += '<a class="smooth quickview iframe-link btn-button quickview quickview_handler visible-lg" href="/quick/'+value.slug+'" title="Quick view" target="_self" data-fancybox-type="iframe">';
html += '<i class="fa fa-search" aria-hidden="true"></i></a></div>';
html += '<div class="product-info"><h4 class="product-name">'+value.title+'</h4>';
html += '<div class="price">'+value.price+' <span class="price-old">$142.00</span></div>';
html += '<div class="product-desc">';
html += '<p>'+value.excerpt+'</p></div></div>';
html += '<div class="button-group"><button class="add-to-cart smooth" onclick="window.location.href=\'cart.html\'">ADD TO CART</button></div></div></div></div></div>';
});
$('#productClick').html(html);
loadIframe();
}
});
});
But, when I load the product I am getting json data on the whole page.
The function loadFrame has following code:
function loadIframe(){
$.getScript( "ajax/test.js" )
}
I am loading the latest news article to my home page, I would like to load the next one on click of a button. However I get this error on click: home.php:353 Uncaught ReferenceError: nextNews is not defined. The code I have written will load another article but will not hide the previous one. Any suggestions for this are also welcome.
<script>
$( document ).ready(function() {
var newsCount = 1;
function nextNews(item){
newsCount = newsCount + 1;
$("#newsHome2").load("load-news.php", {
newsNewCount: newsCount
});
}
});
</script>
<?php
$query = $handler->query('SELECT * FROM articles LIMIT 1');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
if ($_GET['sort'] == 'dateTime')
{
$sql = " ORDER BY dateTime";}
for ($i=0; $i < count($results); $i++) {
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">'.$results[$i]['headline'].' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,' .base64_encode( $results[$i]['logo'] ).'"/>';
echo '<p class="news-time">'.$results[$i]['dateTime'].'< br>'.'</p>';
echo '<p class="news-body56">'.$results[$i]['text'].'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews(this)" class="fa fa-chevron-right fa-1x"></i></div>';
}
?>
Your function 'nextNews' is defined in the anonymous function passed to .ready(). So it can't be called in your html.
Alternative:
Use jquery click event
Define the function outside of the anonymous function
Try this workout Its working fine :)
view file view.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="newsHome2"></div>
<script type="text/javascript">
var newsCount = 1;
$( document ).ready(function() {
nextNews(newsCount)
});
function nextNews(newsCount){
newsCount = newsCount + 1;
$.post("load-news.php", { newsNewCount: newsCount }, function(data, status){
$("#newsHome2").html(data);
});
}
</script>
php file load-news.php
<?php
if(isset($_POST['newsNewCount'])) { $newsCount=$_POST['newsNewCount']; } else { $newsCount=1; }
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">headline '.$newsCount.' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,"/>';
echo '<p class="news-time">dateTime '.$newsCount.'< br>'.'</p>';
echo '<p class="news-body56">text '.$newsCount.'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More '.$newsCount.'</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews('.$newsCount.')" class="fa fa-chevron-right fa-1x"> click here for next </i></div>';
?>
I want my second selects options to vary depending on the choice in the first select.
If you pick "Skalman" you can't pick "Whole day with lunch" and if you choose "Lilleskutt" you can't choose "Half day".
I haven't worked with AJAX before but thinking that it might be the right way to go, if anyone could help me out I would be more than grateful!
I get the options from the database, using two functions in Booking.php:
private function get_room_options() {
$this->load->model('Booking_Model');
$rooms = $this->Booking_Model->get();
$rooms_form_options = array();
// get room title and store in array
foreach ($rooms as $id => $room) {
$rooms_form_options[$id] = $room->title;
}
return array(
'rooms_form_options' => $rooms_form_options,
);
}
public function get_package_options() {
$room = $this->input->post('searchData');
$this->load->model('Package_Model');
$packages = $this->Package_Model->get();
$packages_form_options = array();
foreach ($packages as $id => $package) {
$packages_form_options[$id] = $package->package_name;
}
return array(
'packages_form_options' => $packages_form_options,
);
}
And in my booking.php you find the form:
<?php
echo form_open('booking/preview') ?>
<div>
<?php echo form_label('Conference Room: ', 'id') ; ?>
<?php echo form_dropdown('id', $rooms_form_options, set_value('id')); ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id') ; ?>
<?php echo form_dropdown('package_id', $packages_form_options, set_value('package_id')); ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people') ; ?>
<?php echo form_input('number_people', set_value('number_people')) ; ?>
</div>
<div>
<?php echo form_submit('preview', 'Book'); ?>
</div>
<?php echo form_close(); ?>
And my script so far:
<script type="text/javascript">
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.ajax({
url: "<?php echo base_url('index.php/booking/get_package_options'); ?>",
type: 'POST',
data: searchData,
success: function() {
// how should I get the options in here?
}
});
});
});
</script>
CodeIgniter doesn't support ajax.For more clarification http://phpframeworks.com/
So lets start from view
<?php echo form_open('booking/preview') ?>
<div>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<?php echo form_label('Conference Room: ', 'id'), form_dropdown('id', $rooms_form_options, set_value('id')) ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id'), form_dropdown('package_id', $packages_form_options, set_value('package_id')) ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people'), form_input('number_people', set_value('number_people')) ?>
</div>
<div>
<?php echo form_submit('preview', 'Book') ?>
</div>
<?php echo form_close() ?>
Here optimize your code by removing trailing semicolon & multiple echo
into single statement.
Now in your js part
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.post('YOUR_SEARCH_URL', { data : searchData }).done(function(data, textStatus, jqXHR) {
var h = '';
$(data.YOUR_SERVER_RESPONSE_KEY).each(function(i, v){
h += '<option value="' + i + '">' + v + '</option>'
});
$('[name=package_id]' ).html(h);
}).error(function(jqXHR, textStatus, errorThrown) {
//Handle your ajax error
});
});
});
Now at your controller
public function YOUR_CONTROLLER_ACTION() {
$data = $this->input->post('data');
//Do your work & get data from model for the id
//now send json response
return $this->output
->set_content_type('application/json')
->set_output(json_encode(YOUR_JSON_RESPONSE_ARRAY));
}
Check this two links http://code.runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php & http://code.tutsplus.com/tutorials/codeigniter-from-scratch-day-8-ajax--net-9243 for more details
I wish to get the file size and show inside my disabled textbox.
I googled and there is very less info about this.
Following bellow is my code
In PHP:
<div class="inputWrapper">
<div class="usetitle">* <?php echo Yii::t('labels', 'gameapk'); ?> :
<div class="div_upload_file_container">
<div style="position:absolute; margin: 0; padding:0; height:27px">
<input style="display:none" id="btnUploadFile" name="btnUploadFile" type="file" />
</div>
<div class="div_upload_file_container_inner">
<div class='word'>
</div>
<div style='clear:both'></div>
</div>
</div>
<div style="height:50px"></div>
<div id="uploaded_file"></div>
</div>
<div class="error2"><div id="err_btnUploadFile"></div></div>
</div>
In JS FILE:
//file
$('#btnUploadFile').uploadify({
'swf': base_url + '/js/plugins/uploadify321/uploadify.swf',
'uploader': "index.php?r=apk/uploadfile",
'folder' : '/temp',
'queueID': 'uploaded_file',
'queueSizeLimit' : 1,
'progressData': 'speed',
'removeCompleted': false,
'width': $('.div_upload_file_container').width(),
'height': 28,
'fileTypeDesc': 'Apk Files (*.apk)',
'fileTypeExts': '*.apk;',
'fileSizeLimit': '100GB',
'uploadLimit' : 1,
'itemTemplate': uploadedFileItem(),
'buttonText' : UPLOAD_FILE,
'onSelect': function (file) {
},
'onUploadStart': function (file) {
},
'onUploadSuccess': function (file, data, response) {
console.log (data);
$('#' + file.id).html(file.name);
var obj = JSON.parse(data);
statusCode = obj.statusCode;
if (statusCode == '200'){
console.log (data);
var today = obj.today;
var tmp_folder_with_date = obj.tmp_folder_with_date;
var filesize = obj.filesize;
var hashfilename_filename = obj.hashfilename_filename;
var full_path = obj.full_path;
file_cnt ++;
var html = '';
html = '<div>';
html += '<div style="float:left">';
html += file_cnt + '.';
html += '</div>';
html += '<div style="float:left; margin: 0 0 0 10px">';
html += file.name;
html += '</div>';
html += '<div style="clear:both"></div>';
html += '</div>';
$('#' + file.id).html(html);
}
var params = {
fileid: file.id,
fileName: obj.fileName,
fullSavePath_original: obj.fullSavePath_original,
fullSavePath_resize: obj.fullSavePath_resize,
fullSavePath_tobesave: obj.fullSavePath_tobesave,
fullSavePath_tobesaveURL: obj.fullSavePath_tobesaveURL,
filesize: obj.fileSize,
fullPath_TempFolder: obj.fullPath_TempFolder,
orientation: obj.orientation,
tobesave_file_width: obj.tobesave_file_width,
tobesave_file_height: obj.tobesave_file_height,
todayTempFolder: obj.todayTempFolder
};
DisplayNewUploadedPhotos(params);
},
'onUploadComplete': function (file) {
},
'onCancel': function (event,ID,fileObj,data) {
},
'onDialogClose': function (queueData) {
},
'onInit': function (instance) {
},
'onQueueComplete': function (queueData) {
},
'onClearQueue': function (queueItemCount) {
}
});
function uploadedFileItem() {
var html = '';
html = '<div id="${fileID}" class="fileUploadedItem">';
html += '<div style="margin:10px 0 0 0"></div>';
html += '<div class="uploadify-progress-bar"></div>';
html += '<div style="margin:10px 0 0 0">';
html += '<center>Cancel</center>';
html += '</div>';
html += '</div>';
return html;
}
obj.filesize is the file size ... Am I correct ? If I was correct , what should I do to get obj.filesize from JS to my textbox ?
I have an idea to do that suddenly:
$("#appsize").attr('value', obj.filesize);
HAHA THANKS =D