How should I bind my form to an AJAX call? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi below is my html and javascrpt which is having two text boxes and one submit button and I am getting the form values and storing the values in variable and appending to a url. Now my requirement is to execute the Url but my below code is opening the url, is there any way to execute the url without opening it.
<HTML>
<HEAD>
<script type="text/javascript">
function validate()
{
var name = document.getElementById("name").value;
var value = document.getElementById("value").value;
var url ="http://example.net.net/ftp/Ftp? name="+ name+"&value="+value;
window.open(url);
}
</script>
</HEAD>
<BODY>
<form name="Form1" method="post" action="" onsubmit="return validate();">
<input type="text" size="15" id="name" value=""/>
<input type="text" size="15" id="value" value=""/>
<input type ="submit" value ="submit" >
</form>
</BODY>
</HTML>
I have tried window.location =url; also bt not able to execute it, please suggest me.
Thanks

It seems like you want to do a GET request.
I would use AJAX for this:
$.ajax({
type: 'GET',
url: '/my/url',
success: function(jqXhr) {
console.log(jqXhr.responseText);
},
error: function() {
}
})
If you're not comfortable with JQuery you could do this (IE8+):
request = new XMLHttpRequest
request.open('GET', '/my/url', true)
request.send()
request.onload = function() {
console.log(this.response);
}
request.onerror = function() {
}

I think you are trying to open a url in new window right?
Try window.open
window.open(url,'_blank');

Related

Is there a way to check how long a website takes to load with javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
For my Science Fair project I need to be able to find out how long a website takes to load every 10 seconds. The issue is I'm not sure how to load the website and check how long it takes to load. So far I've made a program that just tells you what you typed in a text box, all I need now is just how to check the website's load time.
-Thank you in advance
Here is the code
<html>
<body id='body'>
<p>Website Checker</p>
<textarea id='websiteurl' rows="1" cols="50"></textarea><br>
<button onclick="checkhowlongittakes()">Input!</button>
</body>
</html>
<style>
#body {
background-color: coral;
}
</style>
<script>
document.getElementById('websiteurl').value = 'Input the url here'
function checkhowlongittakes() {
weburl = document.getElementById('websiteurl').value
//Checkhowlongthewebsitetakestoload(weburl)
}
</script>
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime);
}
If you are using Google Chrome then click F12 then a window pops-up. On that click network and refresh your page. you will get loading time of your each component on page including javascript.
To get a ping time for other websites:
function checkhowlongittakes() {
weburl = document.getElementById('websiteurl').value;
getLoadTime(weburl, function(time) {
console.log("load time for " + weburl + " was " + time + " ms");
});
}
function getLoadTime(url, callback) {
var req = new XMLHttpRequest();
var start = Date.now();
req.onreadystatechange = function(e) {
if (this.readyState == 4)
callback(Date.now() - start);
}
req.open("GET", url);
req.send();
}
<p>Website Checker</p>
<textarea id='websiteurl' rows="1" cols="50" placeholder="http(s)://">https://stacksnippets.net</textarea><br>
<button onclick="checkhowlongittakes()">Input!</button>

Post "url-from' in a form

I want to know from which url a form is send. I've tried this, but the result is 'orgUrl' instead of the url where the form is send from.
Anyone an idea what's wrong with this code?
<input type="hidden" name="url" value=orgUrl>
<script>
$(document).ready(function(){
var orgUrl = window.location.href;
});
</script>
You're trying to mix javascript with normal html which is not possible.
So you need to set the value also by javascript after getting the current url like this
<input type="hidden" id="url" name="url" value>
<script>
$(document).ready(function(){
var orgUrl = window.location.href;
$("#url").val(orgUrl );
});
</script>

insert input to form using javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
iam trying to post a file to database,i first created an empty form and then tried to add input using javascript,but i dont know how to link the newly created input to form and then submit hence the php shows no result.
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<title>image upload</title>
<script>
function sub()
{
var form=document.getElementById('nform');
var fil1 = document.createElement("input");
fil1.setAttribute("type","file");
fil1.setAttribute("name", "image1");
fil1.setAttribute("value", document.getElementById('one1').value);
form.submit();
return
}
</script>
</head>
<body>
<form id="nform" action="http://mydomainname.net/somepost.php"method="post">
</form>
<input type='file' id="one1"/>
<input type="button" onclick="sub();" value="Submit">
</body>
</html>
PHP code:
<?php
$con = mysql_connect("mydomainname.net","489583788","39853953");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("489583788", $con);
echo $_FILES["image1"]["name"];
echo $_FILES["image2"]["name"];
echo $_FILES["image3"]["name"];
?>
Your input is out side of the form element, it wont be passed to action page. So you need to append it to the form and then submit. Use Node.appendChild().
function sub(){
var form=document.getElementById('nform');
var fil1 = document.createElement("input");
fil1.setAttribute("type","file");
fil1.setAttribute("name", "image1");
fil1.setAttribute("value", document.getElementById('one1').value);
fil1.setAttribute("style","display:none;");
form.appendChild(fil1);
form.submit();
return
}

POST JSON to Jersey Service

I am trying to post some json data to REST web service implemented with Jersey framework. I am not using JAXB or jquery but only javascript.
I verified that formed json is correct but in spite of setting content type "application/json", on server it is received as "application/x-www-form-urlencoded".
Here is my code:
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = {};
var elem = document.getElementById('frmMain').elements;
//alert(elem.length);
for(var i = 0; i < elem.length-1; i++)
{
str[elem[i].name] = elem[i].value;
}
document.getElementById('lblValues').innerHTML = str;
var json = JSON.stringify(str);
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(document.getElementById('frmMain').method,
document.getElementById('frmMain').action);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-Length",json.length);
xhr.setRequestHeader('Accept', 'application/json');
//alert(json);
// send the collected data as JSON
xhr.send(json);
xhr.onloadend = function() {
// done
}
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain" action="/JerseyTest/rest/postUser"
method="post">
<input name="firstName" value="harry" /> <input name="lastName"
value="tester" /> <input name="toEmail" value="testtest#test.com" />
<br /> <input type="submit" value="Test"
onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
On the server side:
package com.example.jersey.test;
import javax.ws.rs.*;
#Path("/postUser")
public class JsonTest {
#POST
#Consumes("application/json")
#Produces(MediaType.TEXT_PLAIN)
public String pingPong(String json) {
return "Answer is "+ json;
}
}
I am new to web development and not sure on what I am missing in above code.
I am answering my own question for those who may visit this later. The code above is correct and works well except the fact that the url is been hit twice. First time, for submit button's default action and then as per our script by XMLHttpRequest.
This I came to know after I checked the headers in Httpfox which showed error as NS_BINDING_ABORTED.
After changing the input type to button from submit, all is working fine.

Hidden form file POST in javascript

Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.

Categories

Resources