History.js first load - javascript

I'm using History.js with jQuery.
My page is a search engine.
The form is submitted via $.ajax() and the result is loaded in div#results with pagination.
A click on next page's link is handled by $.ajax too.
Each result is a link to another page.
When I first load my form, I want div#results to be empty. But when I click on result's link then the back button, I want the div#results with the same results.
$('.link_page').on('click', function(e){
e.preventDefault();
var page = $(this).data('page');
$.ajax({
url: '/search',
method: 'POST',
data: {
create_date : $('#create_date').val(),
page : page
}
}).done(function( html ) {
$( "#results" ).html( html );
History.pushState({results: html}, "Search", "/search");
});
});
History.Adapter.bind(window, 'statechange', function (evt) {
var state = History.getState();
$( "#results" ).html( state.data.results );
});
History.Adapter.onDomLoad(function(){
var state = History.getState();
History.replaceState({results: state.data.results}, "Search", "/search");
});
It works well but if I submit my form then I go to any pages of my site and finally I return to my form, the div#results is still filled with the previous search.

Related

Reload part of the page Jquery

I have a table with a td that updates when i press a button .pauseDocker
When It's paused I'm reloading the page. Surely there's a smarter way to just refresh just part of the page in this case the table.
$(document).on('click','.pauseDocker' ,function(){
var buttonClicked = $(this);
var containerName = $(this).attr('name');
$.ajax({
type: 'post',
url: '/container/pause',
data: {containerName: containerName},
success: function () {
location.reload();
},
error: function() {
}
});
});
You can get the first parameter of the success callback and this will contain data from the response of your server. Use that to retrieve the changed data and update client side accordingly

JS, jQuery not working when I refresh part of page with Ajax

I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});

Using history.pushstate on jquery ajax

I have a heavily ajax based application wherein i only have a login page and the main page.
Most of my links are "ajaxed" and i have them done like this:
//get the href of the link that has been clicked, ajaxify ANY links
$(document).on('click', '.tree a', function () {
var link = $(this).attr('href'); //get the href off the list
$.ajax({ //ajax request to post the partial View
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
return false; //intercept the link
});
I want to implement "pushState" on my application and the first step that i have done so far is to add this code:
$(document).on('click', 'a', function () {
history.pushState({}, '', $(this).attr("href"));
});
Now it updates my address bar whenever i click on any of my links and the ajax content gets successfully loaded.
I am kinda new to this API so i don't know what am i missing but here are my issues so far:
when i press the "back" button, nothing happens. I read about "popstate" and browsed through SO to look for solutions but i can't
seem to make them work.
When i click the link from the history, i get the "raw" view of the child html w/o the layout from the master html. What do i need to do if i want it to be displayed like
it was clicked from my main application?
Most of my child views are either forms or list.
This code should help you :
function openURL(href){
var link = href; //$(this).attr('href');
$.ajax({
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
window.history.pushState({href: href}, '', href);
}
$(document).ready(function() {
$(document).on('click', 'a', function () {
openURL($(this).attr("href"));
return false; //intercept the link
});
window.addEventListener('popstate', function(e){
if(e.state)
openURL(e.state.href);
});
});

Reload window without closing Fancy Box

I have a fancybox with a form and an Ajax post behind it:
var form = $("#myform");
var data = form.serialize();
var url = form.attr("action");
$.ajax({
type: 'POST',
url: url,
data: data,
}).done(function() {
location.reload();
window.location.reload(true);
}).fail(function() {}).error(function(httpObj, textStatus) {
setTimeout(function() {
$("#user_email").focus();
}, 100);
$("#quickSigninError").fadeIn();
$("#loadingSpinnerPopup").fadeOut();
$("#submitBtn").prop("disabled", false);
$("#submitBtnCurrent").prop("disabled", false);
$("#cancelBtn").prop("disabled", false);
});
The fancybox works great submits the form and reloads the fancybox when Ajax.done() occurs.
The problem:
I can reload the Fancybox with ease but now my question is how do I reload the original window that's behind the Fancybox without closing the Fancybox.
To emphasize the situation, please note the following screenshot:
Kind regards and thanks for anyone that can help me! :)
EDIT1: Goal is not to get the Fancybox closed.
You cant reload the website, that will reload your page ( including the fancybox. )
create an ajax call that will give you the page content
create another ajax and change the content of the parent
something to keep in mind,
you better change all the content of a (div class="content")
and attach the fancybox to any object not inside the content div because it will be changed.
$.ajax({
type: 'POST',
url: url,
data: data,
}).done(function() {
location.reload();
// ajax to fetch div content //
$.get( "ajax/test.html", function( data ) {
$( ".content" ).html( data );
alert( "Load was performed." );
});
}).fail(function() {}).error(function(httpObj, textStatus) {
setTimeout(function() {
$("#user_email").focus();
}, 100);
$("#quickSigninError").fadeIn();
$("#loadingSpinnerPopup").fadeOut();
$("#submitBtn").prop("disabled", false);
$("#submitBtnCurrent").prop("disabled", false);
$("#cancelBtn").prop("disabled", false);
});
Inside iframe use javascript:
parent.location.reload();
//or
parent.location.href = 'http://google.com'
Note, that iframe should contain code from same origin (the same domain, and the same protocol).

jQuery Submit Form on Enter Not Working

In the script below I've got the code to allow me to add a new line by pressing shift+enter but when I just press enter the code does nothing. I also get no errors. I've removed the resize caret so there is no need to mess with that. What is the bug in my code keeping me from submitting the form?
Disclaimer: yes I know there are multiple posts on this subject but none of them fix my problem so I'm hoping it's a new problem.
<script>
$('#myFormActivity .commentTextarea').keypress(function(event){
if (event.keyCode==13 && !event.shiftKey) {
event.preventDefault();
$( "#myFormActivity" ).submit(function(event1) {
alert("sent");
// Stop form from submitting normally
event1.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
activityid = $form.find( "input[name='activityid']" ).val(),
comment = $form.find( "textarea[name='comment']" ).val(),
url = "process/insertComment.php";
// Send the data using post
var posting = $.post( url, { activityid: activityid, comment: comment } );
// Put the results in a div
posting.done(function( data ) {
$(this).children('.commentTextarea').val('');
});
return false;
});
return false;
}
});
</script>
The class commentTextarea is the class assigned to the textarea element inside of the form which has the ID of myFormActivity.
What you are doing in your keypress event when you say
$( "#myFormActivity" ).submit(function(event1) {
is binding an event to the form submit, not triggering it. Something like (I haven't actually tested it) the following is more what you want I think (note the mime-type on the script tag and that the events should be bound in a document ready):
<script type="text/javascript">
$(function(){
$('#myFormActivity .commentTextarea').keypress(function(event){
if (event.keyCode==13 && !event.shiftKey) {
event.preventDefault();
$( "#myFormActivity" ).submit();
return false;
}
});
$( "#myFormActivity" ).submit(function(event1) {
alert("sent");
// Stop form from submitting normally
event1.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
activityid = $form.find( "input[name='activityid']" ).val(),
comment = $form.find( "textarea[name='comment']" ).val(),
url = "process/insertComment.php";
// Send the data using post
var posting = $.post( url, { activityid: activityid, comment: comment } );
// Put the results in a div
posting.done(function( data ) {
$(this).children('.commentTextarea').val('');
});
return false;
});
});
</script>

Categories

Resources