Change order of images and update in database - javascript

I have an HTML list and I want to change their order with drag and drop and also update in database. But I do not know how it is done. Can you helpl me? I used HTML5sortable plugin, but it does not update in db.
Here is my list:
<ul class="sortable grid" >
<?php
$images = get_children(array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'order' => 'ASC', 'orderby' => 'menu_order ID'));
$i = 0;
foreach ($images as $value) {
?>
<li style='list-style-type: none' >
<img src='<?php echo $value->guid;?>' width='90' />
<a class='btn btn-danger' href='#' onclick='deletePic(<?php echo $i;?>)'>
<i class='icon-trash icon-white'></i>
Delete
</a>
</li>
<?php $i++; } ?>
</ul>

write a ajax call inside sortupdate event handler
$('.sortable').sortable().bind('sortupdate', function() {
var menuId=[];
//store list id or some other unique field to identify your image into menuId variable
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
});

Related

Laravel dynamic content from database clicking on navbar using ajax

I am using laravel 7.I am new in laravel and ajax . I have a 'product's name' navbar. I want , When I click on a product from the navbar , the details of the product will show in a div without reloading the page. demo : ( https://www.webslesson.info/2017/03/dynamic-content-load-using-jquery-ajax-php.html ) the demo is in PHP, I want to use this in laravel.
blade part:
<ul class="nav navbar-nav">
<?php
$group = DB::table('package')->where('group_id', 5)->get();
?>
#foreach ($group as $item)
<li id="{{ $item->package_id }}">{{$item->package_name }}</li>
#endforeach
</ul>
<span id="page_details"></span>
scipt part for ajax on blade file
<script>
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
type: 'POST',
url: '/getmsg',
data: '_token = <?php echo csrf_token() ?>',
data: {id: id},
success: function (data) {
$('#page_details').html(data);
}
});
}
load_page_details(1);
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
</script>
route:
Route::post('/getmsg','AjaxController#index');
controller:
public function index(Request $request)
{
$pack_id=$request->id;
$msg = DB::table('package')->where('package_id',$pack_id);
$output .= '
<h1>'.$msg->package_id.'</h1>
';
return $output;
}
Please help me to make a thing in laravel like the demo ( http://demo.webslesson.info/dynamically-loading-content-with-ajax/# )
First of all, you have 2 data properties on your ajax request. Make that as 1 :
data: { "_token" : "{{ csrf_token() }}", "id" : id}
Then, I would recommend setting dataType to json in the AJAX request, and from the controller returning a json response, instead of the $output = .. bit.
return response()->json(['package_id' => $msg->package_id]);
After that, from your .success callback, you can access the properties of data just as you would with a normal javascript object. To achieve what you want you can use $('#page_details').html(data.package_id).

How to load more logo's with ajax?

I found a solution how to get a load more button that displays more content on click, but it was for posts, I want to make it work for my custom post type 'Klanten'.
I tried editing the code to match my post type, but I get an error: "Undefined index: offset"
functions.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
custom.js
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
$('#load_more_posts').data('offset', parseInt(response.data.offset));
}
});
})
php-file
$query = new WP_Query( array(
'post_type' => 'klanten',
'posts_per_page' => 4,
'offset' => 0,
'paged' => 1,
'order' => 'ASC',
'orderby' => 'rand',
) );
if ( $query->have_posts() ) { ?>
<div class="klanten__wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
<?php
wp_reset_postdata();
return ob_get_clean();
}
Console log
I want to show 4 logo's (elements), and load 4 more each time someone clicks the loadmore button
Replace this
<div id="load_more_posts" class="loadmore" data-offset="4">Load More...</div>
You need to return ajax data with logo array and then append data like below code.
AJAX call
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
var html = "";
$(response.data.klanten).each(function(index,value) {
html += '<div class="logo__wrapper"> <img class="klant__logo" src="'+value.post_thumbnail+'"></div>'
});
$('.logo_wrapper').append(html);
$('#load_more_posts').data('offset',
parseInt(response.data.offset));
}
});
})
HTML Code
<div class="klanten__wrapper">
<div class="logo_wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
function.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
$post_thumbnail = get_the_post_thumbnail($post->id);
$rst['post_thumbnail'] = $post_thumbnail;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
I got help from a colleague and he figured it out. I added this in my js-file (jQuery)
// Counter for logos
var logoCount = $('.logo__wrapper').length;
var counter = 12;
// Show only first 12 logos
$('.logo__wrapper:nth-of-type(1n+13)').addClass('is-hidden');
// Load more logos button click
$('#load_more_posts').on('click', function (e) {
// Loop hidden logo's
$('.logo__wrapper.is-hidden').each(function (i) {
// Hide button if no more logo's
if (counter++ === logoCount) {
$('#load_more_posts').hide();
$('.loadmore__end').toggle();
}
// Show next 12 logos
if (i < 12) {
$(this).removeClass('is-hidden');
}
// Break loop after 12 logos
else {
return false;
}
});
});

yii2 refresh modal after submit form

I want to ask how to refresh the modal after I submit the form in another action? I use yii2.
Here is my code :
index.php:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\KategoriSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Kategoris';
$this->params['breadcrumbs'][] = $this->title;
$this->registerJs("
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var modal = $(this)
var title = button.data('title')
var href = button.attr('href')
modal.find('.modal-title').html(title)
modal.find('.modal-body').html('<i class=\"fa fa-spinner fa-spin\"></i>')
$.post(href).done(function( data ) {
modal.find('.modal-body').html(data)
});
})
");
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'kateg_id',
'kateg_nama',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{size} {view} {update} {delete}',
'buttons' => [
'size' => function($url, $model, $key) {
return Html::a(Html::tag('i','',
[
'class'=>'fa fa-th-list',
'title'=>'Size'
]),
[
'size',
'id'=>$model->kateg_id,
],
[
'data-toggle'=>'modal',
'data-target'=>'#myModal',
'data-title'=>'Size',
]);
}
]
],
],
]); ?>
<?php
Modal::begin([
'id' =>'myModal',
'header' => '<h4 class="modal-title">...</h4>',
'footer' => Html::button('Close', ['class' => 'btn btn-default','data-dismiss'=>'modal']),
]);
Modal::end();
?>
The size button on my grid view will show the modal that returns the render ajax from action size in my controller.
After that here is my size view:
$form = ActiveForm::begin(); ?>
<?= $form->field($model, 'ukuran')->textInput(['id'=>'ukuran']) ?>
<?= $form->field($model, 'kateg_id')->textInput(['id'=>'kategori','type'=>'hidden','value'=>$id]) ?>
<div class="form-group">
<?= Html::button('Tambah', [
'class' => 'btn btn-primary',
'onclick' =>'
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function(res){
alert("PROCESS_SUCCES");
}
});
',
]) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::begin(['id' => 'pjax-grid-view']); ?>
<div id="grid">
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'ukuran_id',
'ukuran',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<?php Pjax::end(); ?>
I'm trying to add refresh after alert but it does not work. It will close the modal and back to index again.
So I'm confused what it should be?
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function(res){
alert("PROCESS_SUCCES");
}
});
I noticed in your .post call, you don't do anything with the res that's passed as the parameter of the success function. You just alert "PROCESS_SUCCES" (is this a macro for something?), and it stops. To modify elements on your page, you would want to select one and use the .html() or .val() functions to change it. Something like this:
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function (res) {
alert("PROCESS_SUCCES");
$("#my_output_area").html(res);
}
});
Alternatively, you can use $.ajax() instead of $.post().
$.ajax({
type: "post",
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function (res) {
alert("PROCESS_SUCCES");
$("#my_output_area").html(res);
}
});

How to show returned data on a Bootstrap Modal popup after submitting data in Yii2?

I have a Modal popup that has two fields, the first one is to submit some information a do an internal query into a database, and the second field on that Modal popup is to show the returned data. However when I test independently (without being a Modal) it worked, however when tested as a Modal it only submit the data but not show any result on the same modal, what could be wrong? Thanks.
This is the view that calls to the Modal popup.
<?php Pjax::begin() ?>
<p>
<?= Html::button('Quick Search', ['value' =>Url::to('index.php?r=site/mypopup'),'class' =>'btn btn-success', 'id'=>'modalButton']) ?>
</p>
<?php
Modal::begin([
'header'=> '<h4>My Modal Popup</h4>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
<?php Pjax::end(); ?>
This is the mypopup view:
<?php Pjax::begin(['enablePushState' => false]); ?>
<?php $form = ActiveForm::begin(['id' => 'mypopup-form', 'options' => ['data-pjax' => true],]); ?>
<?= $form->field($model, 'pattern')->textArea(['rows' => 1]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'mypopup-button']) ?>
</div>
<?php
echo "<pre>";
//SECOND FIELD
print_r($model->data);
?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
This is the controller of mypoup:
public function actionMypopup()
{
$model = new PopupForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->insertPopup();
return $this->renderAjax('mypopup', ['model' => $model]);
} else {
return $this->renderAjax('mypopup', ['model' => $model]);
}
}
This is the js file:
$(function(){
$('#modalButton').on('click', function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
$(document).ajaxComplete(function (event, xhr, settings) {
alert(xhr.getResponseHeader());
});
});
I have overcome the issue by modifying two parts:
First of all I have created a jQuery beforeSubmit method in the main.js file, so it wouldn't refresh the page and submit the form via ajax.
This code code goes below the previous code on the js file.
$('body').on('beforeSubmit', 'form#mypopup-form', function() {
var form = $(this);
if (form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(data) {
$(form).find('.results').html(data);
return false;
});
}
});
Second, then after it will call the ajax to form action; and in the view I have added a condition to check if its posting some data from ajax and then display the results in div name results.
This code goes above all the code on the mypopup file:
<?php if(isset($_POST['MyPopupForm']))
{
echo "<pre>";
print_r($model->data);
echo '</pre>';exit();
}?>
and on the same file at the end:
<div class="results"></div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>

getting the value of a array from controller to view with ajax in codeigniter

I am creating a status update system where i need to upload a image as well as show it when it uploads all using ajax but when i send the image it goes to the database but i cannot access the image in the ajax return
here is the code
<div class="tab-pane fade" id="tabs-2">
<?php echo form_open_multipart('',["id"=>"formupload","name"=>"formupload"]); ?>
<p class="formUnit"> <i class="active_pic"></i>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<button class="uibutton" type="button" id="upload_pic" style="width: 230px; height: 150px;">Upload Picture</button><span id="status"></span>
<?php echo form_upload(["name"=>"imagefile","id"=>"upload_pic" ]); ?>
<ol class="controls clearfix">
<?php echo form_submit(['name'=>'submit','value'=>'Submit',"class"=>"btn btn-primary"]); ?>
</ol>
</p>
<p id="files"></p>
<?php echo form_close(); ?>
</div>
now ajax
jQuery('#formupload').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/postData_image"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
console.log(data);
$('#output_post').attr('src',data);
},
error: function(data){
//error function
}
});
});
now controller
public function postData_image()
{
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 10000000000000,
'max_width' => 1024000000,
'max_height' => 7680000000,
];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$imagefile="imagefile";
if(!$this->upload->do_upload($imagefile))
{
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/profile',compact('upload_error'));
}
else
{
$post = $this->input->post();
//print_r($post);
unset($post['submit']);
$upload_data = $this->upload->data();
$file_name=$_FILES['imagefile'];
$this->load->model('Pmodel');
$post_data=$this->Pmodel->post_data_image($post,$file_name);
$post['data']=$post_data;
echo $image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
return $post;
}
}
model
public function post_data_image($arr,$arra)
{
$id=$arr['id'];
$image=$arra['name'];
$data=array('image'=>$image);
$query=$this->db->insert('post_status',['user_id'=>$id,'image'=>$image]);
return $query;
}
but how to return the value that is generated after insert in the database using ajax
You want to output your post as json so jquery can interpret it.
echo json_encode($post);
To your ajax function add:
dataType: 'json'
And then data will be an array you can use.
Thanx to #Callombert i got the answer for what i was looking i wanted to return the value and 'echo json_encode('$image_path) or $post would return the value in the json form thus you cacn access it in your view
for someone else looking for an answer just add echo json_encode($image_path);
To your ajax function add:
dataType: 'json'
this would get you working.

Categories

Resources