How to access an URL from a function in HTML/Javascript? - javascript

So I started to learn HTML and JavaScript not long ago and I wonder how I could access an URL/download a file from a function I made with JavaScript in another file and imported it with
<script src="jscriptSheet.js"></script>
Maybe I am wording the search badly but I didn't found anything that helps me. The only thing I saw, was doing a form and sending it to a server, but that's not what I need (I think).
What I'm doing is creating 2 dates that need to be passed to the URL so it can access the file and download it:
<div class="dateWrapper">
<p id="date1">Date1:</p>
<input id="date1INPUT" type="date">
<p id="date2">Date2:</p>
<input id="date2INPUT" type="date">
<br><br>
<button id="datesubmit" type="submit" onclick="downloadF()">Download file.</button>
</div>
And the function made with JavaScript:
function downloadF{
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
}
When I execute this, it downloads nothing, it's just a normal button with no action.
How can I do it?

You do not want type=submit if you want to do something else than submitting. INSTEAD use a button as below or attach to the submit handler of the form and use preventDefault if you do not want to submit
I use location= you can use window.open(url) too but that may be blocked
Also your function should be
function functionname() { ... }
Anyway here is an example
document.getElementById("datesubmit").addEventListener("click",function {
location="100.100.100.100/something/something.php"+
"?date1="+document.getElementById("date1INPUT").value+
"&date2="+document.getElementById("date2INPUT").value
})
<div class="dateWrapper">
<p id="date1">Date1:</p>
<input id="date1INPUT" type="date">
<p id="date2">Date2:</p>
<input id="date2INPUT" type="date">
<br><br>
<button id="datesubmit" type="button">Download file.</button>
</div>
If you set the header in the PHP you will see a download dialog
header("Content-type: application/octet-stream");

Welcome to stackoverflow!
As already mentioned in a comment, you don't want to have the type set to "submit" when the button should not really submit the inputs but call a custom javascript function. Instead you just want to have the type set to "button".
Moreover you should define your javascript function like this (watch out for the parentheses):
function downloadF(){
// Access your input fields here
}
For accessing DOM elements you might want to have a look here at w3schools

function downloadF{
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
}
this is having invalid syntax. The JavaScript function should be defined like ( Very basically),
var f1 = function(){
}
function f2(){
}
And,
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
Here you are inserting something like date1 & data2 But it's not exist in your function. You can't use undefined variables.
And if you skip all syntax errors and look at the command
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
you are just setting a variable href and you didn't do any actions.
First learn basic javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript
And the answer of your question is,
If the target file is directly downloadable, you can use window.open('the_target_url') inside function.
If not,
You should do something in PHP. Please refer this link Download file from PHP

Related

How can I retrieve an HTML form value and put it in a JavaScript object?

so I'm kind of a beginner at JavaScript and APIs, things like that. I want to implement an API into my website that can detect whether an article is fake news or not based on the title. I already found the API, which is this, but I'm a bit confused with how to retrieve the form value from my HTML code, shown below:
<input type="text" name="check" id="check">
<button onClick="checkFakeNews" id="btn">Check</button>
<p id="result"></p>
I already tried typing up this function:
function checkFakeNews() {
document.getElementById('check') = text
console.log(text)
}
to try to print out the value, but I didn't get anything.
I also want to get the result, stored in 'data' in the API I believe, and display it in the paragraph. I'd be very grateful to anyone who can help me!
Firstly, You are you writing document.getElementById('check') = text which doesn't do anything.
Second thing that in HTML onClick need to be equal to Function Call you are passing just the Name. You need checkFakeNews() instead of checkFakeNews
This should work as required.
function checkFakeNews() {
const input = document.getElementById('check');
const text = check.value;
console.log(text);
}
<input type="text" name="check" id="check">
<button onClick="checkFakeNews()" id="btn">Check</button>
<p id="result"></p>
https://www.javatpoint.com/document-getElementById()-method , and see https://www.w3schools.com/jsref/prop_text_value.asp
var s = document.getElementById("element").innerHTML; //to set
document.getElementById("myText").value = "Johnny Bravo"; to set

(VB) Passing a textbox value with a Url.Action via javascript

In VB, I am working on an MVC project. I have a text box to enter some search criteria, and a button next to it that upon pressing will submit the value of the text box. Html Snippet:
<input type="text" id="mySearchField" />
<button onclick="location.href='#Url.Action("Search", "Movies", New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'">Search</button>
My question revolves around the final part:
New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'"
The code above does not work or compile, but this is my general idea of what I am attemping to do.
I want to pass the value of the text box along into the Movies/Search function, however I am at a loss as to how to format the line to mix the html, asp, and javascript all at once.
My VB Function for clarity:
Function Search(searchCriteria As String) As ActionResult
Return View()
End Function
Any advice is much appreciated!
This should be pretty close. This has jQuery as a prerequisite. To make this maintainable (you can do this, or not), I'd use NewtonSoft.Json to serialize the URL to Javascript properly, and url-encode the text box value.
<input type="text" id="mySearchField" />
<button id=myButton>Search</button>
<script>
var url = '#Html.Raw(Url.Action("Search", "Movies"))';
$("#myButton").click(function(){
location.href = url + '?searchCriteria=' + $("#mySearchField").val()
});
</script>

auto update the html dom for all the users whenever there's change

I am sorry for asking such a noob question. But I saw a video very long time ago and I think it was a framework based on jquery, where if a user makes some CRUD changes to an object, the object's properties are auto updated not only for 1 user, but on all the other users browser. I am trying to find it but I am all lost! I would really really appreciate if you could help me out. Thank you!
Lets say you have a html form that looks like this
<form>
<input type="text" name="firstName" value="Jackson" />
<input type="text" name="lastName" value="Rivera" />
<textarea name="lifestory">
When i was 2yo, spot died...
</textarea>
</form>
simply add an OnChange event on every element you want to dynamicly change:
<form>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<textarea onchange="shareValueWithOthers(this.name, this.innerHTML)">
When i was 2yo, spot died...
</textarea>
</form>
Notice that a change of the elements value (or in the case of the textarea - it's contents) causes the function shareValueWithOthers(this.name, this.value) starts to run. this.name is the variable for the name, this.value is the variable for the value, this.innerHTML is the variable for the contents.
Now you have to write a Javascript function so you can send the changes to the server. Look into AJAX. Make a function that sends a POST request to your PHP script.
Your PHP script should save all the values either in a database, or in JSON-format in a file on the server. JSON is the easiest. Look into JSON PHP PARSER.
Last but not least. If you do the right thing, and make sure that every new value that a user enters gets updated in your json file by your PHP script. You can make the last step. which is to make a javascript function that retrieves the JSON file. JSON stand for JavaScript Object Notation, so your javascript can use this right away.
What you will do next, is to change all the values in your DOM that look different from the values in your retrieved JSON object.
two type of protocol, Websocket or WebRTC.
socket.io is Websocket very popular and easy.
gevent-socketio for python
Plenty base on node.js. sailsjs, deployd, meteor

Assign a input value to variable on same page with Jquery

I am working with a api where i need to post a url from a form and get response. Everything is working well except one thing. I could not figure out how to get url posted in form input in to a variable for javascript. Take a look at following.
<form action="#" method="post">
<input type="text" class="url" name="url" />
<input type="submit" value="Analyse for Page Speed" value="submit" />
</form>
I use above form to get url and i want that url to be a value for the following variable
// Specify the URL you want PageSpeed results for here:
var URL_TO_GET_RESULTS_FOR = 'your url here';
How to get this done?
Is this what you're looking for?
var URL_TO_GET_RESULTS_FOR = document.getElementsByName('url')[0].value;
getElementsByName returns an array with all elements having the name passed as parameter. Since I'm assuming you have only one element with name="url", I get the first position of the array and returns the value.
As #crush pointed out in the comments, this task alone probably does not merit the use of jQuery. So if you aren't already using it, this should probably not be the deciding factor. If you need a pure JS solution, go with #ClaudioRedi's answer.
However, I'm assuming you're already using jQuery, and are asking for a jQuery solution. So here it is:
var URL_TO_GET_RESULTS_FOR = $('form input[name="url"]').val();
This will get the value of an <input> with the name url within a <form> element.

Why do two forms appear?

I am using jQuery and bootstrap to give drop-down search suggestions.Following is the html code.But when I type something in the search form and then clear the form.Two forms apears as in the picture.Why? I am new to jQuery. Thanks for any help.
<div class="container">
<div class="row">
<div class="span6 offset3">
<form class="form-search">
<input type="text" id="month" name="month" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
<div id="suggestions">
</div>
</form>
</div>
</div>
</div>
<script>
jQuery("#month").keyup(function(){
ajax('search', ['month'], 'suggestions')});
</script>
EDIT:
I am using web2py framwork.This is the search function's code:
def search():
if not request.vars.month: return dict()
month_start = request.vars.month
selected=complete('piracyfinder',month_start) #this line get the search results
return DIV(*[DIV(k['title'],
_onclick="jQuery('#month').val('%s')" % k['title'],
_onmouseover="this.style.backgroundColor='lightblue'",
_onmouseout="this.style.backgroundColor='white'"
) for k in selected])
It appears you are using the same function (i.e., search()) to fill in the suggestions as well as to create the form (though that function doesn't process the form when submitted). According to the logic, when request.vars.month is either empty or does not exist, the function returns an empty dict. This will result in the associated view (i.e., /views/[controller name]/search.html) being executed and returned. Presumably the search.html view contains the HTML code shown above. So, when you clear the input box, the keyup handler is triggered and sends an empty month variable, which results in a new copy of the form being sent back and inserted in the "suggestions" div. You can avoid this problem by checking whether request.vars.month exists:
if not request.vars.month:
return '' if 'month' in request.vars else dict()
A better approach might simply be to use different functions for the search form and the suggestions given that they do completely different things and don't share any code.
if not request.vars.month also applies to the month var existing but being empty. Therefore, it's returning the form.
You need to do one of these:
Have your "suggestions" code be in a different page/file
Add a isAJAX variable to the request (or some other way to identify AJAX requests)
Check if the variable exists, rather than checking if it is falsy.

Categories