My jQuery ajax call works fine with Jquery 1.7. I had to update some code to 1.9 and it doesn't work anymore. This call is part of a contact form. This sends info to a separate database via the curl file. The contact form itself feeds just fine. It's just this code that has stopped working.
If I use this library it functions fine:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
With this library it stops working:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
function event_listener() {
$('#submit-btn').click(function() {
var checkbox = $('#newsletter-signup');
var emailAddress = $('#email-input').val();
if (checkbox.attr('checked')) {
$.ajax({
url: '/form-curl.php?e=' + emailAddress,
success: function(r) {
$("#sales-contact-form").submit();
}
});
} else {
$("#sales-contact-form").submit();
}
});
} //end event_listener
$(function(){
event_listener();
});
Just a thought: the script probably does not reach inside of the if (checkbox.attr('checked')).
According to the upgrade guide to jQuery 1.9:
For example, boolean attributes such as checked and disabled on a
checkbox are affected by this change. The correct behavior of
"input[checked]" is to select checkboxes that have a checked
attribute, regardless of its string value, and regardless of their
current state.
Sooo, all that checkbox.attr('checked') does, is it returns the value of checked attribute. End of story.
I assume you need to change this
if (checkbox.attr('checked'))
to this
if (checkbox.is(':checked'))
-- which will actually give you a boolean on the state of the checkbox.
Related
I have a program that calculates bitcoin mining profitability and thus requires the live price of bitcoin, but I also want the user to be able to edit the price after it is initially loaded as the live price.
The problem I'm running into is that when I run my code bpv goes initially as undefined, even though it should be called when the body loads, theres no issue with the ajax call because once run update after the body has loaded, bpv gets defined.
I suspect this is because the ajax call takes longer than the page takes to load, leaving bpv undefined, then when I run update() the code is already initialized so theres no delay.
What I also suspect would fix this would be to make the page wait to load until the ajax call has been sent back, but I can't imagine this being scaleable at all?
I'm very new to this so try and be easy on me, thanks.
<head>
var bpv;
function update(){
getVal();
getPrice();
function getPrice(){
$.ajax({
dataType:"json",
type: 'GET',
url:'https://blockchain.info/ticker',
success: function(data){
bpv = data.USD.last;
}
});
}
}
</head>
<body onload = "update()" >
<script>
function getVal(){
//Current Value of Bitcoin
bpv = document.getElementById("bp").value;
</script>
Value of Bitcoin ($)<br/>
<input type="text" id="bp" onKeyDown="getVal()" onKeyUp="getVal()" value="" ><br/>
EDIT: I used Alex's solution, although it only fixed the input displaying undefined, and not the end result of the calculations, so if implemented a very janky solution in where I run the calculation again, .1 seconds after the page has loaded, if anyone whos smarter than me knows a better solution my ears are wide open
Ajax calls are asynchronous. So the rest of the page will always execute while the call is being done. I'm not exactly sure what you are trying to accomplish, but if you wish to show the value of Bitcoin on the input box and then let users change it after it's been loaded, you could follow something like:
Start with input box disabled;
Load bitcoin with AJAX call;
Set the response price into the field;
Enable the field so users can edit;
That could look like:
(I'm removing part of the code to exemplify, but if you have any questions let me know)
<head>
<script>
var bpv;
document.addEventListener("DOMContentLoaded", function(event) {
getPrice();
});
function getPrice(){
$.ajax({
dataType:"json",
type: 'GET',
url:'https://blockchain.info/ticker',
success: function(data){
bpv = data.USD.last;
setPriceInput(bpv);
}
});
}
function setPriceInput(value) {
var input = document.getElementById('bp');
input.value = value;
input.disabled = false;
}
</script>
</head>
<body>
Value of Bitcoin ($)<br/>
<input type="text" id="bp" value="" disabled>
</body>
https://jsfiddle.net/81oqsk5x/1/
This solution will wait for the page to be rendered, then try to get the price. Once the price is responded from the API, it will set the price on the input and enable it again (if you look at the input element, it starts as disabled)
So a couple things.
Your first tag is this is not valid. The head tag needs to
contain proper contents.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head
Move all the javascript inside of the script tag
function getVal(){ is not properly formatted and has invalid syntax. you are missing a closing bracket
Instead of trying to set bpv after you make the AJAX call, update the value of the DOM document.getElementById("bp").value = data.USD.last
Always put your Jquery code within the Ready function
$(document).ready(function(){
// your code here
});
I have a drop down list that when a selection is made will insert a bunch of elements within a form to the DOM using ajax, within this form I have textareas that I wish to be TinyMCE textareas.
I have this inside of my HTML head:
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
This is the ajax function that I use to add a bunch of elements, this is working how I need it to.
function getSecFacility(facsecid, facid) {
$("#new_section_form").hide();
$.ajax({
type: "POST",
url: "facility_section_information.php",
data: 'facility_section_id='+facsecid+'&facility_id='+facid,
success: function(data){
$("#selected_fac_section").html(data);
}
});
//loadTinyMCEEditor();
};
I have other textareas on my page that are not inserted by ajax and they display as WYSIWYG editors no problem, the issue is when I am adding in new elements.
I have checked several other questions trying to find an "answer" but nothing is working.
I tried to make a function called loadTinyMCEEditor() that I was calling within my getSecFacility() function after my ajax call. Within this function I was trying to reinitialize tinyMCE for these newly added textareas.
loadTinyMCEEditor() looks like this:
function loadTinyMCEEditor() {
tinyMCE.init({
selector: "textarea"
});
tinyMCE.execCommand('mceAddControl', false, 'test'); //test is the class name I gave this textarea
//tinyMCE.execCommand('mceAddControl', true, 'test'); //tried setting the bool to true..even tried without these lines
}
No matter what I try I cannot seem to get it to work with newly inserted textareas, How can I get these textareas to be TinyMCE textareas?
EDIT
I can now view the editor to my newly added textareas after I make a selection from my drop down list. However this only works once, if I make a second selection the new textareas only display as plain textareas. Here is what I changed in my ajax function:
function getFacSecFacility(facsecid, facid) {
$("#new_section_form").hide();
$.ajax({
type: "POST",
url: "facility_section_information.php",
data: 'facility_section_id='+facsecid+'&facility_id='+facid,
success: function(data){
$("#selected_fac_section").html(data);
loadTinyMCEEditor();
}
});
};
function loadTinyMCEEditor() {
tinymce.init({
selector: "textarea"
});
}
So after I make a selection this ajax function will run and display new textareas + other form information and I re-initialize the tinymce editors but for some reason this is only working once.
What should I change/do so that I can make multiple selection from my drop down list so that each time the new textareas will display as tinymce textareas?
You need to call tinyMCE.activeEditor.setContent with your incoming ajax-content. In your callback try:
tinyMCE.activeEditor.setContent(data);
Greetings
If you want to convert #selected_fac_section to a tinymce editor, you should call the init function of tinymce in your success function. Ajax calls are async unless you define otherwise. So, if you try to initialize the textarea outside of the ajax call, there still won't be a textarea to decorate with tinymce because the ajax call hasn't been finished yet. Use the id value for the selector this time and you should be good to go.
I am writing this from my phone so writing code here is a pain. Sorry for that. Just wanted to help you out quickly after seing you comment on my another answer. Will check this thread first thing in the morning to make sure if you need more help.
I am trying to achieve something when i click the button. The button is loaded from the server using an AJAX call. However, nothing happens when the button is clicked. Here is my code:
(This ajax call is in JS Fiddle -- only for testing purposes)
JS Fiddle
Code:
<div id="target"></div>
new Request.HTML({
url: '/echo/html/',
data: {
html: "<div id='0001'>"+"<h5 class='title'>Hello World</h5>"+"<h4 class='date'>2014-07-19</h4>"+"<button> Add to Calendar </button>"+"</div>",
delay: 0
},
method: 'post',
update: 'target'
}).send();
$("button").click(function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
Since the button does not yet exist you can use jQuery.on to delegate an event handler.
$("body").on('click', 'button', function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
Also your fiddle does not work since you are using both jQuery and MooTools but only loading MooTools.
Added after seeing authors page:
The var value = $(this).siblings(".title").text(); selector will not work. I would recommend adding an event class (as in calendar event) to the wrapper and using:
var value = $(this).parents(".event").find(".title").text();
If you are adding elements to the DOM via AJAX (or any other method) and you want listeners to remain bound to them, then you need to attach those listeners to elements in the document that don't change - like $(document).
e.g.
$(document).on('click','button',function(e) {
//your code here
});
The problem with your code is that you're getting all the buttons by doing $("button") and then attaching click listeners to them. The problem is that when you're doing this, your button hasn't been attached to the document and, therefore, will not have a click listener attached to it.
If button doesn't exist on page load. You can;t use $("button") to address it. You have to surround it by something else(div for example) and do it like this:
$('div').on('click','button', function(){...})
There are 2 things you need to consider.
ONE - jQuery that is included with mootools.
I was surprised that $ function in mootools version that you are using gave me a very BASIC jQuery function. I tried higher versions of mootools and still the same happened. I am sure it is not jQuery at all and mootools is just using $ variable for their purpose. [Optional: So, you may also consider defining jQuery as a different variable in your script.]
So, I added a link to latest jQuery in External Resources on jsfiddle and then it worked. Do not forget to expand External Resources on left on jsfiddle. But, if mootools is using $ for its own purpose, then jQuery will surely overwrite it. Please consider using jQuery as a different variable than $.
TWO - Use the onSuccess function of AJAX request.
You call the AJAX request and so you have to wait for some time for browser to load it which depends on user's internet connection. So, this is why we use onError and onSuccess events. Write the button function in onSuccess because button does not exist on document until AJAX is loaded.
Please check this code and it works.
http://jsfiddle.net/U7ewu/
Code:
new Request.HTML({
url: '/echo/html/',
data: {
html: "<div id='0001'>"+"<h5 class='title'>Hello World</h5>"+"<h4 class='date'>2014-07-19</h4>"+"<button> Add to Calendar </button>"+"</div>",
delay: 0
},
method: 'post',
update: 'target',
onSuccess: function() {
$("button").click(function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
}
}).send();
EDIT:
Please use $.noConflict(); so that mootools and jquery do not conflict each other on $ variable. $ is already being used by mootols, so please use the word jQuery instead.
Please check this jsfiddle.
http://jsfiddle.net/wkMep/
Code:
$.noConflict();
new Request.HTML({
url: '/echo/html/',
data: {
html: "<div id='0001'>"+"<h5 class='title'>Hello World</h5>"+"<h4 class='date'>2014-07-19</h4>"+"<button> Add to Calendar </button>"+"</div>",
delay: 0
},
method: 'post',
update: 'target',
onSuccess: function() {
jQuery("button").click(function(){
var value = jQuery(this).siblings(".title").text();
value += jQuery(this).siblings(".date").text();
alert(value);
});
}
}).send();
try this
$("button").on("click",function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
I have a page that display some data. It is loaded from a database using php and mysql, I use zend framework to handle all this.
On this page I have two things that use jquery. one is a paginator and the other is a thumps up function.
the paginator works fine. It receives the data as json and applys it to the view. all the functions that I need to handle this are located in one js file. In this file I listen for clicks...
$(document).ready(function() {
$("a#next").click(getProgramms);
$("a#previous").click(getProgramms);
$("a#page").each(function() {
$(this).click(getProgramms);
});
});
Now I have a problem with the thumps up function. It is located in another js file. Everytime the thumbs up button is clicked the script should just alert "click". actually when you click before you use the paginator a "click" appears, but when you do it after nothing happens. but the html in the dom inspector appears to be the same.
in my thumpsup.js I just have
$(document).ready(function() {
$("a.tp").click(thumpsUp);
});
function thumpsUp() {
alert("click");
}
I do not know where the problem is. maybe the js files are interferring each other!?
function thumpsUp() {
var url = window.location.hostname + '/programme/thumpsup/id/'
+ $(this).attr('page');
$.post(url, {
"format" : "json"
}, function(data) {
alert(data);
}, 'html');
return false;
}
I'm guessing the paginator is rewriting your elements and they are losing their click event binding. Try using live() for event binding instead:
$(document).ready(function() {
$("a.tp").live('click',thumpsUp);
});
function thumpsUp() {
alert("click");
}
You might have the Script files (which are included in your mark up) the wrong way round. That's the only solution I can think of...
I'm pretty sure you can get away with two $(document).ready()'s (even if it is frowned upon).
My site has a form which insert records in a database using ajax, at the same time, it "refreshes" a table also using AJAX in the same page showing this new record.
So I have the JS code
// New Record Div
$('button[type=submit]').click(function() {
// Read all the form content
var creditor = $('#selCreditor').val();
var reason = $('#txtReason').val();
var value = $('#txtValue').val();
var debtor = $('#selDebtor').val();
$.ajax({
type: 'POST',
url: 'index/insert/creditor/'+creditor+'/reason/'+reason+'/value/'+value+'/debtor/'+debtor,
success: function() {
$('#status').slideDown();
$('#latestRecords').fadeOut();
$.ajax({
type: 'POST',
url: 'index/latest',
success: function(html) {
$('#latestRecords').fadeIn();
$('#latestRecords').html(html);
}
});
}
});
return false;
});
Basically, it inserts a new record in the database, then on success, it requests a page which contains only the table and populate the div with the returned data. It's sort of a refresh when the data is submitted. Everything is done using AJAX.
I've uploaded the situation image for a better understanding. image
The Problem
Everything goes fine until you try to delete a "refreshed" table row. Without the AJAX (only press F5) I can delete any row I want through the delete button, but when I insert a row and the try to delete any row in the table won't do. This is the Delete button code
// TR Fading when deleted
$('.delete').click(function() {
$.ajax({
type: 'POST',
url: 'history/delete/id/'+$(this).attr('id')
});
$(this).closest('tr').fadeOut('slow', function() { $(this).remove(); });
$('#latest')
return false;
});
I suspect that the problem is $(this) which not refers to the delete button element once the table is refreshed, but I don't know how to fix it.
If the entire table is being reloaded then .click() wont work as it will have lost the elements it was applied to. Try using .live() instead.
e.g.
$('.delete').live('click',function(){...});
Also assign $(this) to a variable and use the variable instead, it can help make the code a bit clearer I think. e.g. var $deleteButton = $(this);
take a look at jquerys live, i think this is what you're looking for.
In addition to Nalums anwser, Who stated that you can use .live() — which will work even if you add dynamic elements through jQuery — you should instead use for most occasions the newer .delegate() (version added: 1.4.2)
Could be used in this fashion:
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
Or check out api.jquery.com/delegate/ for more information.