Unable to change href value with JQuery - javascript

I am aware that this question has been asked before and I had the solution working last week based on the responses in the answers provided, nothing has changed and all of a sudden the jquery has stopped working.
I am using an Ajax call (below) that returns me a string that I assign to a hidden link on a page to force the download of a file from my works LAN.
$(document).ready(function () {
$(".excelLoader").hide();
$('.extract')
.on('click',
function () {
var rh = Number($(this.id).selector);
console.log("clicked: " + rh);
var loader = "load_" + rh;
var excel = "excel_" + rh;
console.log(loader);
$("." + excel).hide();
$("." + loader).show();
var params = {
responseHeaderId: rh
}
$.ajax({
type: "POST",
url: "SubmissionTracker.aspx/ExportFile",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#hiddenLink").attr("href", data.d);
console.log($("#hiddenLink").val());
$("#hiddenLink").click();
$("." + excel).show();
$("." + loader).hide();
},
error: function (data) {
console.log("error :" + data);
console.log(data);
$("." + excel).show();
$("." + loader).hide();
}
});
});
})
the issue that I have now is that the href is not being set, so the click event fires but with nothing to fetch.
The line I believe to be the issue is $("#hiddenLink").attr("href", data.d);
the line it is trying work with in my ASP.Net Webforms page is <a id="hiddenLink" href=""></a>.
I have cleared my Cache, removed any temporary files that may have existed but still cannot reproduce the positive results I had last week.
Any and all help bery much appreciated.
-----------update----------------
issue appears to be on the click event of the link. JQuery that I am usering is version jquery-1.11.3.js which is referenced first, and the js file where this is referenced is in the middle of all the other referenced files.

Related

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Checkbox jquery change function is not working and no errors

I have a list of items and I want to do something whenever one of the items is selected, but the problem is that the check-box's change function is not working with me.
I have checked the code inside the function and it's working fine outside the change event. i'm not sure of the reason why it's not working but what could it be other than the function its self ?
Here the change function:
$("input[name='checkCoResult']").change(function () {
if (this.checked) {
$("#searchResultSecond").attr("style", "opacity: 0.6");
$("#searchResultSecond *").attr("disabled", "disabled").off('click');
}
});
and this is the code that generate my list:
$.ajax({
url: "CCDMSWebService.asmx/getCoSearchResult",
data: JSON.stringify(objectData),
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Result = response.d;
contantDiv.text("");
$.each(Result, function (index, val) {
contantDiv.append('<div class="panel-bod"><label style="margin:2px; border-radius: 10px;border: 1px solid #cc0000;padding: 5px;"><input type="checkbox" value="' + val.companyID + '" name="checkCoResult" class="nnn"> '
+'<img src="images/' + val.companyID + '.png" alt="company logo" width="30%" height="30%">' + val.companyName + ' provides all your needs</label></div>');
})
},
failure: function (msg) {
alert(msg);
}
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). In your case it seems you already have a div named contantDiv present in your page, so modify your code like
contantDiv.on("change","input[name='checkCoResult']",function(){ ...
Check out http://api.jquery.com/on/#direct-and-delegated-events for more details.
if your content is dynamic then try
$(document).on("change","input[name='checkCoResult']",function(){
// your code
});

Issue filling select box via ajax call in Django

I am running into an issue creating cascading select boxes (backend Django-though I think this portion is mostly worked out). I have the following javascript code adapted from this stackoverflow response.
$(document).ready(function(){
$('select[name=experiment]').change(function(){
experiment_id = $(this).val();
request_url = '/admin/get_measurements/' + experiment_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(){
$('select[name=measurement_a]').append('<option value="' + this.key + '">' + this.value +'</option>');
// $('select[name=measurement_a]').append($("<option />").val(this.key).text(this.value))
});
},
return: false
})
})
});
In my project I select an experiment which triggers a call to "get_measurements" function and receive a list of "measurements" which should populate the measurement select box. Currently when I select the experiment I see the json response as expected:
{1: "MyFirstMeasurment", 2: "MySecondMeasurement"}
The measurement select box received 2 new selections however, both of them have the text "undefined" as opposed to "MyFirstMeasurement" and "MySecondMeasurement". I am guessing this is something simple in my code, Thank you for the help, let me know if you need more information.
It turns out I needed to do a couple of things to fix this, thanks for the help and hints. Here is the final code.
$(document).ready(function(){
$('select[name=experiment]').change(function(){
experiment_id = $(this).val();
request_url = '/admin/get_measurements/' + experiment_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(key, value){
$('select[name=measurement_a]').append("<option value='" + value + "'>" + value +</option>");
});
},
return: false
})
})
});

jQuery order of events - unable to figure out proper solution

I'm trying to create an if/else statement within my jQuery code that changes the ajax URL and success function that gets fired off:
if($($this.context).find('img').hasClass('scheduler-img')) {
url = window.location.origin + "/recipes/" + planned_recipe_id +'/update_recipe'
} else {
url = window.location.origin + "/recipes/" + recipe_id +'/make_recipe'
success = successfulRecipeAdd(closest_date, image_url, recipe_id);
}
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
data: {
planned_for: planned_for,
meal_type: meal_type
},
success: (function() {
success
}),
error: (function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
})
});
I'm using this for a jQuery draggable and sortable table, so when I'm dragging and dropping the first item, it doesn't work because it tries creating the 'success' variable with an empty dataset. However, it does work for every subsequent drag/drop after.
function successfulRecipeAdd(closest_date, image_url, recipe_id) {
$.get( window.location.origin + "/recipes/get_recipes", function(data) {
console.log(data);
var planned_recipe_id = $(data).last()[0][0].id;
$(closest_date).append("<img src='"+image_url+"'class='scheduler-img col-md-12' id='"+ recipe_id +"' data-planned-id='"+planned_recipe_id+"'>");
});
}
I'm having a lot of trouble figuring out a way to write this that would allow me to create variables within the if/else statement, then fire off the ajax call using variables, rather than having two ajax calls within the if/else statement.

Onclick function on div not working

I have a function for getting records from database on keyup event.
Here is my code:
function displaySearch(key) {
$.ajax({
type:"POST",
url:"searchprofile.php",
data:{
k:key
},
success:function(data){
var details_arr=data.split("+");
$('.searchresult').empty();
for(var i=0;i<details_arr.length-1;i++){
$('.searchresult').append("<div class='profile' id='searchprofile'><img class='profilepic' src='images/profile.jpg'/><div class='doctorname'><div class='pname' onclick='saveName("+details_arr[i]+")'>"+details_arr[i]+"</div></div></div>");
$('.searchresult').show();
$('.searchresult .profile').show();
}
details_arr.length=0;
}
});
}
But i am getting javascript error here saying "Unexpected token ILLEGAL".
How do i give the onclick function with the value of details_arr[i]?
Please help.
As you have jQuery, you really shouldn't inline code. As you see it makes it more difficult to handle quotes inside quoted strings (yes, you're missing quotes around your argument to saveName).
You may do this :
(function(i){
$('.searchresult').append(
"<div class='profile' id='searchprofile'>"
+ "<img class='profilepic' src='images/profile.jpg'/>"
+ "<div class='doctorname'>"
+ "<div id=someId class='pname'>"+details_arr[i] // <- give some Id
+"</div></div></div>"
);
$('#someId').click(function(){saveName(details_arr[i])});
})(i);
$('.searchresult').show();
Note that I used a closure to ensure that i has the needed value in the callback (not the value at end of iteration).
Be careful with the split: on most browsers "+aaa".split('+') makes ["", "aaa"] and as you don't iterate up to the end of the array, this sample string would made you iterate on nothing.
function openNow(x)
{
var pageUrl = '<%=ResolveUrl("~/OnFriends.php")%>'
$.ajax({
type: "POST",
url: pageUrl + '/CreateNew',
data: '{k: "'+ x +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(data)
{
<---Now Do Your Code Hear--->
}
});
}
CreateNew is my web service what i created in .php file
I would use something like that
bare in mind ID must be unique inside a document (HTML Page)
because the content is generated on the fly; it's better to use the JQuery "on"
$(".pname").on("click", function (event) {
saveName($(this).text());
});
event handler to bind the click event
function displaySearch(key){
$.ajax({
type: "POST",
url: "searchprofile.php",
data: {
k: key
},
success: function(data) {
var details_arr = data.split("+");
var searchResults = "";
for (var i = 0; i < details_arr.length - 1; i++) {
searchResults += "<div class='profile'>" +
"<img class='profilepic' src='images/profile.jpg'/>" +
"<div class='doctorname'>" +
"<div class='pname'>" + details_arr[i] +
"</div></div></div>";
}
$('.searchresult').html(searchResults).show();
}
});
}
$(".pname").on("click", function (event) {
saveName($(this).text());
});
use the Jquery html to replace everything inside searchresult outside the loop that way it
will be called once not details_arr.length - 1 times
you should tell the line at which you are getting error
i think you did not specified you web service in ajax call at...
"url:"searchprofile.php"
Finally got the onclick function working. :)
Instead of appending the div everytime, i just editted my php page by adding the html i needed in the data that is returned in ajax.

Categories

Resources