I hired a developer to help with some work, he was mostly PHP focused and attempted this javascript. The following AJAX script breaks the page whenever it reloads the HTML into the DOM. It called a function via Codenigniter to reload the view within the page. Once this happens, all of the javascript no longer works.
I can't seem to find a solution that helps solve this issue. Please help.
Note: Ideally I would of rather the code only loaded the data and not refresh the HTML, but for now this will need to do as I am up against a timeline.
The code:
$(document).ready(function () {
// Ajax Form Submit
$('body').on('click', '.submitForm', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
var url = $('#' + formid).attr('action');
var formdata = $('#' + formid).serialize();
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$(this).hide();
$('#' + formid).find('.loader').show();
}
$.ajax({
type: "POST",
cache: false,
url: url,
data: formdata,
dataType: 'json',
success: function (data) {
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$('#' + formid).find('.submitForm').css('display', 'inline');
$('#' + formid).find('.loader').hide();
}
if (data.type == 'add') {
if (data.html) {
var newhtml = "<tr>" + data.html + "</tr>";
$('.tab-pane.active table').append(newhtml);
}
$('#' + formid).find('.message').html(data.msg).show();
$('#' + formid).trigger('reset');
setInterval(function () {
$('#' + formid).find('.message').hide();
}, 5000);
} else {
if (data.error) {
$('#' + formid + ' .message').show().html(data.error);
} else {
$('#' + formid + ' .message').show().html(data.msg);
if (data.reload_loc) {
window.setTimeout(function () {
window.location.href = data.reload_loc;
}, 4 * 1000);
}
}
}
}
});
});
// Generic Save Form Data
$('body').on('click', '#saveFormdata', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
$('#' + formid).submit();
});
});
You just do something like this:
function bindEvent()
{
$('body').on('click', '.submitForm', function () { //Your code });
$('body').on('click', '#saveFormdata', function () { //Your code});
}
function unblindEvent()
{
$('body').off('click', '.submitForm'); //Something like this, please read Jquery.off
$('body').off('click', '#saveFormdata');
}
Before you replace these element, call unblindEvent(). And after you replace these elements call bindEvent().
Related
Ajax1:
<script type="text/javascript">
$(document).ready(function () {
$('.CategoryName').click(function() {
var categoryName = $(this).attr("data-id");
var url="{{url('getSubCategoryName/').'/'}}" + categoryName;
$.ajax({
url : url,
type: 'GET',
dataType:'json',
success:function(data){
$.each(data, function( index, value ) {
var output = '';
output = ' ' + value.subCategoryName + '';
**$(".subcategory").append('<ul><li data-
id="'+value.subCategoryName+'" class="getDeviceCategoryName">'+value.subCategoryName+'</li></ul>')**
});
}
});
});
});
</script>
The code which is marked in bold has the value for data-id attribute..And I need to pass that value when class named getDeviceCategoryName is clicked.
AJAX2:
<script type="text/javascript">
$(document).ready(function () {
$('.getDeviceCategoryName').click(function() {
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
</script>
This is one I tried for that..But its not working.It doesnot alerts or shows any error.
You should consider jquery event delegation:
Change your jquery selector line like this:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','.getDeviceCategoryName',function() {
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
</script>
Here you go with a solution
$(document).ready(function () {
$(document).on('click', 'li.getDeviceCategoryName', function() {
console.log($(this).data("id"));
});
});
Since the elements are generated dynamically, so you need to delegate events.
For receiving the data-attribute you can do $(this).data("attribute-name"); in your scenario it will be $(this).data('id');
Hope this will help you.
Personally I think code is more efficient if the click event is applied to the element right after it's created.
$(function () {
$('.CategoryName').click(function () {
var categoryName = $(this).attr('data-id');
var url = '{{url(\'getSubCategoryName/\').\'/\'}}' + categoryName;
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data, function (index, value) {
var output = '';
output = ' ' + value.subCategoryName + '';
$('.subcategory').append($('<ul/>').append('<li data-id="' + value.subCategoryName + '" class="getDeviceCategoryName">' + value.subCategoryName + '</li>')
.find('li')
.click(function () {
var subCategoryName = $(this).attr('data-id');
alert(subCategoryName);
});
);
});
}
});
});
});
$(document).ready(function () {
$(document).on('click', '.getDeviceCategoryName', function(){
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
I want to get an alert once the DIV is refreshed with the new Information/Website
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function changeURL(){
var URL2add = "http://google.com";
var user="1";
$.ajax({
url: 'myApi.php?user=' + user + '&url='+ URL2add,
success: function(html) {
var newHTML = "<object id='webloader' data='" + html + "'></object>";
$("#exweb").fadeOut(5, function () {
$("#exweb").html(newHTML).fadeIn(50);
// alert("done");
});
}
});
}
</script>
the way i have it now the alert pops up Before the Div is refreshed
You can use the complete action of fadeOut() function similar to what you are doing for fadeIn(). In your above code, you can simply do it like this-
$.ajax({
url: 'myApi.php?user=' + user + '&url='+ URL2add,
success: function(html) {
var newHTML = "<object id='webloader' data='" + html + "'></object>";
$("#exweb").fadeOut(500, function () {
$("#exweb").html(newHTML).fadeIn(5000, function() {
alert("done");
});
});
}
});
Another example with working fiddle here - https://jsfiddle.net/gug08249/
I have an ajax function, which submits the data and refreshes the div after the data has been updated. The problem is that the jQuery elements within the div breaks after the form has been submitted, and the div has been refreshed.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit" ,function(){
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function(msg){
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(function() {
$('a[id^="teamname"]').editable({
ajaxOptions : {
type : 'post'
}
});
});
$(document).ready(function() {
$('select[id="swap"]').change(function(){
$( "#saveprogress" ).show("fade");
});
});
You need to use event delegation to support dynamically added elements also you need to initialize the plugin again once the div is refreshed
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit", function () {
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function (msg) {
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission and pass a callback which will initialize the plugins
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh", createEditable);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(createEditable);
function createEditable() {
$('a[id^="teamname"]').editable({
ajaxOptions: {
type: 'post'
}
});
}
$(document).ready(function () {
//use event delegation
$(document).on('change', 'select[id="swap"]', function () {
$("#saveprogress").show("fade");
});
});
I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...
i am working on project which have like unlike function look like facebook but i am getting stuck when i click multiple time at once on like button or unlike button then its work like firing and if i have 1 or 2 like and i click many time fast fast then my likes gone in -2 -1. how i solve this issue ? if when click many time always get perfect result. below my jquery script
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
});
});
});
It is because of the async nature of ajax request.... when you click on the element continuously... the click event will get fired before the response from previous request come back and the link status is updated to next one
Case:
Assume the rel is unlike, then before the response came back again another click happens so the rel is not yet updated so you are sending another unlike request to server instead of a like request
Try below solution(Not Tested)
$(document).ready(function () {
var xhr;
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
//abort the previous request since we don't know the response order
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false
}).done(function (html) {
$('.spn' + ID).html(html);
}).always(function () {
xhr = undefined;
});
});
});
Set a variable, we'll call it stop and toggle it.
$(document).ready(function () {
var stop = false;
$(".like").click(function () {
if (!stop)
{
stop = true;
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
}).always(function() { stop = false; });
}
});
});