Two different ajax requests without refreshing page - php

I have a site that uses ajax to load a post directly to the page when clicked.
But... I also have an ajax contact-form at the same page. But if I click a post first, then want to send a message later, it fails. But if I refresh the page and go straight to the contact-form and send a message it doesn't fail at sending. Is there any way that I can maybe "reload" ajax without refreshing the page so that you can do multiple things at my site with ajax?
$(document).ready(function() {
function yournewfunction() {
var requestCallback = new MyRequestsCompleted({
numRequest: 3,
singleCallback: function() {
alert("I'm the callback");
}
});
var width = 711;
var animationSpeed = 800;
var pause = 3000;
var currentSlide = 1;
var $slider = $("#slider");
var $slideContainer = $(".slides");
var $slides = $(".slide");
var $toggleRight = $("#right");
var $toggleLeft = $("#left");
$toggleRight.click(function() {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed, function() {
currentSlide++;
if (currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
});
$toggleLeft.click(function() {
if (currentSlide === 1) {
currentSlide = $slides.length;
$slideContainer.css({
'margin-left': '-' + width * ($slides.length - 1) + 'px'
});
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
} else {
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
}
});
if ($(".slide img").css('width') == '400px' && $(".slide img").css('height') == '400px') {
$(".options").css("width", "400px");
$(".slide").css("width", "400px");
$("#slider").css("width", "400px");
$(".video-frame").css("width", "400px");
var width = 400;
};
if ($("#slider img").length < 2) {
$("#right, #left").css("display", "none");
};
if ($("iframe").length > 0 && $("iframe").length < 2) {
$(".options").css("width", "711px");
$(".slide").css("width", "711px");
$("#slider").css("width", "711px");
$(".video-frame").css("width", "711px");
$('.slide').hide();
var width = 711;
};
if ($(".slide img").css('width') > '400px' && $(".slide img").css('width') < '711px') {
$(".options").css("width", "600px");
$(".slide").css("width", "600px");
$("#slider").css("width", "600px");
$(".video-frame").css("width", "600px");
var width = 600;
};
}
$.ajaxSetup({
cache: false
});
$(".post-link").click(function(e) {
e.preventDefault()
var post_link = $(this).attr("href");
$("#single-post-container").html('<img id="loads" src="http://martinfjeld.com/wp-content/uploads/2015/09/Unknown.gif">');
$("#single-post-container").load(post_link, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
} else {
$("#main-content").fadeIn(500);
$("body").addClass("opens");
yournewfunction();
}
});
requestCallback.requestComplete(true);
return false;
});
});
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});

Though it's hard to follow exactly what is going on without being able to see the context of your HTML and without you giving us a more concrete description of exactly which line of code fails to execute, this is likely because one Ajax call is replacing a bunch of HTML which clobbers all your event handlers. So, when you then try to do the second Ajax operation, it's click handler is no longer in force so nothing happens.
Replacing a DOM element loses all event handlers that were attached to the original DOM element. Using .html() or assigning to .innerHTML replaces all the DOM elements within that element, thus losing all their event handlers.
The typical solution to this is to either reinstall the event handlers after replacing the content that you want event handlers on or use delegated event handling from a parent element that is not replaced.
Here are some references on delegated event handling:
JQuery Event Handlers - What's the "Best" method
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
Should all jquery events be bound to $(document)?

Related

Duplicate results Infinite scrolling API PHP

I am doing infinite ajax scrolling with php and api but my data is repeating. i don't want to load data when user is end of page(run perfectly) . What i want when user reach at certain div(check_onload) then load the data but in this case data is repeating.Here is below my code how i stop repeating data.
<div id="post-data"></div>
<div style="display:none;" class="ajax-load"></div>
<div class="check_onload"></div>
<script type="text/javascript">
///this run Perfectly
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var token = $(".tokenId").val();
GetMoreData(token);
}
});
///Repeating or duplication the data
$(window).on('scroll',function() {
if (checkVisible($('#check_onload'))) {
var token = $(".tokenId").val();
GetMoreData(token);
} else {
}
});
function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}
function GetMoreData(token){
$.ajax(
{
url: '/loadMoreData.php?token=' + token,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data.html);
$("#tokenId").val(data.token);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
You have 2 window scroll events being triggered, causing duplicates because you are requesting data from the server with the same token twice, each time the user scrolls the page. I will have to assume that removing 1 of them will fix your problem.
Without seeing your server code, this is the only solution.

Changing class type using Jquery

I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV
var loadinggif = '../img/loading.gif';
$(document).ready(function(){
// set up the click event
$('body').on('click','.btnbg', function() {
var toLoad = '../vr/startup.php';
$('.content').empty();
$('.content').slideUp('slow', loadContent);
$('#load').remove();
$('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
$('#load').fadeIn('normal');
function loadContent() {
var userName = $('#userName').val();
var remote_addr = $('#remote_addr').val();
var forwarded_for = $('#forwarded_for').val();
var url = $('#url').val();
//$('#forwarded_for1').val()'';
var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};
$('.content').load(toLoad, _post , function(response, status, xhr)
if (status == 'error') {
var msg = "Sorry but there was an error: ";
$(".content").html(msg + xhr.status + " " + xhr.statusText);
}
}).slideDown('slow', hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
You can use the css() function in Jquery :
$(".content").css({'background-color': 'red'});
Edit
I red your question wrong. To change class you can use $('.content').removeClass('classOne').addClass('classTwo');
If you have a class like has-error, you can use toggleClass() to toggle it, it will remove it if it's present or add it if not :
$('.content').toggleClass('has-error');
for your if elseprobleme, simply do :
if(condition) {
$('.content').removeClass('class2 class3').addClass('class1');
} else if(condition2) {
$('.content').removeClass('class1 class3').addClass('class2');
} else {
$('.content').removeClass('class1 class2').addClass('class3');
}
Use removeClass() and addClass().
Here is an example:
$('.content').removeClass("styleOne").addClass("styleTwo");
Edit
if(response == "Worked Fine"){
$('.content').removeClass("default").addClass("styleGreen");
}else{
$('.content').removeClass("default").addClass("styleRed");
}

delete file thumbnail from dropzone

Below is the code which I use to upload images through dropzone.
<script>
Dropzone.options.uploaddeadlineimages = {
// The camelized version of the ID of the form element
// The configuration
paramName: 'files',
url:"<?=base_url()."Product/upload_listing_images";?>",
dictDefaultMessage: "<img src='<?=base_url()."public/images/";?>/frontend/camera-black.png'><h2>Drag and drop your photos here to upload</h2><p><a href='javascript:void(0)'>Or Click here to browse for photos</a></p>",
uploadMultiple: false,
createImageThumbnails: true,
addRemoveLinks: true,
parallelUploads:100,
dictInvalidFileType:'Please upload only valid file type(png,jpg,gif,pdf)',
clickable:true,
maxFiles:100,
autoProcessQueue: true,
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
}else{
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
// The setting up of the dropzone
init: function() {
var myDropzone = this;
//alert after success
this.on('queuecomplete', function( file, resp ){
//alert('hahahahahaha');
});
// First change the button to actually tell Dropzone to process the queue.
document.getElementById("create_listing_button").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
the code has this parth which is used to append the new filename into hidden field so that i can save those names in database then. but the problem is that when i click on delete button i need to delete the name of that file from the hidden field too. I am getting an encrypted name from the server.
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
}else{
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
I don't need the exact code. I just need a method by which i can pass the new filename to a function when i click on delete button. this should not prevent the delete from doing it default function
well i found an answer . just update the success part according to your need. but as in my case i needed the image name as id of preview element. it will be done in this way.
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
file.previewElement.id = response;
}else{
file.previewElement.id = response;
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
to change the value of list after delete button just add the following code in dropzone.js file(just the way i did it).
the code starts from line number 274. just change it from this
removeFileEvent = (function(_this) {
return function(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
return _this.removeFile(file);
});
} else {
return _this.removeFile(file);
}
}
};
})(this);
_ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
removeLink = _ref2[_k];
_results.push(removeLink.addEventListener("click", removeFileEvent));
}
return _results;
}
},
to this(just four lines added. do it carefully, otherwise you can mess up all)
removeFileEvent = (function(_this) {
return function(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
var id = $(this).closest("div").prop("id");
update_img_list(id);
return _this.removeFile(file);
});
} else {
var id = $(this).closest("div").prop("id");
update_img_list(id);
return _this.removeFile(file);
}
}
};
})(this);
_ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
removeLink = _ref2[_k];
_results.push(removeLink.addEventListener("click", removeFileEvent));
}
return _results;
}
},
add this function at the end of file change ('#listing_images') to ('#id_of_your_field_which_contains_the_list')
function update_img_list(id){
var list = $('#listing_images').val();
separator = ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == id) {
values.splice(i, 1);
$('#listing_images').val(values.join(separator)) ;
}
}
return list;
}

jQuery load() not functioning as expected

I've a jquery script that call the number2.php page, which is supposed to execute and show the result in a <div>. The problem is that is not working. Can you help me? Thanks.
<script>
$(function() {
$('#submit').click(function() {
if ($('#taille').val() != 0) {
var param = 'l=' + $('#taille').val();
}
else {
var param = 'b=' + $('#datepicker').val() + 'c=' + $('#datepicker1').val() + 'num' + $('#num').val();
}
$('#retour').load('number2.php', param);
);
});
</script>
Your code has a syntax error; it's missing closing } in the click handler function.
now it works but after loading number2.php my main page is refreshed and i lose the result !!!
In this case, you should hook to the submit event of the form element and call preventDefault() on the event to prevent the normal form submission. Try this:
$(function() {
$('#myForm').submit(function(e) { // change #myForm to target the <form>
e.preventDefault();
var param = {};
if ($('#taille').val() != 0) {
param.l = $('#taille').val()
}
else {
param.b = $('#datepicker').val();
param.c = $('#datepicker1').val();
param.num = $('#num').val();
}
$('#retour').load('number2.php', param);
});
});

"Send" button to change color and message on sent using AJAX and PHP

So I am trying to create a form with a submit button that changes its color and message once it has been submitted. Both the code for submission through [AJAX and PHP] and button animation works on their own. However, I can't seem to get them working together. For some reason, it seems that the AJAX is cancelling or stopping the animation from running once the submit button has been clicked. Can someone point me in the right direction? The first part of the code triggers the button animation and the bottom half of the code triggers a post request to a php script to send an email to the person.
var submitButton = $('#submitme'); // Variable to cache button element
var alertBox = $('.alert-box'); // Variable to cache meter element
var closeButton = $('.close'); // Variable to cache close button element
$(submitButton).click(function() { // Initiates the send interaction.
if ($("#commentForm").valid()) {
$(this).fadeOut(500); // Fades out submit button when it's clicked
setTimeout(function() { // Delays the next effect
$(alertBox).fadeIn(500); // Fades in success alert
}, 500);
}
});
$(closeButton).click(function() { // Initiates the reset function
$(alertBox).fadeOut(500); // Fades out success message
setTimeout(function() { // Delays the next effect
$('input, textarea').not('input[type=submit]').val(''); // Resets the input fields
$(submitButton).fadeIn(500); // Fades back in the submit button
}, 500);
return false; // This stops the success alert from being removed as we just want to hide it
});
//AJAX code
$(document).ready(function() {
$(submitButton).click(function() {
var name = $('input[name=name]').val();
var email = $('input[name=email]').val();
var subject = $('input[name=subject]').val();
var comment = $('textarea[name=comment]').val();
if ($("#commentForm").valid()) {
//data to be sent to server
post_data = {'name':name, 'email':email, 'subject':subject, 'comment':comment};
//Ajax post data to server
$.post('form-processing.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
});
Check this Fiddle
$(document).ready(function(){
var submitButton = $('#submitme'); // Variable to cache button element
var alertBox = $('.alert-box'); // Variable to cache meter element
var closeButton = $('.close'); // Variable to cache close button element
$(submitButton).click(function() { // Initiates the send interaction.
$("#commentForm").validate();
if ($("#commentForm").valid()) {
$(this).fadeOut(500); // Fades out submit button when it's clicked
setTimeout(function() { // Delays the next effect
alertBox.fadeIn(500); // Fades in success alert
}, 500);
}
});
$(closeButton).click(function() { // Initiates the reset function
alertBox.fadeOut(500); // Fades out success message
setTimeout(function() { // Delays the next effect
$('input, textarea').not('input[type=button]').val(''); // Resets the input fields
submitButton.fadeIn(500); // Fades back in the submit button
}, 500);
return false; // This stops the success alert from being removed as we just want to hide it
});
//AJAX code
$(submitButton).click(function() {
var name = $('input[name=name]').val();
var email = $('input[name=email]').val();
var subject = $('input[name=subject]').val();
var comment = $('textarea[name=comment]').val();
if ($("#commentForm").valid()) {
//data to be sent to server
post_data = {'name':name, 'email':email, 'subject':subject, 'comment':comment};
//Ajax post data to server
// $.post('/link.php', post_data, function(response){
//load json data from server and output message
//if(response.type == 'error')
//{
// output = '<div class="error">'+response.text+'</div>';
//}//else{
output = '<div class="success">This is the post respnose.</div>';
//}
$("#result").html('ffasdf').slideDown('slow');
// }, 'json');
}
});
});
So it's not getting the effect that I want. Eventually I end up just using the ajax function in jquery and everything works for now on desktop, however it seems that on mobile device, the ajax call to the php script to process and send the email seems to be broken.
//AJAX code
$(document).ready(function() {
$(submitButton).click(function() {
if ($("#commentForm").valid()) {
//data to be sent to server
//post_data = {'name':name, 'email':email, 'subject':subject, 'comment':comment};
post_data = 'name='+ name + '&email=' + email + '&subject=' + subject + '&comment=' + comment;
$.ajax({
type: "POST",
url: "form-processing.php",
data: post_data,
success: function() {
//display message back to user here
}
});
return false;
}
});
});

Categories