infinite scrolling doesn't work when the popup appears - ajax

I installed an extension for my magento store, that make a quickview modal in the products list (imedia quickview - it' actually a bootstrap modal ) and works nice, but due to many products in the list i add a script for infinite scroll (http://infiniteajaxscroll.com/vendor/jquery-ias/dist/jquery-ias.min.js). Everything was fine, until i saw that the infinite scoll doesn't seems to work if the modal popup appears.
Here it's what I've done so far:
<pre>
<script type="text/javascript">
jQuery(window).load(function(){
activatePopup();
// Initialize the pagination plugin
var ias = jQuery.ias({
container : ".category-products",
item : ".product-item ",
next : "a.next",
pagination : '.pages',
loader : "<img src='/img/sys/loader.gif' />",
triggerPageThreshold : 0,
});
// Pagination plugin callback function
ias.on('rendered', function(items) {
activatePopup();
});
});
function activatePopup() {
var baseUrl = '<?php echo Mage::getBaseUrl(); ?>';
var containerClass = 'category-products';
$('.'+containerClass+' li').each(function(e){
var productId = $(this).find('.quick_view_btn').attr('id');
$(this).click(function(){
$(this).find('.quick_view_btn').html('Incarca..');
$.ajax({
type: "POST",
url: baseUrl+"quickview",
data: "id="+productId,
success: function(msg){
//$("html, body").animate({ scrollTop: 0 }, "slow");
$('.'+containerClass+' li .quick_view_btn').html('MAI MULT');
$('#modal .main-content').empty().append(msg);
$('#modal').css({'display': 'block', 'top':'50%','visibility':'visible','opacity':'1'});
$('body').css('overflow', 'hidden');
// popup submit validation
}
});
});
});
}
</script>
</pre>

Related

AJAX form redirecting on submit when using CKeditor

I am trying to submit an AJAX form with Laravel using the code shown below. After I submit the form, all the data is saved in the database as expected apart from the following field which is displayed as NULL in the database.
<textarea name="content" id="editor"></textarea>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form');
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
alert(data.successful);
}
});
})
});
</script>
public function addVideo(Request $request)
{
$addVideo = new cms_videos;
$addVideo->VideoStatus = $request->VideoStatus;
$addVideo->VideoTitle = $request->VideoTitle;
$addVideo->VideoStrapline = $request->VideoStrapline;
$addVideo->VideoURL = $request->VideoURL;
$addVideo->VideoDescription = $request->content;
$addVideo->VideoTags = $request->VideoTags;
$addVideo->MetaActName = $request->MetaActName;
$addVideo->MetaRegion = $request->MetaRegion;
$addVideo->MetaGenre = $request->MetaGenre;
$addVideo->MetaVenue = $request->MetaVenue;
$addVideo->VideoCoverPhoto = $request->VideoCoverPhoto;
$addVideo->save();
return response()->json(['successful'=>'Video successfully added']);
}
After doing some research I was told to add the following code to the top of the code shown above:
CKEDITOR.instances.SurveyBody.updateElement();
Now all the data is submitted to the database as expected. However when I now submit the form instead of an alert popping up saying "Successful" I am now redirected to the form action URL where it displays "Successful". How can I stop this redirection and display the alert on the page the form was submitted?
I'm not sure but I think the issue is here when you do e.preventDefault() because it works for the button click not for form submission. Try this out and hope it will help you.
Notice: you have to add upload_video class to your forms
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// If the button is type of submit you can remove this part of code
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form.upload_video');
form.submit();
})
});
//
$("form.upload_video").on('submit',function(e){
e.preventDefault();
let form = $(this),data=form.serialize();
//
let content=FCKeditorAPI.GetInstance('content').getData();
data['content']=content;
//
$.ajax({
type:'POST',
url: form.attr('action'),
data: data,
success:function(data){
alert(data.successful);
}
});
});
</script>
This part
let content=FCKeditorAPI.GetInstance('content').getData();
May not be true because I don't work with CKEDITOR right now and i can't test it but you can console.log() it before you send the ajax request and make sure the content exists in the variable as you expected.

Masonry view not working after loading more posts via ajax

I'm using this method to load more posts with Ajax.
I'm also using Masonry for the posts layout.
Masonry works fine for the first set of posts, but not for the next set of posts that are appended after clicking load more posts.
How can I make Masonry work after loading more posts?
Screen before click
Screen after click
Source Code:
index.php
<!-- Post Layout -->
<div class="posts <?php echo $home_style; ?>">
<!-- Normal Post -->
<?php
if (have_posts()) :
/* Start the Loop */
while (have_posts()) : the_post();
/* Home Layout */
if ($home_style === 'standard') {
get_template_part('inc/posts/content');
} else {
get_template_part('inc/posts/content', 'grid');
}
endwhile;
else :
get_template_part('template-parts/content', 'none');
endif;
?>
<?php
global $wp_query; // you can remove this line if everything works for you
// don't display the button if there are not enough posts
if ($wp_query->max_num_pages > 1)
// you can use <a> as well
echo '<div class="misha_loadmore grid-post">More posts</div>';
?>
</div>
<!-- Post Layout / END -->
Ajax Code
jQuery(function ($) {
$('.misha_loadmore').click(function () {
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page': misha_loadmore_params.current_page
};
$.ajax({
url: misha_loadmore_params.ajaxurl, // AJAX handler
data: data,
type: 'POST',
beforeSend: function (xhr) {
// change the button text, you can also add a preloader image
button.text('Loading...');
},
success: function (data) {
if (data) {
button.text('More posts').prev().before(data); // insert new posts
misha_loadmore_params.current_page++;
if (misha_loadmore_params.current_page == misha_loadmore_params.max_page)
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here
// if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});
});
Masonry script.js
/* Masonary Grid */
$('.home-grid').masonry({
itemSelector: '.grid-post',
percentPosition: true,
gutter: 33
});
In most javascript libraries, if you change the DOM (HTML) after initializing the plugin, you will have to tell the library that changes have been made. Most libraries will include a function or listen to an event that tells it to update. In the case of Masonry, it looks like this function is reloadItems.
In your case, it looks like you will have to call $('.home-grid').masonry('reloadItems'); directly after you do button.text( 'More posts' ).prev().before(data);.
Full code:
jQuery(function ($) {
$('.misha_loadmore').click(function () {
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page': misha_loadmore_params.current_page
};
$.ajax({
url: misha_loadmore_params.ajaxurl, // AJAX handler
data: data,
type: 'POST',
beforeSend: function (xhr) {
button.text('Loading...');
},
success: function (data) {
if (data) {
button.text('More posts').prev().before(data); // insert new posts
$('.home-grid').masonry('reloadItems');
misha_loadmore_params.current_page++;
if (misha_loadmore_params.current_page == misha_loadmore_params.max_page)
button.remove(); // if last page, remove the button
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});
});

Using ajax to update the currently page with Laravel

I have this ajax inside my file.php (It hits the success callback):
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
console.log(data);
}
});
})
</script>
Now on my Controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));
}
What I want to do:
I have a LIST with professor and their disciplines. What I need to do is:
Whenever I change the value of that select box, I just remake the function with the new parameter.
I'm trying to use ajax to remake that list but nothing change, not even the URL with the professor.php?anoSemestre=xx.
Also, when I try to use the $_GET['anoSemestre'] the page doesnt show any change or any ECHO.
But If I go to Chrome spector>NEtwork and click the ajax I just made, it shows me the page with the data I sent.
Cant find out what I'm doing wrong.
UPDATE
I did what was suggested me, now I'm working with the data I get from the success callback:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
}
});
})
</script>
The return of var lista = $(data).find('#list-professores'); is:
Accordion Effect
#list-professores li input[name='item']:checked ~ .prof-disciplinas {
height: auto;
display:block;
min-height:40px;
max-height:400px;
}
This list is an Accordion Menu (using a checkbox and changing it with js&css), so everytime I click on a professor < li>, it's suppose to open and show a sublist (disciplines of that professor I clicked). But it's not opening anymore and no errors on the console. No idea why.
The issue here is what you are returning in your controller and how you do it, you donĀ“t need to redirect or refresh the entire page. This could be achived using a single blade partial for the piece of code you may want/need to update over ajax. Assuming you have an exlusive view for that info, you could solve this with something like this:
in your view:
<div class="tableInfo">
<!--Here goes all data you may want to refresh/rebuild-->
</div>
In your javascript:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(){
$('.tableInfo').html(data); //---------> look at here!
}
});
})
</script>
in your controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
if (Request::ajax()) {
return response()->json(view('YourExclusiveDataPartialViewHere', ['with' => $SomeDataHereIfNeeded])->render()); //---------> This is the single partial which contains the updated info!
}else{
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));//---------> This view should include the partial for the initial state! (first load of the page);
}
}

How to update content of a Bootstrap modal loaded using Ajax?

I've a bootstrap Modal with users list, inside which I'm displaying another modal for adding a new user. The Add new User Modal is fetched using Ajax. When I add a new user using Ajax, I want to update the div with Ajax response message(.alert-success or .alert-danger in bootstrap).
Right Now the user is loaded but I can't show the message as the modal itself is loaded using Ajax.
$('body').on("click", "#createGroupUserModual .submit", function (e) {
var alertContainer = $(document).find('#groupUserFormCreate').find("#alerts");
$.ajax({
url: $('#groupUserFormCreate').attr('action'),
type: 'POST',
dataType: "json",
cache: false,
data: $('#groupUserFormCreate').serialize(),
success: function(response) {
console.log("success " + response.message);
var returnMessage = "<div class='alert alert-success'>"+response.message+"</div>";
//this below line is not updating the contents with the message.
alertContainer.html(returnMessage);
},
error: function(response) {
console.log("failure is here " + response.message);
var returnMessage = "<div class='alert alert-danger'>"+response.message+"</div>";
alertContainer.html(returnMessage);
}
});
});
I see that not same code for redraw de alertContent, it only exists when response is success but not in errro, under $.ajax query
So:
error: function(response) {
console.log("failure is here " + response.message);
var returnMessage = "<div class='alert alert-danger'>"+response.message+"</div>";
alertContainer.html(returnMessage);
}
Try this code, added the redraw html in error.
Expect will be.

Ajax loaded content div class is not applied

I have a page that has a few divs connected in a flowchart via JS-Graph.It. When you click one of the divs, I want it to 1) generate text in a special div 2) generate a popup via click functions attached to the two classes "block" and "channel" in each div. This works when the page is static.
When I add ajax so on click of a button and add more divs, only one of the two classes appears in the HTML source. "Channel" is no longer visible and the function to generate a pop-up on click of a channel class div does not work anymore...
AJAX call:
$("#trace").bind('click', $.proxy(function(event) {
var button2 = $('#combo').val();
if(button2 == 'default') {
var trans = 'Default View';
}
if(button2 == 'abc') {
var trans = 'abc';
}
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button2=' + $('#combo').val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data constains the data we get from serverside
{
JSGraphIt.delCanvas('mainCanvas');
$('.test').html('<h1>' + trans + '</h1>'); // Clear #content div
$('#mainCanvas').html(''); // Clear #content div
$('#mainCanvas').append(data);
JSGraphIt.initPageObjects();
}
});
return false; // keeps the page from not refreshing
}, this));
DIV class: (works in index.php but not transactions.php)
// Boxes
while($row = sqlsrv_fetch_array($result))
{
echo '<div id="'.$row['id'].'_block" class="block channel" style="background:';
Functions:
$(document).on('click', '.block', $.proxy(function(event) {
var input = $(event.target).attr('id');
var lines = input.split('_');
var button = lines[0];
$.ajax({
url: 'srv.php',
data: 'button=' + button,
dataType: 'json',
success: function(data)
{
$('#content').html('');
$('#content').append(data);
}
});
return false;
}, this)); // End Application Details
$(".channel").click(function () {
alert('channel');
});
Something about registering with pages, I'm not sure exactly how it works. The fix should be to change your channel click function to be the same as your first and use the .on('click') option.
found some related reading material. https://learn.jquery.com/events/event-delegation/

Resources