Javascript function doesn't trigger - javascript

$("tbody").on('click', '#update', function () {
$("#UpdateModal").modal("show");
var id = $(this).data("id");
console.log(id);
$.ajax({
type: 'Get',
url: "/Users/GetUser?id=" + id,
data: {
"cusid": id
},
success: function (response) {
console.log(response);
console.log(response.data.userName);
var departments = #Html.Raw(Json.Serialize(#ViewBag.departments));
var duties = #Html.Raw(Json.Serialize(#ViewBag.duties));
var roles = #Html.Raw(Json.Serialize(#ViewBag.roles));
$('#UpdateModal #Id').attr('value', response.data.id);
$('#UpdateModal #UserName').attr('value', response.data.userName);
$('#UpdateModal #FirstName').attr('value', response.data.firstName);
$('#UpdateModal #LastName').attr('value', response.data.lastName);
$('#UpdateModal #Password').attr('value', response.data.password);
$("#UpdateModal #DepartmentId option:first-child").prop("selected", "selected").text(response.data.departmentName);
$("#UpdateModal #DutyId option:first-child").prop("selected", "selected").text(response.data.dutyName);
$("#UpdateModal #RoleId option:first-child").prop("selected", "selected").text(response.data.roleName);
if (response.data.isActive) {
$("#UpdateModal #IsActive #true").prop("selected", "true")
console.log(response.data.isActive);
}
else {
$("#UpdateModal #IsActive #false").prop("selected", "false")
console.log(response.data.isActive);
}
for (var i = 0; i < departments.length; i++) {
if (response.data.departmentName == departments[i].departmentName) { $("#UpdateModal #DepartmentId option:first-child").prop("selected", "selected").val(departments[i].id); }
}
for (var i = 0; i < duties.length; i++) {
if (response.data.dutyName == duties[i].dutyName) {
$("#UpdateModal #DutyId option:first-child").prop("selected", "selected").val(duties[i].id);
}
}
for (var i = 0; i < roles.length; i++) {
if (response.data.roleName == roles[i].roleName) { $("#UpdateModal #RoleId option:first-child").prop("selected", "selected").text(response.data.roleName).val(roles[i].id); }
}
}
});
});
What I want to do here is to pull the data into my update modal with API. But it can't do it. Actually it was working before but suddenly the code stopped working. Can anyone see the error?
What do I need to do for this function to work? It gets triggered when I use the same code in another view. But it never gets triggered here. Please help.

There could be multiple reasons why this code is not working. Here are a few possible solutions:
1 - Check if the target element (#update) exists in the DOM when the click event handler is attached to it. If the element is dynamically generated, you may need to use event delegation, as follows:
$("tbody").on('click', '#update', function() {}
2 - Verify if the AJAX request is being sent and if the server is returning a valid response. You can use the browser's network tab or your browser's developer tools to see the network requests and the responses.
3 - Check the values of id, departments, duties, and roles in the console. They should have valid values.
4 - Ensure that the selectors used in the code are correct and that they match the actual HTML structure. You can use your browser's developer tools to inspect the elements and see if the selectors match the elements.
5 - Make sure that the jQuery library is loaded correctly and that there are no errors in the console.

Related

Ajax events error when sending multiple http request

when i'm try to get data for some html element from a website by ajax i added some events like xhr.onloadstart,xhr.onloadend to show the loader element before sending the request and adding the data after finishing the response and hide the loader
the problem is when i try to click on multiple elements after each other it's just stop working just display the load for some html elements and not given any data and that's happening just when i try to click on 3 or 4 element after each other directly - and when i click normally and wait for load it's working without any problems -- i don't know if the problem is with my code or the problem in ajax like it's cannot handle many requests at the same time ... Please anyone help me
i was working with jquery ajax and changed to the XMLHttpRequest() and the problem still the same
Here's my code
for(let q = 0; q < elem.length; q++) {
elem[q].addEventListener("click",function() {
let url = $(this).find(".elem").attr("href");
let _this = this;
let $this = $(this);
var xh = new XMLHttpRequest();
xh.onloadstart = function(bubbles) {
_this.getElementsByClassName("loader")[0].style.display = 'block';
}
xh.onreadystatechange = function(change) {
_this.getElementsByClassName("loader")[0].style.display = 'none';
}
xh.onloadend = function(data) {
console.log(data)
//result dom object
console.log($(data.currentTarget.responseText)[71].getElementsByClassName("row").length)
if($(data.currentTarget.responseText)[71].getElementsByClassName("row").length > 0) {
let row = $(data.currentTarget.responseText)[71].getElementsByClassName("row")[0].getElementsByClassName("row")[0];
let select_color = $(row).find("#container #color_select_options").attr("class","ElemData");
$this.append(select_color[0]);
//when user click again delete appended element and keep the first one
if($this.find(".ElemData").length > 1) {
for(o = 1; o < $this.find(".ElemData").length; o++) {
_this.getElementsByClassName("ElemData")[o].remove()
}
}
}
})
}

javascript confirm dialog keeps appearing sometimes

Hello I'm using confirm dialog to ensure a user action. But the confirm dialog keeps appearing again and again while I don't see in my code anything which is triggering this. Is it a bug? or am I doing something wrong?
$('#table_trans tbody').on('click', 'tr td button', function() {
var trans_id = $($(this).parents(':eq(1)')[0].childNodes[0]).html();
var r = confirm("Sure!");
if (r == true) {
$.ajax({
url: '?r=transactions/ajaxdelete',
data: {
id: trans_id
},
success: function(response) {
$.notify(response, "error");
}
});
$($(this).parents(':eq(1)')).remove();
} else {
alert("Action Cancelled!");
}
});
One more thing to add, It happens only sometimes that the Javascript confirm dialog keeps appearing. sometimes it behaves correctly, sometimes it appears twice, but sometimes infinitely.
UPDATE
As suggested by Parag Bhayani, Here is the javascript that adds a row to the table #table_trans
// msg is a json response received by making an ajax call
for (var i = 0, l = msg.length; i < l; i++) {
var rowz = "<tr><td>" + msg[i].id +"</td><td>"+msg[i].account_no+"</td><td>" + msg[i].date_of_transac +"</td><td>"+msg[i].description+"</td><td>"+msg[i].amount+"</td><td><button id=\"delete_trans\">Delete</button></td><tr>";
tbl_html = tbl_html + rowz;
}
// sorry for the discomfiture .... but please scroll to extreme right to see the button, clicking which is triggering the event.
This could be happen only if your event is registered multiple times, so one case for that could be causing this issue is that, event registeration code is in loop then your event might have registered n number of times.

Multiple chrome.webNavigation.onHistoryStateUpdated not working

The goal of this is to have my extension wait for a change in the History, depending on what it says, do a certain action.
Here is what I have so far
popup.js
chrome.tabs.update({ url: "https://www.WEBSITE.com/messages" });
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
if (details.url.indexOf("messages") >= 0) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'getInboxStats.js'
});;
} else {//if (details.url.indexOf("match") >= 0) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'startBotting.js'
});;
}
});
chrome.runtime.onMessage.addListener(function(message) {
if (message.type == "emptyAmount") {
emptyAmount = message.content;
if (!(percentageOfMessages > 0)) {
percentageOfMessages = 50;
}
amountToSend = Math.floor(emptyAmount * (percentageOfMessages / 100));
alert(amountToSend);
chrome.tabs.update({ url: "https://www.WEBSITE.com/match" });
}
});
getInboxStats.js
var currentAmount = document.getElementsByClassName('count')[1].innerHTML;
var maxAmount = document.getElementsByClassName('total')[0].innerHTML;
var emptyAmount = maxAmount - currentAmount;
chrome.runtime.sendMessage({ content: emptyAmount, type: "emptyAmount" });
startBotting.js
alert("TEST");
The issue I have is that the getInboxStats.js starts, but it's like the onHistoryStateUpdated only seems to work once because the file startBotting.js never displays an alert that says 'TEST'
You misunderstand the purpose of onHistoryStateUpdated.
It captures the instances of history state manipulation without navigation via History API as opposed to regular navigation. When you call update({url: "..."}) it's a regular navigation.
If you're really concerned about browser history updates, you should be using chrome.history.onVisited.
If you want to use webNavigation API to capture regular navigations, you should use onCommitted event.
You should also look into chrome.tabs API.

Clicking links with WebdriverIO

I have a web page that I am trying to test via Webdriver I/O. My question is, how do I click a couple of links via a test? Currently, I have the following:
var webdriverio = require('webdriverio');
var client = webdriverio.remote(settings).init()
.url('http://www.example.com')
.elements('a')
.then(function(links) {
for (var i=0; i<links.value.length; i++) {
console.log('Clicking link...');
var link = links.value[i].ELEMENT;
link.click().then(function(result) {
console.log('Link clicked!');
});
}
})
;
When the above gets executed, I get an error that says "click is not a function" on link. When I print link to the console, it looks like JSON, which would make sense since the documentation says that the elements function returns WebElement JSON objects. Still, I'm just trying to figure out how to click this link.
How does one do such?
Thanks!
You need elementIdClick
http://webdriver.io/api/protocol/elementIdClick.html
Here is an example
var settings = {
desiredCapabilities: {
browserName: 'firefox',
},
};
var webdriverio = require('webdriverio');
var client = webdriverio.remote(settings).init()
.url('http://www.example.com')
.elements('a')
.then(function(links) {
for (var i=0; i<links.value.length; i++) {
console.log('Clicking link...');
var link = links.value[i].ELEMENT;
client.elementIdClick(link).then(function(result) {
console.log('Link clicked!');
});
}
});
Result of the above code will be
Clicking link...
Link clicked!
Hello there you could do directly this though:
it clicks all elements a on the page
var client = webdriverio.remote(settings).init()
.url('http://www.example.com')
.click('a')
.end()
);
you could you a selector to target specific a elements
example:
.click("article .search-result .abstract .more")

How would you cycle through each image and check it for an error in a casperjs script?

How would you cycle through every image on a given page and check to see if it was loaded or errored out?
The following are not seeming to work in the phantomjs/casperjs setup yet cycling through and grabbing the src is working.
.load()
and
.error()
If the above does work, could someone show a proper usage that would work in a casperjs script?
The code I used looked similar to the following:
var call_to_page = this.evaluate(function() {
var fail_amount = 0;
var pass_amount = 0;
var pass_img_src = [];
var fail_img_src = [];
var img_src = [];
$("img").each(function(){
$(this).load(function(){
pass_amount++;
pass_img_src.push($(this).attr("src"));
}).error(function(){
fail_amount++;
fail_img_src.push($(this).attr("src"));
});
img_src.push($(this).attr("src"));
});
return [img_src, fail_amount, fail_img_src, pass_amount, pass_img_src];
});
Any help as to why the above code doesnt work for me would be great. The page is properly being arrived upon and I am able to mess with the dom, just not .load or .error. Im thinking its due to the images being done loaded, so Im still looking for alternatives.
CasperJS provides the resourceExists function which can be used to check if a particular ressource was loaded. The ressource is passed into a function, so custom constraints can be raised.
casper.then(function(){
var fail_amount = 0;
var pass_amount = 0;
var pass_img_src = [];
var fail_img_src = [];
var elements = this.getElementsInfo("img");
elements.forEach(function(img){
if (img && img.attributes && casper.resourceExists(function(resource){
return resource.url.match(img.attributes.src) &&
resource.status >= 200 &&
resource.status < 400;
})) {
pass_amount++;
pass_img_src.push(img.attributes.src);
} else {
fail_amount++;
fail_img_src.push(img.attributes.src);
}
});
this.echo(JSON.stringify([fail_amount, fail_img_src, pass_amount, pass_img_src], undefined, 4));
});
This can be done after the page is loaded. So there is no need to preemptively add some code into the page context.
In turn, the problem with you code may be that the callbacks never fire because the images are already loaded of already timed out. So there is no new information.
If you're not sure what kind of errors are counted, you can use a custom resources detection for all available types or errors.
var resources = []; // a resource contains at least 'url', 'status'
casper.on("resource.received", function(resource){
if (resource.stage == "end") {
if (resource.status < 200 || resource.status >= 400) {
resource.errorCode = resource.status;
resource.errorString = resource.statusText;
}
resources.push(resource);
}
});
casper.on("resource.timeout", function(request){
request.status = -1;
resources.push(request);
});
casper.on("resource.error", function(resourceError){
resourceError.status = -2;
resources.push(resourceError);
});
function resourceExists(url){
return resources.filter(function(res){
return res.url.indexOf(url) !== -1;
}).length > 0;
}
casper.start(url, function(){
var elements = this.getElementsInfo("img");
elements.forEach(function(img){
if (img && img.attributes && resourceExists(img.attributes.src) && !resourceExists(img.attributes.src).errorCode) {
// pass
} else {
// fail
}
});
});
I don't have much experience with caperjs, in my observation I identified below points
Note:
jQuery .load( handler ) and .error( handler ) both were deprecated from verson 1.8.
If you're using jQuery 1.8+ then attaching load and error events to img(tags) does nothing.
jQuery Ajax module also has a method named $.load() is shortcut form of $.get(). Which one is fired depends on the set of arguments passed.
Here are Caveats of the load event when used with images from jQuery Docs
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
So if you've version 1.8+ of jQuery the below block does nothing.
$(this).load(function(){
pass_amount++;
pass_img_src.push($(this).attr("src"));
}).error(function(){
fail_amount++;
fail_img_src.push($(this).attr("src"));
});
As a result this return [img_src, fail_amount, fail_img_src, pass_amount, pass_img_src]; statement will give us only img_src[with number of imgs as length] array filled with srcs of imgs in page. and other elements fail_amount, fail_img_src, pass_amount, pass_img_src will have same defaults all the time.
In the case of jQuery 1.8 below load and error events attachment with jQuery were meaningful(in your case these events were attached after they were loaded on page, so they won't show any effect with load and error callbacks), but the time where we attach events matters. We should attach these before the img tags or place the events in tag level(as attributes onload & onerror) and definitions of function handlers script should keep before any img tag or in very beginning of the body or in head
There're ways to figure out some are here:
use open-source plug-in like (Use imagesLoaded](https://github.com/desandro/imagesloaded)
Can use ajax call to find out whether the img.src.url were good or not?
Dimension based check like below function IsImageRendered
below I've but its old one not sure the browser support at this time. i recommend to go with above plug in if you can use it
var call_to_page = this.evaluate(function () {
function isImageRendered(img) {
// with 'naturalWidth' and 'naturalHeight' to get true size of the image.
// before we tried width>0 && height>0
if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
return false;
}
//good
return true;
}
var pass_img_src = [];
var fail_img_src = [];
var img_src = [];
$("img").each(function () {
var $img = $(this), $srcUrl = $img.attr("src");
img_src.push($srcUrl);
if (!$srcUrl)
fail_img_src.push($srcUrl);
else {
if (isImageRendered($img.get(0))) {
pass_img_src.push($srcUrl);
}
else {
fail_img_src.push($srcUrl);
}
}
});
var fail_count = fail_img_src.length,
pass_count = pass_img_src.length;
return [img_src, fail_count, fail_img_src, pass_count, pass_img_src];
});

Categories