I'm developing a post comment system with PHP CodeIgniter framework.When a user comment for a post-it didn't get loaded without page refresh. Here is my ajax code.
var id = $(this).attr("data-id");
// check to see which events this comment already has
var events = $._data( this, 'events' ).keypress;
// Try to find if keypress has already been registered
// registering it twice causes duplicate comments
var hasEvents = false;
for(var i=0;i<events.length;i++) {
if(events[i].namespace == "") {
hasEvents = true;
}
}
if(!hasEvents) {
$.ajax({
url: global_base_url + 'feed/post_comment/' + id,
type: 'POST',
data: {
comment: comment,
csrf_test_name: global_hash,
page: global_page,
hide_prev: hide_prev
},
dataType: 'json',
success: function(msg) {
if (msg.error) {
alert(msg.error_msg);
return;
}
$('#feed-comments-spot-' + id).html(msg.content);
$('#feed-comments-' + id).html(msg.comments);
}
});
}
My form code is:
<div class="feed-comment-area" id="feed-comment-<?php echo $r->ID ?>">
Related
After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.
(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});
I have chat and i am loading these by ajax
$.ajax({
type: "GET",
url: "chat/mini.php",
success: function(chat){
$('.chat-message').html(chat);
},
error: function(err) {
console.log(err);
}
});
And i Have in chat/mini.php link to delete
X
and script
$(".delbutton").click(function () {
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if (confirm("Sure you want to delete? There is NO undo!")) {
$.ajax({
type: "GET",
url: "chat/delete.php",
data: info,
success: function () {
}
});
}
return false;
});
And these cod working when i not loading chat with ajax but when i loading these with ajax these don't working. I must add something to work?
So I have a one page site, that only shows a login with username and password.
I have the $.ajax fire on the submit click.
What I want is for it remove the login box and load in the page that will have all the content ready for the ajax content to go into.
$.ajax function works and was tested by alert(n); the number for my json array.
What happens is after the box disappears and the page loads, it reverts back to the login box.
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
});
});
This is a pretty common problem. When you bind to a submit event, you are effectively able to run some logic, but unless you stop it, the event will continue to propagate and will also run the normal submit logic, which causes a full page refresh. This is fairly easy to prevent:
$(document).ready(function() {
$('#launchform').on('click', function(e) {
e.preventDefault(); // Add this
});
});
As stated in another answer, you can also return false;. That is sometimes a better way to do it when using jQuery as it effectively cancels everything. Although, in non-jQuery solutions, it doesn't stop the event bubbling. You can read more details about why here: event.preventDefault() vs. return false
If you are performing this within a <form> element then the form is probably submitting after the ajax call and reloading the page. Try adding:
return false;
to the end of the click event function to prevent the form submitting.
So the above code would look like:
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
return false;
});
I have wrote a webkit notification script on my web app to pull notifications from a database. The code is seen below:
function checkNotifications() {
if (window.webkitNotifications.checkPermission() == 1) {
window.webkitNotifications.requestPermission();
}
else {
$.ajax({
type: "GET",
dataType: 'json',
url: '/check_notifications',
success: function(data){
if (data){
var ticketId = data.ticket_id;
console.log(data);
var comment = data.comment;
var createdDate = data.created_at;
var notificationComment = data.comment;
var notificationId = data.notifcation_id;
var notification = window.webkitNotifications.createNotification('/pt_logo_small.png', 'Project Ticket '+ticketId+ ' Updated!', 'Ticket has been updated. Click here to see!');
notification.show();
console.log(notificationId);
notification.onclick = function(){
this.close();
console.log("NOTIFICATION WAS CLICKED!")
$.ajax({
type: "GET",
dataType: 'json',
url: '/read_notifications/' + notificationId,
success: function(){
window.location = '/pto/' + ticketId;
},
error: function(){
window.location = '/pto/' + ticketId;
}
});
console.log(ticketId, comment, createdDate);
};
}
}
});
}
setTimeout(checkNotifications, 20000);
}
For some reason. I if select another tab, or go to another path inside my webapp, the script still runs to display the notifications, however the .onclick event never triggers.
Anyone have any idea why the even wouldn't trigger?
According to Apple, onclick should bring the page which created the event to focus, which it does. However nothing inside my .onclick function triggers.