jquery ajax post call, ajaxify history and back button - javascript

I have ajax calls made in jquery function which i call with onClick options placed on divs.
example:
<div class='basic' onClick='example( <?php echo numberIwant ?> )'> example </div>
and the functions than looks like this:
function example(ID){
$.ajax({
type: "POST",
url: "example.php",
data: "ID="+ID, success: function(msg){$("#main").html(msg);}
});
}
Now I want to make browser back button to work, to open the previous page(ajax content).
I googled and tried multiple scrips like ajaxify and history.js and so on but I just cannot get it working.
I don't know if I either don't know how to use ajaxify properly or if it just doesent work with this kind of method..
Can anyone help me?

Using the backbutton w/ AJAX has historically been a very common problem. Luckily, with HTML5 came history.pushState which sort of allows you to manually manipulate what the browser does during a navigation (e.g., backbutton).
Some good resources on this:
http://diveintohtml5.info/history.html
http://adhockery.blogspot.com/2011/02/javascripts-history-object-pushstate.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Related

Limited with JavaScript onCLick() when making AJAX call

I am working on an existing project and heavily using jQuery AJAX calls. Existing pages have three different sections header, left menu and main content. Implemented with Spring MVC it is updating whole page whenever view is returned from Spring controller.
Now since I am working with one of the menu item but having tab content I am using jQuery to manipulate data within tabs using jQuery. While doing so whenever I have to work with hyperlink I can't use <a> tag since return from link will replace whole page . So I am always limited to use onClick() even ton the link and do AJAX call then put response back in window using jQuery.
Details
<script>
$.ajax({
type: ...,
url: ...,
success: function(response) {
$('#tab1-content').empty().html(response);
}
});
</script>
So my question is - Is there any other way so that I can use href properties of <a> tag and update window with response view?
I am not sure if I understood you correctly. Could you try something like this:
Details
<script>
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
loadDetail(href);
});
function loadDetail(url) {
alert("Load from: " + url);
// Ajax call
}
</script>
Fiddle
You can prevent default behaviour of tag just return false from your function.
See this fiddle http://jsfiddle.net/s8mpwokt/
Or just like in Michael answer attach event from javascript so you'll get event instance in your callback function with preventDefault() and stopPropagation().

Form method and lightbox (or alternative)

I've been looking over an older post trying to work out a solution for showing the confirmation PHP in a lightbox.
As my knowledge on javascript and ajax is close to zero - well, it IS zero - I'm hoping someone might elaborate.
<form method="post" action="contact.php">
Is the basic form method. Would I be able to use something like Tinybox2 and simply add
TINY.box.show({url:'submit.php',post:'id=16',width:200,height:100,opacity:20,topsplit:3})
to the action, rather than a php?
Cheers, Trin
If you want to use TinyBox, you need to serialize your form before you post it. One of the fastest and nonpainful way to do this to use jQuery (Just add reference if you haven't done this.)
TINY.box.show({url: $("form").prop("action"), post:$('form').serialize(),width:200,height:100,opacity:20,topsplit:3})
First one grabs the "action" url from your form, and the second method makes your form to be posted with TinyBox.
This code should display a tinybox when user submits the form:
$("form").submit(function( event ) {
event.preventDefault();
TINY.box.show({
url: $("form").prop("action"),
post: $('form').serialize(),
width:200,
height:100,
opacity:20,
topsplit:3
});
return;
});
Just put this inside
<script type="text/javascript">
$(document).ready(function () {
// Here.
}
</script>
block.

Commenting System - Showing posted comment without page reload

working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)

redirect form after submit

I created a submit form with JS simply to post a variable to PHP:
entry.innerHTML= ' <form action="eLoad.php" method="post"> <input class="submitLink" type="submit" name="name" value='+uploaded[i][1]+'> </form>
It works but in my php i want to send back a variable to JS. I'm using Json but every time I submit, the form submits to my browser and ouputs the php file and echos whatever JS text I have on the browser. I want to redirect to another page after the php and the JS (json) in my php loads.
Any help? Thanks
Sounds like sending an AJAX request and redirecting on the callback function is what you need.
As suggested here, I also strongly recommend using an existing library.
To use jQuery for example, you'll first have to include it by adding:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
Once you've done that and can use the library, try something like this:
$.ajax({
url: "eLoad.php"
}).done(function() {
window.location = <url-to-redirect-to>;
});
One last thing to mention, there are many useful params you can use when calling the jQuery's ajax function, take a look at http://api.jquery.com/jQuery.ajax/
What you are looking here is for async submition of forms, otherwise known as AJAX.
I suggest you adopt an existing library to do the boring part for you.
Visit this Lightweight JS AJAX library , you will need to use ajax as suggested, implementing and using jQuery will be the fastest way, but do go for other options like zepto.js, mootools, etc. Also if you want to build your own solution for your problems do a little research on xmlhttp, refer to this link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
You wont have to write a lot of code to do this, but using readily available libraries wont hurt.
I recommend an AJAX solution. Take a look at the JQuery JavaScript library at http://api.jquery.com/jQuery.ajax/. With AJAX you can load content (and post forms) dynamicly into your webpage without refreshing the page.
Edit: Example code:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('submit', 'form#my-form', function() {
$.ajax({
type: "post",
data: $(this).serialize(),
url: "my_page.php",
success: function(response) {
alert(response);
}
});
});
</script>

Ajax and Fancybox form redirecting

So I had the bright idea to use fancybox and jquery to send a form via AJAX. The form actually displays quite nicely. However when the form is submitted, the user is always redirected. I've tried to mitigate this several ways but to no avail. It's been a while since I've used jQuery so it may be something stupid. I can't for the life of me figure out what's going wrong.
Here's the code, to the best of my knowledge it should prevent the form from redirecting:
$('#fancybox-wrap #email_form').bind('submit', function(){
$.fancybox.showActivity();
var form_data = $(this).serialize();
form_data[crap] = 'Crap';
$.ajax({
type : "POST",
cache : false,
url : "<?php echo site_url('inventory/email'); ?>",
data : form_data,
success: function(data) {
$.fancybox(data);
}
});
return false;
});
If there are any better ways to do this I would glad to hear them. Thanks!
(This answer stems from the discussion between myself and MackDaddy in the comments of the question.)
The problem here is not that Ajax or Fancybox has interrupted the intended flow of the form (stopping it from following its action), but rather simply that:
The selector is wrong, since div#email_form is not the form itself, but rather its container, and therefore cannot take a submit event; and
Fancybox appears to remove the div and replace it elsewhere inside its own containers. Therefore, the use of the bind function does not work as expected, since the element it attaches to is removed from the DOM and a duplicate is inserted. The live function should be used instead, since it will attach the event not only to the first #email_form, but all subsequent ones that are inserted into the DOM.
Have you tried action="javascript: void(0)" in your form?

Categories

Resources