Assign value to id in html link with javascript - javascript

I have the following link that passes an id to my controller to render a report.
Print Report
I would like to assign this value id in the link above to the result I have returned from the database in the call below....
// Global variable
var DocumentID = null;
$('#Save').click(function(e) {
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
url: "/Home/SaveDetails",
dataType: "json",
type: "POST",
data: ko.toJSON(viewModel),
contentType: "application/json;charset=utf-8",
success: function(result) {
if (result > 0) {
//Assign return value to DocumentID
DocumentID = result;
alert("This work request has been successfully saved in database. The Document ID is: " + result);
} else {
alert("The Work Request was not saved, there was an issue.");
}
},
complete: function() {
// Hide loading image.
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle error.
alert(errorThrown);
}
});
} else {
alert("Form is not valid");
}
});
The call above works and returns a DocumentID and displays this in an alert with success. The link above works if the id has a hard-coded value; I would just like to make this value dynamic.

if (result > 0) {
//Assign return value to DocumentID
var DocumentID = result;
var href = '#Url.Action("GetReport", new { type = "PDF", id =' + DocumentID +'})';
$("a:contain('Print Report')").attr('href', href);
}

The above suggestions will generate an error for an unsupported pseudo, in this case 'contain' which is not available or known to the anchor tag. There is also an error with the syntax of putting the DocumentID in the Url.Action. I was not able to get this to work, instead I found another error: Too many characters in literal.
Instead give your anchor an id and find that id using jQuery and replace it's href attribute, this is done in the second line of code under Javascript.
html:
<a href="#" **id="Report"**>Print Report</a>
Javascript:
var DocumentID = result; var href = '#Url.Action("GetReport")?type="PDF"&id=' + DocumentID + '';
$("#Report").attr('href', href);
Take note of two things. The URL is formed and the anchor tag is found differently versus previous suggestions.
This has been tested and works for parameters of type string and int, respectively in your callback function to handle getting the report. If you want two strings then add an additional double-quote around the DocumentID like this: id=" ' + DocumentID + ' "';

in your ajax-success handler just set the href of the anchor to whatever you want
var newHref = '#Url.Action("GetReport", new { type = "PDF", id = '+DocumentID +'})';
$('a').attr('href',newHref);

Related

How to target span by class name and get ID then pass ID in Ajax?

I am trying to get id of a span in a dropdown which has classname and id is dynamic but classname is always fixed so I tried this document.querySelector(".tag").id and this is working when I select the span from dropdown but when I did not select anything from dropdown my ajax gives an error main.js:357 Uncaught TypeError: Cannot read properties of null (reading 'id') which is clearly for this, How will I pass this span id so that if I select or not it should be pass in ajax?
why is it happening?
update:
I have tried this
const element = document.querySelector(".tag");
if (element) {
jourid = element.id + "_" + $("#tags_input").val();
} else {
jourid = " ";
}
but now it says jourid not define if I am not selecting the value ! how will i resolve this ?
<span id="249257" class="tag"><span>Test</span>x</span>
$(function () {
var frm = $("#saveform");
frm.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: {
PubId: $("#Publications").val(),
sdate: $("#datepicker").val(),
jour:document.querySelector(".tag").id,
pnumber: $("#pnumber").val(),
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
alert( "Saved!");
window.location.reload();
},
});
});
});
How will I pass the id of span so that there will be successful ajax call whether value is empty or not?
The error is occuring because the document.querySelector was not able to find any span elements.
You only need to add a check on whether the query return any element before accessing id field of it.
something like this:
frm.submit(function (ev) {
ev.preventDefault();
// this will set `undefined` to id if the span element is not obtained
var id = document.querySelector(".tag")?.id;
// now you can error check here and return if needed
// if(!id) return;
//or set id as empty
if(!id) id = " ";
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: {
// ...,
jour: id,
// ...
},
...
});
}
as for the jourid not defined, you just need to write let jourid; before using the variable in if statment, like so
let jourid;
if (element) {
jourid = element.id + "_" + $("#tags_input").val();
} else {
jourid = " ";
}

Splitting multiple elements and sending via ajax

I'm trying to map every element that has a contenteditable attribute in order to send the results with each individual element's value being sent. However, I am running into a problem when I try to use comma's inside a field because I am joining the elements then splitting them to get an array of values.
Here is my code:
function getProfileData(element, button) {
var profile_data = $(element).html();
var data = $(element).blur(function() {
profile_data = $(element).map(function() {
return this.innerHTML;
}).get();
});
$(button).on('click', function() {
var edited_content = profile_data.join(", ");
var split = edited_content.split(",");
$.ajax({
method : "POST",
url : "/members/profile/create-profile",
data : {
display_name : split[0],
email_address : split[1],
age : split[2],
location : split[3],
bio : split[4]
},
}).done(function() {
alert("Profile saved!");
location.href = '/members/profile';
}).fail(function() {
alert("Error saving profile, please try again");
});
});
}
Is there any way to not having a comma inside a field cut off the rest of the text after it?
Thanks!

How to get the facebook user id to another javascript file after login?

I understand that I can get the facebook id by doing:
FB.api('/me', function(response) {
alert('Your id is ' + response.id);
});
However, I want to have the user login and then grab that id in a different file so I can handle it. Right now I have:
var id = "";
var fburl = "http://graph.facebook.com/" + id + "?callback=?"
$(function(){
$("#fb-profile-picture")[0].src = "http://graph.facebook.com/" + id +"/picture";
$.getJSON(fburl, function(data){
console.log(data);
$("#name").append(data.name);
$("#user-id").append(data.id);
});
});
and if I manually enter the id in the id var it works however I'd like to be able to grab that response.idas the value and use it in this other javascript file but I haven't figured out how to.
Assuming you
cannot control which of the scripts is executed first
you are working in an environment with a global window object
part one is only executed once
you are using jQuery
making a global and firing an event might be a solution, although not considered best practice.
Script 1:
FB.api('/me', function(response) {
window.fbCustomId = response.id;
console.log(window.fbCustomId);
$(window).trigger('fbResponseLoaded');
});
Script 2:
function renderProfile() {
var fburl = "//graph.facebook.com/" + window.fbCustomId + "?callback=?"
$(function () {
$("#fb-profile-picture")[0].src = "//graph.facebook.com/" + window.fbCustomId + "/picture";
$.getJSON(fburl, function (data) {
console.log(data, window.fbCustomId);
$("#name").append( $('<span>').text(data.name) );
$("#user-id").append( $('<span>').text(data.id) );
});
});
}
if (window.fbCustomId) {
renderProfile();
} else {
$(window).on('fbResponseLoaded', renderProfile);
}

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.

Javascript / JQuery loop through posted ajax data string to assign new values to

I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'&para1='+ para1 +
'&para2=' + para2+
'&para3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}

Categories

Resources