jQuery doesnt invoke alert box - javascript

I have the following:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.getJSON(
"/myServer/getAllWidgets",
function(data) {
var optionsHTML = "<select id='widget-sel'>";
optionsHTML += "<option selected='selected' id='default'>Select an option</option>";
var len = data.length;
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i] + '">'
+ data[i] + '</option>';
}
optionsHTML += "</select>";
$('#widget-sel-div').html(optionsHTML);
}
);
$("#widget-sel").change(function() {
alert("Hello!");
});
});
</script>
<div id="widget-sel-div"></div>
So, the idea is that when document.ready fires, it populates the widget-sel-div with a select box (widget-sel) and then creates a change handler for that select that simply prints "Hello!" to the screen via alertbox.
When I run this, I get no errors (Firebug doesn't complain at all) and the select gets populated with all my widgets from the AJAX call to /myServer/getAllWidgets. The problem is, the change handler isn't working: when I select a widget I don't get the alertbox. Can anybody spot where I'm going awrye? Thanks in advance.

At the time the code runs, the #widget-sel element doesn't exist in the DOM, because you add it in the callback to getJSON (which is asynchronous). You can't bind an event handler to it when it doesn't exist yet.
To get around this, you can delegate the event handler higher up the DOM tree (looks like you can use the parent div in this case) with the .on() method (jQuery 1.7+, if you're using an older version, use .delegate() instead):
$("#widget-sel-div").on("change", "#widget-sel", function () {
alert("Hello!");
});

This is due to the asynchronous nature of the AJAX call. The change handler will be executed before the AJAX call has completed and therefore there will be no element in the DOM for it to bind to. Instead, place the change in the AJAX call back:
$.getJSON(
"/myServer/getAllWidgets",
function(data) {
var optionsHTML = "<select id='widget-sel'>";
optionsHTML += "<option selected='selected' id='default'>Select an option</option>";
var len = data.length;
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i] + '">' + data[i] + '</option>';
}
optionsHTML += "</select>";
$('#widget-sel-div').html(optionsHTML);
$("#widget-sel").change(function() {
alert("Hello!");
}
}
);
Or alternatively you can leave the change handler where it is and delegate the event listener to a static parent element like this:
$('#widget-sel-div').on('change', '#widget-sel', function() {
alert("Hello!");
});

Related

Jquery append after ajax not working every time

I have a problem with jquery append. This is the code:
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
This code work very well, but not every time. (only the append option not working. This: console.log(string_option) it`s ok every time).
Can you help me, please?
Thank you!!
Looks like you need to put the code to be executed after the document is fully loaded using the "$( document ).ready" jQuery event
$( document ).ready(function() {
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
});
You can learn more about this on the below link
https://api.jquery.com/ready/
Try to check the response on Ajax success sometimes it happens due to malformed JSON is sent back with a 200/OK
One possible problem could be that you run the .append() before DOM is loaded. If this is the problem you can try 2 methods:
put this javascript code inside footer.
add to your code:
$(document).ready(function(){
//... your ajax request
})

Load script or CDN after ajax call

I'm trying to run this ajax method for multi select drop down:-
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
},
async: false
When i use the static multi select drop down on the html it works without red box, image shown as below :-
And which is not working is shown in red box:-
These scripts i'm using :-
<link href="~/css/jquery.multiselect.css" rel="stylesheet" />
<script src="~/js/jquery.multiselect.js"></script>
<script src="/js/jquery.min.js"> </script>
The issue as i see is that in case of dynamic my scripts runs before page load and thus this dynamic ajax don't show drop down,but in case of static multi select drop down it works because this drop down is before the page loads and thus the script runs over it how do i run ajax before page call or before these scripts run.
Just call your .selectMultiple event function in your ajax success method after inserting your select tag in DOM
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
$('#langOpt3').selectMultiple(
//your code
);
}

Getting my Search Form to Trigger JQuery Ajax request

I've set up an Ajax request to the Ebay API using Jquery, which works while I have a search term/keyword hardcoded, but I cannot figure out how to write the code to make my (bootstrap) button trigger the Ajax request using the search form input. I've tried various things to no avail. I'm completely new to this and this is my first time making an Ajax request and using JQuery so hopefully this makes sense.
Jquery:
$(document).ready(function() {
url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=rare soul 45"; //This would get deleted?
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I'm a bit surprised you managed to get an ajax request running but you struggle with registering a click event handler. :) but here we go...
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
// get the input value with:
var searchstring = $('input[type="text"]', this).val();
// your ajax request, using the variable above
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
It looks like you are making that ajax call upon document ready which is not really what you want. You want to make that call upon a button press event. So I would do this.
Put that ajax call into a function that you can call
Give the button an id
On document ready, use jquery to attach an event handler to the element with the id in step 2 above that triggers a call to your function mentioned in step 1 above.
Then, don't forget to extract the value in the field from the event and place it into the called ajax function as a parameter.
Given your current HTML, you can call a click event on your submit button like this...
$('button[type="submit"]).on('click', function(event) {
/*
since the button is of type "submit",
prevent the default behavior. Which,
in this case, is to submit the form.
*/
event.preventDefault();
//Check your browser's console to see what this is
console.dir(event);
//insert AJAX code here
});
This code uses the jQuery .on() method to capture the given event, 'click', on a given element $('button[type="submit"]'). Once this event has been captured, you can access it as event, or name of your choice, within the function.
This event object contains information regarding the event itself. It can be quite daunting at first, but I encourage you to look through a console.dir(event); call. More specifically, e.currentTarget/e.target, and view to get a sense of what is going on. From there you can look into what the difference is between some things that seem the same and get as familiar with it as you'd like.

Difficulty calling JavaScript function on click after dynamically generating table

I'm having difficulty making a clickable button in my dynamically generated table that would send data specific to the table cell that was clicked.
My table is generated and modified whenever the user types into the search box with this AJAX call:
$(document).ready(function(){
$("#data").keyup(function () {
$.ajax({
type: "POST",
dataType: "JSON",
data: "data=" + $("#data").val(),
url: "search1.php",
success: function(msg){
var output = "";
for(var i = 0; i < msg.length; i++) {
output += '<tr onmouseover=this.style.backgroundColor="#ffff66"; onmouseout=this.style.backgroundColor="#F0F0F0";>';
output += '<td>';
if (msg[i].website != ''){ output += '' + msg[i].name + '</td>';}
else output += msg[i].name + '</td>';
output += '<td class="description">' + msg[i].description + '</td>';
output += '<td><input type="button" onclick=' + submit() + ' value=' + msg[i].id + '></td></tr>'; // Here is where I'd like to put in a clickable button
}
$("#content").html(output);
$("#myTable").trigger("update");
}
});
});
});
If I make submit() simply alert("hello") it runs when the page is loaded for every instance of the onclick call to submit(). Could someone please explain to me how to make submit only get called when its button is clicked and not on page load. Thanks in advance.
You have to put the submit() call in a quoted string. Same goes for the msg[i].id. All values in HTML should be quoted.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
You are trying to assign submit() to the button's onclick, but you are actually calling the function when you generate the string output. It needs to be in quotes inside the string, not concatenated in.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
//----------------------------------------^^^^^^^^^^^^
A better strategy would be to leave out the onclick attribute entirely, and use jQuery's .on() to dynamically assign the method. It is often considered a better practice to bind events dynamically rather than hard-code them into HTML attributes.
// No onclick attribute in the string:
output += '<td><input type="button" value="' + msg[i].id + '"></td></tr>';
// And a call to .on() in the $(document).ready()
$('input[value="'+msg[i]+'"]').on('click', function() {
submit();
});

Make a <td> rendered by Javascript clickable

I'm quite new to webdevelopment and AJAX and I'm facing a little issue there. Basically, I have a form on my webpage. When I submit this form, it makes an AJAX call to my controller, send me the data I want back, and change the html content of the page.
JS code :
$(document).ready(function() {
$("#mydiv table tbody td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$('#myform').submit(function()
{
try {
var host = $("#host").val();
var port = $("#port").val();
var username = $("#username").val();
var password = $("#password").val();
var database = $("#database").val();
$.ajax({
type: "POST",
url: "/management/connectDatabase",
dataType: "JSON",
data: "host="+host+"&port="+port+"&username="+username+"&password="+password+"&database="+database,
cache: false,
success:
function(data){
$('#mydiv').html(show_tables(data));
},
});
return false;
}
catch(e){
console.debug(e);
}
});
});
function show_tables(data)
{
var html = '<div id="mydiv">';
html += '<table class="display" id="example">';
html += '<thead><tr><th>Tables</th></tr></thead><tbody>';
for (var tablesCount = 0; tablesCount < data.tables.length; tablesCount++){
html += '<tr class=gradeA id="trtest">';
html += '<td id="tdtest">' + data.tables[tablesCount] + '</td>';
html += '</tr>';
}
html += '</tbody></table>';
html += '</div>';
return html;
}
When I submit the form, the HTML is generating right, and I can see my content. But, I can't click on any entries of the <table>. Moreover, when I want to see the sourcecode of my page, it doesn't displays me the table, but still my form, even if it has still been validated.
Could someone explain me what I do wrong here ?
Depending on which jQuery version you're using, you need to either bind the click event using jQuery.delegate or jQuery.on in order for things to work with dynamically added DOM elements.
Edit: as pointed out by Geert Jaminon, you have to use the selector parameter of the on function. This works for me.
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() + "My TR is:" + $(this).parent("tr").html());
});
.live() is replaced by .on() in the newer jQuery versions.
http://jsfiddle.net/ZqYgv/
you need to bind the click event handler after the rendering of the elements, since they weren't in place when you made the binding.
If you insert data dynamically, you need to add the click event after the data has been inserted.
http://codepen.io/thomassnielsen/pen/FEKDg
$.post('ajax/test.html', function(data) {
$('.result').html(data);
// Add .click code here
});

Categories