Commenting System - Showing posted comment without page reload - javascript

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 ;-)

Related

js/jquery Async Content Overwrites Page

ive ran into the following Problem and maybe someone can give me a little advice or a way around this. I have the following Problem:
A Partner of my Page provided me with a Code that i should use on my Page, which writes some Content to my Page that i really want.
Unfortunately this Content is only relevant to People living in a certain region.
So i am using the service of an ip-api which returns the region the current user is in and lets me work with that. This is done with a jsonp ajax call.
If the Person is in the right Region the Code should be executed, if he is not, it shouldnt.
The Problem is that the code to be executed contains a document.write. So if i call that code inside of the ip-api callback the document is allready loaded and the document.write will overwrite my page.
So the big Question is: Is there a way to capture the document.write output into a variable like with PHPs output buffer? Or maybe some way to overwrite the content of an iframe instead of the whole Page? Anything that prevents the document.write from overwriting the page and redirects its output into a part of my page would be sufficient.
Thanks for your time :)
PS: this is the code im talking about:
$.ajax({
url: "http://ip-api.com/json/",
dataType: "jsonp",
success: function( response ) {
if(
response["city"]=="Hamburg" ||
response["region"]=="SH" ||
response["region"]=="NW"
){
document.write("Some Content here");
}
}
});
Replace
document.write("Some Content here");
with
$('#my-container').html('Some content here');

Alternative of this script in jQuery?

I use the following script to get the content of the remaining.php.
The drawback is that sometimes it doesn't work or it is kinda slow to display the text. Is there any other way of doing this ?
Thank you
$(document).ready(function(){
$("#SubmitButton").click(function (){
$('#remaining').load('remaining.php');
});
});
You could directly include the contents of remaining.php into the initial markup but make it hidden by applying display:none; style to the #remaining element. Then when the button is clicked simply show it:
$(function() {
$('#SubmitButton').click(function () {
$('#remaining').show();
});
});
Of course if you need to pass some parameters to the script which will depend on some javascript variables that are known only at the moment the button is clicked you will need to use AJAX as you are currently doing.
If "sometimes it doesn't work or it is kinda slow", the problem is probably the server you are using, not your javascript code.
The javascript code you're showing us here doesn't really do anything that could be slow, it only binds an event on a submit button. However, what could be slow is waiting for the answer from your web server when sending a request for remaining.php
From there, there is a thousand of reasons why your web server could be slow. Maybe you could post the content of your remaining.php file so we can see what is going on in there.
This isn't really a fault of jQuery, but the speed of return from your server. Perhaps there's a better way to handle it instead of fetching a full page?
For example, if your content request was only retrieving a message, you could return JSON from your server and have jQuery handle the data:
$(document).ready(function(){
$("#SubmitButton").click(function (){
$.post('remaining.php',
null,
function(data) {
// do stuff with your JSON result
});
});
});
When you're using .load(), you're sending a request to the server to get your content, which is why it can seem slow. I'm not sure why it sometimes won't work , but I would venture to guess that you may be clicking $("#SubmitButton") before $(document).ready fires.
Depending on your implementation, you may be able to refactor your application so that the text you want to display is pre-loaded on the page.

jQuery live doesn't works as expected

i have problems with ajax requests and simple <input type="submit"/>.
i use to load views inside other views, modular i mean, with jquery using .load(url) from one view to another.
so the problem is that if i load view_2 inside view_1 and the js script for view_2 is inside view_1 i need to use live('click') for example to launch an xhr request from view_2, so when i try it launches 3 (multiple) xhr at same time, instead of only 1 at time, don't know why.
the only thing i know is:
using live('click') in view_1 it launches 3 multiple XHR.
using click() in view_1 it doesn't work(obviously i think).
using click() directly inside view_2 it works (but i can't use js
in loaded views, i can use js only in "parents" views)
the functions are really simple, really don't know why i have this problem (i also disabled submit in ajax beforeSend) check this is a view_1 code which runs on loaded view_2 and launches 3 XHR for click :|
$(document).ready(function(){
$('#save-doc').live('click',function(){
var _title = $('#doc-title').val();
var _doc = $('#doc-doc').val();
update_doc(url_update_doc,{'title':_title,'doc':_doc,'id_doc':_choosed_doc,'id_project':id_project},this);
});
});
function update_doc(_url,_data,_starter){
$.ajax({
type:'POST',
data:_data,
url:_url,
dataType:'json',
beforeSend:function(){
$('.ajax-loading').show();
$(_starter).attr('disabled','disabled');
},
error:function(){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
},
success:function(json){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
if(json.error){
$('#error-title').html(json.error_title);
$('#error-doc').html(json.error_doc);
$.scrollTo('.append-form-edit-doc','fast');
}
if(json.confirm){
$.scrollTo('#top','fast');
$.gritter.add({
title:'Document Saved',
text:json.confirm
});
}
}
});
}
If that's a submit button inside the form then unless you prevent the default action, the form will be submitted. (That'd account for 2 POSTs, but not three.)
Remember that .live() is binding the event handler to the document itself. With that in mind, it is searching for #save-doc throughout the document on every click.
If there are multiple elements in the document with the 'save-doc' ID then they'll all be triggered.
However, what I bet is happening to you is you may have multiple forms layered which are all being executed by this one input.
Edit: Third possibility, is what Pointy mentions. Executing a submit via your event handler and another submit occurring because of browser behavior.
Please provide the HTML and what is being loaded into them.

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?

page fetched by AJAX cannot execute any javascript

I have been with that a whole day..
I have a home page(index.php) and i have a small menu in it(made up of buttons) and a <div id=tab_contents></div>
i have used AJAX in such a way that whenever i click on any of these buttons, another page is loaded in the tab_contents-div.ie:home_tab0.php, home_tab1.php, home_tab2.php for each button respectively.
The page that i want to fetch with ajax should contain a <body onload=initialize()> ...</body> function.or it can contain a javascript code snippet to trigger the initilization() function.
that is when the button is clicked,the page lets say home_tab0.php is loaded, codes inside the home_tab0.php should trigger the initialization() frunction.
i have tried every possible way in my knowledge to make it work but without success...:(
please if i can get any help for this i would be so grateful.
With jQuery it's easy to call any function after the ajax call has returned, and data is loaded. I guess that's what you want to do. There are a few examples here:
http://api.jquery.com/jQuery.get/
E.g:
$.get('home_tab0.php', function(data) {
$('#tab_contents').html(data);
initialize();
});
This is a common problem. I recommend using jQuery and letting it take care of this for you. Reimplementing what they've done would be a waste of your time.
http://api.jquery.com/load/
$("#tab_contents").load("http://www.foo.com/loadContent");

Categories

Resources