This question already has answers here:
Prevent browser caching of AJAX call result
(21 answers)
Closed 6 years ago.
I have this problem where the jQuery get function inside my updateMyApps isn't being called correctly. I call the function right after declaring it and that works perfectly. It loops through the data and appends the elements to the DOM.
But when I submit the form #addapplicationform it runs the jQuery post function which works correctly but the updateMyApps function doesn't seem to be working correctly when that happens.
The console.log("Test"); always seems to get called. Even when submitting the form. But for some reason the callback function for that get request only gets called that one time on page load.
<script>
function updateMyApps() {
console.log("Test"); //Always works
$.get("/api/clients", function(data) {
console.log(data); //Works first time
$("#myapps").html("<h4>My Applications</h4>");
data.forEach(function (item) {
var element = '<div>' + item.name + '</div>' + '<div>' + item.id + '</div>' + '<div>' + item.secret + '</div>' + '<input type="submit" class="submit btn btn-primary form-control" value="Edit" style="width: 100px;">';
$("#myapps").append(element);
});
});
}
updateMyApps(); // Works perfectly
$("#addapplicationform").submit(function( event ) {
event.preventDefault();
$.post("/api/clients", $( "#addapplicationform" ).serialize(), function () {
updateMyApps(); //Doesn't work
});
});
</script>
Any ideas on why the get request callback is only firing once?
EDIT
Forgot to mention this. It looks like the GET /api/clients only is getting called on page load. When submitting the form it isn't even hitting my back end at all.
EDIT 2
Realized this was a caching issue. Adding $.ajaxSetup({ cache: false }); seems to have fixed the issue. Also marked the question as duplicate of where I found that code snippet.
Try adding a console.log in your submit....
<script>
function updateMyApps() {
console.log("Test"); //Always works
$.get("/api/clients", function(data) {
console.log(data); //Works first time
$("#myapps").html("<h4>My Applications</h4>");
data.forEach(function (item) {
var element = '<div>' + item.name + '</div>' + '<div>' + item.id + '</div>' + '<div>' + item.secret + '</div>' + '<input type="submit" class="submit btn btn-primary form-control" value="Edit" style="width: 100px;">';
$("#myapps").append(element);
});
});
}
updateMyApps(); // Works perfectly
$("#addapplicationform").submit(function( event ) {
event.preventDefault();
console.log("works!!!"); // <-- add this console.log
$.post("/api/clients", $( "#addapplicationform" ).serialize(), function () {
updateMyApps(); //Doesn't work
});
});
</script>
Related
EDIT1:
So I did managed to fix this problem. But I'm not sure how.
I've been using two identical forms with different IDs for different
reasons (Add and Edit forms). In those forms I had inputs with IDs.
But for both forms I've been using the same ID for the inputs in them.
So I change those IDs to classes (how it should be). I think this was
the reason for the bug.
The second thing I've changed was removing
the first form in a moment I would click on the second form (Edit
form/button) because It was making a trouble, trouble I didn't
addresed in here and I don't think It has anything to do with my
initial problem. Just writing everything I did in any case.
I'm having a problem with jQuery Datepicker and Timepicker. I'll try to describe my situation.
I have dynamically created html for my local storage values (imagine squares with it's own data in it.)
My problem... If I simply load these squares and I want to change something, by clicking on edit button, It will create a form with pre-written values in them, by clicking on one of these inputs, a calendar shows up. And then after clicking on some date, the pre-written value changes with value of a date I've clicked on. Same for Timepicker. But! There is a problem.
If I want to create new squares with new data ( by dynamically creating form with inputs, then the data is saved to local storage) and then (without refreshing the page) clicking on edit button, bringing same old form (as described above) and clicking on some of the inputs, calendar shows up, but after clicking on some date, the value of the input doesn't change. Same with Timepicker, doesn't overwrite the pre-witten value.
But if I refresh the page and want to edit something (without creating new squares/data), Datepicker change the value without problem.
Can you help me please? I'll try to answer any question if needed.
Here is a function that show everything saved in local storage.
function fetchBookmarks() {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
bookmarks.sort(function compare(a, b) {
var dateA = new Date(a.date);
var dateB = new Date(b.date);
return dateB - dateA;
});
var results = document.getElementById("results");
results.innerHTML = "";
for (var i = 0; i < bookmarks.length; i++) {
var date = bookmarks[i].date;
var distance = bookmarks[i].distance;
var time = bookmarks[i].time;
results.innerHTML += '<div class="bookmarks shadow p-3 m-2 bg-light rounded">' +
'<div class="row">' +
'<div class="col">' +
'<h3>Date: </h3>' +
'<h3>Distance: </h3>' +
'<h3>Time: </h3>' +
'</h3><input onclick="editBookmarks(\'' + time + '\')" class="btn btn-outline-primary mr-1 btn-lg" id="edit" type="button" value="Edit"><input onclick="deleteBookmarks(\'' + time + '\')" class="btn btn-outline-danger btn-lg" id="deleteBookmarks" type="button" value="Delete">' +
'</div>' +
'<div class="col">' +
'<h3 class="font-weight-bold">' + date + '</h3>' +
'<h3 class="font-weight-bold">' + distance + '</h3>' +
'<h3 class="font-weight-bold">' + time + '</h3>'
'</div>' +
'</div>' +
'</div>';
};
};
And here is function after clicking on edit button...
function editBookmarks(time) {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
for (var i = 0; i < bookmarks.length; i++) {
if (bookmarks[i].time == time) {
$(".bookmarks").hide();
results.innerHTML += '<form class="bookmarks shadow p-3 m-2 bg-light rounded" id="editForm">' +
'<h4>Date: </h4><input class="form-control form-control-lg" id="date" placeholder="Select" value="' + bookmarks[i].date + '" type=""><br>' +
'<h4>Distance: </h4><input class="form-control form-control-lg" id="distance" placeholder="In miles" value="' + bookmarks[i].distance + '" type="text"><br>' +
'<h4>Time: </h4><input class="form-control form-control-lg" id="time" placeholder="Select" value="' + bookmarks[i].time + '" type=""><br>' +
'<input class="btn btn-success btn-lg" type="submit" value="Submit">' +
'</form>';
/* $('#date').datepicker()
$('#time').timepicker({
timeFormat: "H:mm",
hourMin: 0,
hourMax: 4
}); */
bookmarks.splice(i, 1);
};
};
$("#editForm").on("submit", function (e) {
var date = $("#date").val();
var distance = $("#distance").val();
var time = $("#time").val();
if (!distance.length || !date.length || !time.length) {
alert("Something missing!")
} else {
var bookmark = {
date: date,
distance: distance,
time: time
};
bookmarks.push(bookmark);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
fetchBookmarks();
$("#editForm").hide();
};
e.preventDefault();
});
$("#search").hide();
};
And here is Datepicker with Timepicker
$('body').on('focus', "#date", function () {
$(this).datepicker();
});
$('body').on('focus', "#time", function () {
$(this).timepicker({
timeFormat: "H:mm",
hourMin: 0,
hourMax: 4
});
});
I know that this is quite much to ask and I'm having a problem with articulating. I'm just lost in this.
I'm thankful for any help.
Here's a link for GitHub file, I think It's better than posting the code here. My whole problem is at the bottom of the file, if you're interested.
https://github.com/ovy1448/MyRun/blob/master/js/main.js
Thanks again.
As per my understanding, since you are using onfocus event to attach datepicker/timepicker, all the event of datepicker/timepicker is not getting attached to the field. I faced similar problem 2-3 years back. What I did is that I added a function for the datepicker onSelect event which updates the field value. You can try this(as below) and let me know if it works
$('body').on('focus', "#date", function () {
$(this).datepicker({onSelect: function(dateStr){
$('body').('#date').val(dateStr);
}});
});
$('body').on('focus', "#time", function () {
$(this).timepicker({
timeFormat: "H:mm",
hourMin: 0,
hourMax: 4,
onSelect: function(timeStr){
$('body').('#time').val(timeStr);
}
});
});
So I did managed to fix this problem. But I'm not sure how. I've been using two identical forms with different IDs for different reasons (Add and Edit forms). In those forms I had inputs with IDs. But for both forms I've been using the same ID for the inputs in them. So I change those IDs to classes (how it should be). I think this was the reason for the bug.
The second thing I've changed was removing the first form in a moment I would click on the second form (Edit form/button) because It was making a trouble, trouble I didn't addresed in here and I don't think It has anything to do with my initial problem. Just writing everything I did in any case.
The situation is this:
$.each(data, function(index, element) {
$('#bullets').append('<li id="demo" onclick="loadCards(\'' + element.id
+ '\','+index+')"><a href=\'#\'>' + element.name + '</a></li>');
});
This is adding an inline javascript onclick and calls the function loadCards with two parameters id and name.
Works fine in normal web application but am creating a chrome extension and figured out the inline javascript is not supported.
I tried to add event-listener but am not able to pass the parameters. I tried adding following code after the loop:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#demo').addEventListener('click', loadCards( ));
}); // have to pass id and name in loadCards.
How can I pass id and name from above JSON to the event listener?
Try below: set values as data attributes and read it in click event handler
$(function(){
$.each(data, function(index, element) {
$('#bullets').append('<li id="demo" data-id="' + element.id + '" data-index="' + index + '" data-name="' + element.name + '"><a href=\'#\'>' + element.name + '</a></li>');
});
$(document).on('click', '#bullets li', function(){
var id=$(this).data('id');
var name= $(this).data('name');
loadCards(id, name);
});
});
the argument to addEventListener needs to be a function reference, not a call to the function.
document.querySelector('#demo').addEventListener('click', function() {
loadCards(param1, param2 );
});
I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(''.$variable.'');"
It will work! (with no Vue), ok ? :)
The following code works fine on Chrome and FireFox, but it doesn't work properly on IE:
if (jQuery.trim(jQuery("#"+element_id.name).val()) != "" && jQuery.trim(jQuery("#"+element_id.name).val()) != "0") {
jQuery("#filters-box").append('<span id="filter-'+ element_id.name +'" class="toggler"><button class="button white" onClick="removeFilter(\'filter-' + element_id.name + '\')"> ✖ </button>' + document.getElementById(element_id.name + "_caption" ).value + ' -> ' + document.getElementById(element_id.name).value + '</span>');
}
Though it can append the HTML code and render them on the page properly, but its onClick event generates the above error message.
Strangely i have tried changing your function name "removeFilter" and it works absolutely fine
Please find the change
var element_id = {
name: "test",
"test_caption": "_caption"
};
function rmvFilter(ele) {
alert(ele);
}
var html = '<span id="filter-' + element_id.name + '" class="toggler">';
html += '<button class="button white" id="button" onClick="rmvFilter(\'caption_' + element_id.name + '\');"> ✖ </button></span>';
jQuery("#filters-box").append(html);
I dont find any error in your code except that the exact combination of name isn't strangely working in IE9 only
If you precompile the string with jQuery you can attach events as if it were already in the DOM (basically). This is cleaner, non-obtrusive and should work in all browsers supported by jQuery:
if (jQuery.trim(jQuery("#"+element_id.name).val())
!= "" && jQuery.trim(jQuery("#"+element_id.name).val()) != "0") {
// precompile to a temp var
var $temp = jQuery('<span id="filter-'+ element_id.name +'" class="toggler"><button class="button white"> ✖ </button>' + document.getElementById(element_id.name + "_caption" ).value + ' -> ' + document.getElementById(element_id.name).value + '</span>');
// this works fine
$temp.find('button.button.white').on('click', function () { removeFilter('filter-' + element_id.name); });
jQuery("#filters-box").append($temp);
}
My thanks to you, Kartheek. I just ran into the same problem with a function called "removeFilter(event)" in IE9 (it worked fine in Firefox and Chrome) and changing the function name worked for me too.
I can only assume this was some kind of built-in function for IE which had not been implemented as of IE9, so the browser calls the wrong function which throws its not-implemented error.
I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);