Getting value to append to url with javascript - javascript

I'm working on updating some code that someone else initially wrote. I found out they are passing a value to the url onClick, which redirects to the url and allows me to get the value with $_GET. They use a function to handle this process. I have a need to change the redirect url, but keep the rest of the process the same. I copied their function, changed the name, and changed the redirect url. For some reason, it's not passing the value and I can't access it through GET
Here is their code, which still works on my system:
function lab_popup2(id)
{
// alert(id);
jQuery('#lab_popup').fadeIn();
var param = RU+'includes/earningdetail2.php?id='+id;
jQuery('#lab_popup_ifram').attr({'src':param});
var v = jQuery('#lab_popup_ifram').html();
jQuery('#consult_popup_ifram').html(v);
jQuery('#lab_popup_ifram').fadeIn();
}
I pass this function the value like this:
<a href="#" onClick="lab_popup2('test');">
The new code that I'm trying to create is below. You'll see the only difference is where it redirects, so I'm not sure why it wouldn't pass the value this time. I did a var dump on GET to make sure, and there was nothing.
function lab_popup_emails_completed(id)
{
//alert(id);
jQuery('#lab_popup').fadeIn();
var param = RU+'includes/earningdetail4.php?id='+id;
jQuery('#lab_popup_ifram').attr({'src':param});
var v = jQuery('#lab_popup_ifram').html();
jQuery('#consult_popup_ifram').html(v);
jQuery('#lab_popup_ifram').fadeIn();
}
Once again, I use this code to send a value to the function:
<a href="#" onClick="lab_popup_emails_completed('completedpaid');">
Since the way I call the function is identical, and the functions themselves are the same except the redirect, I just don't see why the first example works and the second doesn't.

Related

How to make consecutive API calls in JavaScript with variables [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 9 months ago.
Sorry if this is kind of a "noob" question but I'll ask anyway. :)
I have a HTML page and a JavaScript file where I make two API calls to get train trip information.
You are filling out the city you want to travel from and the first API call returns an ID for that location.
The the second API call is supposed to use this received ID to get you up to six upcoming departures from that location to a preset destination.
The first API call works with the variable cityname being passed from the input field from the HTML page and in the log I get an ID number back. That is shown in the console logs. Unfortunately I'm not allowed to provide a picture (too low reputation :)).
The second API call always fails since the variable trainoriginid always ends up empty (I guess that this is actually a variable scope issue). I have tried to use the same technique on the second API call as in the first call, as you can see in the commented "var url" line, but no matter where I try to declare or set the trainoriginid it ends up empty. How am I to pass the result from the first API call to the second? All info is appreciated.
This line is from the error message:
GEThttps://api.resrobot.se/v2.1/trip?format=json&originId=&destId=740098037&passlist=true&showPassingPoints=true&accessId
If I use the call with the "const url" line everything works so there you can see what the url should look like.
The (not complete) JavaScript code looks like this:
let reqBtn = document.querySelector('.request-btn');
let reqInput = document.querySelector('.request-input');
let respResultDiv = document.querySelector('.response-result');
let trainoriginid = '';
reqBtn.addEventListener('click', event => {
let cityName = reqInput.value;
console.log(cityName);
var citylookup = `https://api.resrobot.se/v2.1/location.name?input=${cityName}&format=json&accessId=[APIKey]`;
axios.get(citylookup).then(searchresponse => {
console.log(searchresponse.data);
let searchdata = searchresponse.data;
trainoriginid = searchdata.stopLocationOrCoordLocation[0].StopLocation.extId;
console.log(trainoriginid);
});
//var url = `https://api.resrobot.se/v2.1/trip?format=json&originId=${trainoriginid}&destId=740098037&passlist=true&showPassingPoints=true&accessId=[APIKey]`;
const url = `https://api.resrobot.se/v2.1/trip?format=json&originId=740000008&destId=740098037&passlist=true&showPassingPoints=true&accessId=[APIKey]`
axios.get(url).then(response => {
console.log(response.data.Trip);
let data = response.data.Trip;
NOTE!
After following the link above and and doing some testing - using callbacks solved my problem. Just for reference the final solution looks like this:
reqBtn.addEventListener('click', event => {
let cityName = reqInput.value;
respResultDiv.textContent = '';
console.log(cityName);
getStationId(cityName, getTrainList)
});
function getStationId(cityNameinput, callback){
var citylookup = `https://api.resrobot.se/v2.1/location.name?input=${cityNameinput}&format=json&accessId=[API-key]`;
var originid;
axios.get(citylookup).then(searchresponse => {
console.log(searchresponse.data);
let searchdata = searchresponse.data;
originid = searchdata.stopLocationOrCoordLocation[0].StopLocation.extId;
console.log(originid);
callback(originid);
});
}
function getTrainList(trainoriginid){
console.log(trainoriginid);
var url = `https://api.resrobot.se/v2.1/trip?format=json&originId=${trainoriginid}&destId=740098037&passlist=true&showPassingPoints=true&accessId=[API-key]`;
axios.get(url).then(response => {
console.log(response.data.Trip);
let data = response.data.Trip;
[Do a bunch of stuff with the result here]
});
}
In your example above, your second lookup call needs to be inside the "then" response method of the first lookup. You are calling both inline at the same time, so the second call will always use the empty "trainoriginid" as it is not set yet. Also, in your example above, I can not see you actually applying "${trainoriginid}" to the second url.
In this case, you do not need to make the second url a "const" as it is a one use deal. It is probably best to use "let" (and apply the "${trainoriginid}").
As a side note, axios is awaitable, so you could use await on the first call (and make the click method async), then you could have both lookups inline like that, but it is probably easier to just move the second call inside the the response of the first.

setting a variable in javascript to be used in another form

I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};

How to use the Firebase real time database for web application

In my website I'm Showing my database after user has given the database name, Is there any way I can constantly update the web shown databasebase without refreshing the page . I've tried using setInterval but it's not working for some reason .
function c(){
setInterval(beta, 1000);
}
function beta(){
var d = document.getElementById("opopo").value;
var firebaseRefff= firebase.database().ref('LOCATION/'+d);
firebaseRefff.on('child_added', snap=> {
var slot=snap.getKey();
var alloted=snap.child("ALLOTED").val();
var date=snap.child("DATE").val();
var limit=snap.child("LIMIT").val();
var time=snap.child("TIME").val();
$("table tbody").append(""+slot+""+alloted+""+date+""+limit+""+time+"Null");
});
}
You do not need, and should not use, setInterval to trigger the queries. What you have in your beta() function looks pretty good.
firebaseRefff.on('child_added', snap => {}) means "whenever a child is added under this location, trigger the callback function (empty in my example) with the parameter 'snap'". It will also be called once, initially, for each child that is already at that database reference location.
You need to make sure you've called beta() once to setup this trigger.
If you're still having problems, you might want to insert logging to make sure beta() is being called, what the full reference path is, if the callback is ever triggered, and if your jquery string is correct.

Executing a jquery function stored as a variable name

I'm struggling with figuring out how to call/execute a function in jQuery. I've done quite a bit of searching and find what looks like it should be the answer, but it doesn't seem to work. I assume it is a scope issue since everything else seems to match examples I've found here, but I'm relatively new to jQuery and can't quite figure it out.
Basically, when the "bookmark" button is clicked, it uses ajax to create an entry in the database, and changes the format of the clicked button. This acts as expected. The trick is this requires someone to be logged in. The actual click of the button adds a #bookmarkme anchor to the url - if they aren't logged in (this is where things start getting tricky for me), the log in window pops up and they are prompted to sign up/log in, and the page reloads to set all the log in variables properly. This also works as expected. Where it breaks down is once the user logs in and the page reloads, I can't get the "bookmarkFunction" to run.
<script type="text/javascript">
var loggedin = <?php echo $loggedin; ?>;
var headerButtonScript = function(){
var bookmarkFunction = $("#bookmark").click(function(){
var directoryName = "<?php echo $directoryName;?>";
if(loggedin == 1 && $("#bookmark").hasClass("headerButton")){
$.ajax({
type: "POST",
url: "../includes/bookmarkProcess.php",
data: {directory: directoryName},
success: function(data, status){
if(data == "success"){
$("#bookmark").switchClass("headerButton", "headerButtonDisabled", 1000, "easeInOutQuart");
$("#bookmark").text("Bookmarked");
}
}
});
}
else{
$("#signInContent").toggleClass('hidden');
$("#signInPopUp").toggleClass('hidden');
}
});
};
var headerButtonsAfterLoad = function(){
var currentAddress = window.location.href;
var hashPosition = currentAddress.indexOf("#");
var targetLocation = currentAddress.substring(hashPosition+1);
if(targetLocation == "bookmarkme"){
if(loggedin==1){
//CALL bookmarkFunction HERE;
//I know I get to this location when expected, because placing an alert("message") gives me the pop up
}
}
};
$(document).ready(headerButtonScript);
$(window).bind('load',"",headerButtonsAfterLoad);
</script>
Based on my research, I have tried the following lines (one line attempted each time rather than all at once, of course) in the excerpt to try to call the function, but no luck yet.
if(targetLocation == "bookmarkme"){
if(loggedin==1){
//CALL bookmarkFunction HERE;
bookmarkFunction();
bookmarkFunction.run();
bookmarkFunction.call();
bookmarkFunction.apply();
}
}
Any help on locating my issue - scope, methods, or otherwise - is greatly appreciated!
"I need the script to take the same action it would when I click on the bookmark button (ID = bookmark) when the page reloads and has the anchor #bookmarkme"
This will do what you want^
$('#bookmarkme').trigger('click');
$("#bookmark").click(). should work.
Remember, calling a jQuery method on a jQuery object returns the original jQuery object. So if you say:
var bookmark=$('#bookmark')
Then bookmark is set to the jQuery object (which contains the element of id=bookmark as a property).
If you attach methods to the object like this:
var bookmark=$('#bookmark').click(function(){console.log('You clicked!')})
Then, yes, the element with id bookmark will now call this event when you click it, but the click method on a jquery object returns the original jquery object. That means bookmark will still be equal to $("#bookmark"), not the function in the click method.
So in conclusion, when you attach an event to a jquery object, like click or hover, it goes into the dom and attaches the event, and then returns the original jquery object. That way you can do things like:
var bookmark=$("#bookmark").click(function(){console.log("you clicked")}).mouseover(function(){console.log("you moused over")})
And you can keep attaching events forever and ever, and bookmark will always be equal to $("#bookmark")

Variable not updating in script string, yet it updates

Very confused here.
I have a search box which reads a list of school names from my database. When I select a school, the id (from the db) gets put in a hidden textbox.
I also have a search box which reads a list of courses from my database. However, I made the query so that it only reads the courses from the selected school.
It does that, in theory.
I was planning to pass the school id, which I grab from the hidden box, to the search script which in turn passes it to my database query. However, the variable I put my school id in doesn't seem to be updating.. yet it does. Let me explain.
I come on the page. The school for my test account has id 1. The id number in my hidden box is indeed 1. I search for a school which I know has some courses assigned to it: the id number in the box changes to 3.
I have a JS variable called school_id which I declared outside of my $(document).ready. I assume that means it's global (that's what I got taught even though SO told me once it isn't really the correct way to do this. Still have to look into that). I wrote a function which updates this variable when the school search box loses focus:
$("#school").blur(function() {
school_id = $("#school_id").val();
});
A quick javascript:alert(school_id); in my browser bar also shows the updated variable: it is now 3 instead of 1.
Onto the search script part of my page (excerpt of the script):
script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&"
As you can see, I pass the school_id variable to the script here. However, what seems to be happening is that it always passes '1', the default variable when the page loads. It simply ignores the updated variable. Does this string get parsed when the page loads? In other words, as soon as the page loads, does it actually say &id=1? That's the only idea I can come up with why it would always pass '1'.
Is there a way to make this variable update in my script string? Or what would be the best way to solve this? I'm probably missing out on something very simple here again, as usual. Thanks a lot.
EDIT
Updated per request. I added a function getTheString as was suggest and I use the value of this function to get the URL. Still doesn't work though, it still seems to be concatenating before I get a chance to update the var. HOWEVER, with this code, my ajax log says id:[object HTMLInputElement], instead of id:1. Not sure what that means.
<script type="text/javascript">
var school_id;
$(document).ready(function() {
$("#school").blur(function() {
school_id = $("#school_id").val();
});
// zoekfunctie
var scholen = {
script:"/profiel/search_school?json=true&limit=6&",
varname:"input",
json:true,
shownoresults:false,
maxresults:6,
callback: function (obj) { document.getElementById('school_id').value = obj.id; }
};
var as_json = new bsn.AutoSuggest('school', scholen);
var richtingen = {
script: getTheString(),
varname:"input",
json:true,
shownoresults:true,
maxresults:6
};
var as_json2 = new bsn.AutoSuggest('studierichting', richtingen);
});
function getTheString() {
return "/profiel/search_richting?json=true&limit=6&id=" + school_id + "&";
}
</script>
This is because the URL is static, it is not updated as the ID changes.
You should update the URL as part of the code you wrote to get the ID:
$("#school").blur(function() {
school_id = $("#school_id").val();
// update URL here ...
});
Aren't you concatenating script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&" before the event is fired and the var updated?
Okay. So the problem was my third party plug-in instead of the code I wrote. I fixed this by editing the code of the autoSuggest plugin so it now includes my id field in the AJAX request.
var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp)+"&id="+ $("#school_id").val();
Thanks to everyone who tried to help me out!

Categories