XMLHttpRequest() after submit from form - javascript

I'm new to Javascript, can I use XMLHttpRequest() after I hit submit from form but the result should be the same as onclick event. I have a function named get and by using XMLHttpRequest() I can add a new object within the div sample, it works if it's a button. The only difference is that I want to add new object to the div sample without redirecting to http://127.0.0.1:5000/get?query=apple after I submit the form, form and function get() should be working together in this case. And also I don't want to see the http://127.0.0.1:5000/get?query=apple in the browser's url field after I submit the form. I need some help, I push myself to use pure js as possible and not to rely on jquery.
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form action="/get" method="GET">
<input name="query">
<input type="submit">
</form>
<script>
function get(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
</script>

This is how you can interrupt submit event, and do whatever you want.
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form id="form">
<input name="query">
<input type="submit" value="Submit">
</form>
<script>
document.querySelector('#form').addEventListener('submit', function(e){
e.preventDefault();
var query = e.target.elements['query'].value;
get(query);
});
function get(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
</script>

function get(query) {
console.log("Called Function");
query = document.getElementById('query').value;
console.log(query);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form id="myForm" action="/get" method="POST">
<input type="text" name="query" id="query">
<input type="button" onclick="get()" value="Submit form">
</form>
You have user Form type method="GET" which changed to method="POST" and added onclick="get()" to call the function from javaScript

Related

AJAX send to php controller not working in javascript

The snippet shows my html and js. In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz
UPDATE: I added some code to make sure the send request is complete. However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request. I still can't get any js data into php. I could create hidden inputs and fill those in from js and the submit but that seems ugly. can someone help?
function swagSend() {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var henry = "henry"
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("zzz=" + henry);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("myForm").submit();
}
}
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>
<input type='text' name='myname'>
<button type='submit' value='submit' onClick=swagSend();>Submit</button>
</form>
If you are making an Ajax call, there is no reason to submit the form. remove it.
If you want the form data to be submitted in the Ajax call, you need to read the form input values and build up the list yourself.
function swagSend(event) {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var henry = "henry"
var name = encodeURIComponent(document.getElementById("myname").value)
xhttp.send("zzz=" + henry + '&myname=' + name);
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>
<input type='text' name='myname' id='myname'>
<button type='submit' value='submit' onClick="swagSend(event)">Submit</button>
</form>
you should only send with xhttp.send and not additionally with document.getElementById("myForm").submit();

Html code in body executes after script runs

I'm new in Javascript and i'm trying to make an http request to fetch some data and display the results in html. I'm fetching the results and update the html code, but then the html code inside body reloads and shows the default values. My code is,
<head>
<script>
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.onreadystatechange = processRequest;
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
// populate here results array
// i change the value with the following line
document.getElementById("title_1").innerText = "fetched_value";
}
}
}
</script>
</head>
<body>
<div class="search_btn">
<form id="search_form" method="get" onSubmit="return httpGetAsync()">
<input type="text" class="search" placeholder="Search" id="search">
<input type="submit" value="search" class="search_button">
</form>
</div>
<div id="one">
<p id="title_1">default</p>
</div>
</body>
The 'title_1' changes its text to 'fetched_value' but it then reloads and becomes 'default' again. What am i doing wrong?
It's because your onSubmit does not receive false. Simply add return false to httpGetAsync end
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener(
"readystatechange",
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("title_1").innerText = "fetched_value";
}
},
false);
xhr.onreadystatechange = processRequest;
return false;
}
You need to prevent the default action on submit, which is to use the "action" attribute on the form element to reload the page (if it's not present the current page is reloaded).
function httpGetAsync(event) {
event.preventDefault();
...
}

Keyup Event in case of dot CO & COM url Shorten

I'd love to know if there is a possibility to add a trigger ("KEY EVENT"ׁׂׂ) to avoid sending the request twice.
The problem is if we start typing in the URL field the domain http://www.example.com.. The AJAX will trigger on "http://www.example.co" and then again when you add the last letter.
There are an option to avoid that or give the user few second to finish to write the full domain?
<html>
<head>
<script>
function isUrl(url){
var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
return regex.test(url);
}
function showHint(str) {
if (!isUrl(str)) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a url in the input field below:</b></p>
<form>
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>

call js function from form action then call php from js

We can call php directly from form action in html:
<form name='x' action = "filename.php">
in this case, php will receive all inputs in the form even we don't pass them.
Can we call js function from form action in html?
<form name='x' action = "javascript:jsFunction();">
Then, call the php from the js function?
jsFunction()
{ var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Hint
I cannot use onsubmit because it log me out from the platform. in other words, it reload the platform from the beginning of the login page.
I am working on integration and I don't have a clear idea about the platform.
Edit 1:
Now, in the HTML file:
<form enctype='multipart/form-data' id = "myform">
<input type='submit' value='Basic search' onclick = "i2b2.BLAST.jsFunction();">
JS file:
i2b2.BLAST.jsFunction = function ()
{
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", blastresult.php, true);
xhttp.send();
event.preventDefault();
});
}
it reloads the platform from the beginning of the login page!
Edit2:
I put some alert to see if the button call the javascript.
i2b2.BLAST.jsFunction = function ()
{
alert('hi');
this.yuiTabs = new YAHOO.widget.TabView("BLAST-TABS", {activeIndex:1});//this two lines navigate to second tab
this.yuiTabs.set('activeIndex', 1);
alert('hi');
myForm.addEventListener('submit', function()
{
alert('hi');
preventDefault();
The button call the js and display first 'hi' then navigate to second tab then reload the page. It stop at the second 'hi'.
Any help is highly appreciated.
Thanks.
Yes you can, First give your FORM an id
<form id="myForm"></form>
then in javascript try this:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
e.preventDefault();
});
Instead of:
<form name='x' action = "javascript:jsFunction();">
Use:
<form name='x' onsubmit="jsFunction();">
You can POST via AJAX as you have shown in your code:
function jsFunction(event) {
// prevent default event from taking place (submitting form to file)
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Though you will need to serialize your data and pass it to xhttp.send(), it will need to be form url encoded like: key1=value1&key2=value2. You are probably better off using jQuery in the manner #mmm suggests.

Ajax failed to load contents from php file

I am trying to display contents of a php file on my html page using ajax.
I have an html file with the following ajax code :
get_ajax.html
<form action="">
First name: <input type="text" id="txt1" onblur="show users(this.value)">
</form>
<p>Username: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = newXMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
user.php
<?php
echo $_GET["u"];?>
It doesn't display the username on my get_ajax.html page.
Is there something wrong with my code?
First check the existence of user.php and verify the proper path,by the way why don't use Jquery,it is easy and straight forward.
Here is an example using jquery :
var str = 'something';
$.get('user.php',{u:str},function(serverResponse){
$("#txtHint").html(serverResponse); //this should add the value something to the DOM
});
Appears you have type in your code as below
- onblur , you are making a call to "show users(this.value)"
- there is a space between "show" and "user" , even u correct the space , you dont have a function "showuser" anywhere.
- your function to make the ajax call is "showHint"
- next you need a space between "new" and "XMLHTTpRequest()"
<form action="">
First name: <input type="text" id="txt1" onblur="showHint(this.value)"/>
</form>
<p>Username: <span id="txtHint"></span></p>
</form>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>

Categories

Resources