Hello i'm using this code. i have a problem in this. when i enter input in my input box, it is fine. but when i press enter the page is refreshing for a sec and the input box is auto clearing.
<script>
function book_suggestion() {
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
The reason your page is reloading is because <form> elements catch enter presses.
Catching an enter press will submit the form.
Submitting a form without an action="" attribute will submit to the same page.
Submitting to a page that doesn't handle the request will simply reload the page, and your form input will be reset to blank.
To fix this, disable submit-on-enter by using javascript to catch a keypress equal to 13 and return false or cancel the event.
<input type=text id=book onKeyUp="book_suggestion( event )">
... [snip] ...
function book_suggestion( e ){
if( e.which == 13 ){
e.preventDefault();
e.stopPropagation();
return false;
}
... [snip your code] ...
That should do the trick.
For what it's worth, people on Stack Overflow don't generally like to modify your code at your request. This is a simple fix that can be found by Googling for the keywords ("catch keypress", "cancel event", etc.).
If I understand you, you want to submit yourself form data. You should return false within book_suggestion() function. And add onsubmit to <form> element. Make sure it should have return. Like that:
<form onsubmit="return book_suggestion();">
Related
I'm using JavaScript keyup() event for a single text box.
If someone types “Windows”, it will send an HTTP request for every keyup:
“W”, “Wi”, “Win”, “Wind”, “Windo”, “Window”, “Windows”
This is the desired behaviour.
When the user clears the text box empty, it gives an error.
This is the undesired behaviour.
Question
How can I stop an HTTP request being sent when the text box is cleared?
You can use AJAX to send information to the server (and get information for that matter):
<?php
if (isset($_POST['search'])) {
echo json_encode($_POST);
die();
}
?>
<form>
<input id="search" type="text" name="search" />
</form>
<script>
document.getElementById("search").addEventListener('keyup', function (e) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "#", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.readyState == 4 && xhr.status == 200) {
object = JSON.parse(xhr.responseText);
console.log(object);
}
}
}
xhr.send("search=" + this.value);
});
</script>
Check the value before making request
function getResult(elem) {
if (elem.value !== '') {
console.log('Have values')
} else {
console.log('No values')
}
}
<input type="text" onkeyup="getResult(this)">
I have the onkeyup search function its working fine without any issue.
I want that when I will write in a textbox and there is a part of result I want to keep updating without reloading full page.
I have used the below code for refresh automatically after xxx seconds, it is refreshing the part of div using the below code of refresh but on key change, not automatically. I need it to be refreshing automatically after xxx seconds.
In the result there is close and open button if office time is still valid or closed. if i searched with OnKeyUp and it showed me the result with TRAVEL office is open and after 5 seconds its timing will finish for that i need to keep that refresh code to work on that time when the time will finish and will refresh it.
help is needed in this, please if somebody can adjust it.
Code for refresh:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#pen').load('sample.php');
}, 1000); // the "3000"
});
HTML
<form class="well-home span6 form-horizontal">
<input type="text" id="book" onKeyUp="book_suggestion()">
</form>
<!-- Display Result of onkeyup Search -->
<div class="check" id="suggestion">
<!-- Refresh here -->
<div class="row check" id="pen">
</div>
</div>
JS of onkeyup
function book_suggestion() {
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "textboxSearch=" + book;
xhr.open("POST", "sample.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("suggestion").innerHTML = xhr.responseText;
document.getElementById("suggestion").load = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
This is a typicall example, how to confuse yourself by mixing the jQuery with vanilla javascript and on..... event on an element. Once, you use jQuery, let use it's advantages.
First of all, organize your things, and use only jQuery, remove the onKeyUp from element.
//Setinterval
var timer = setInterval(function () {
$('#pen').load('sample.php');
}, 1000);
$('#book').on('keyup', function() {
$('#suggestion').load('sample.php', {action: 'onkeyup', textboxSearch: $(this).val()}, function(response) {
console.log('Response of sample: ' + response + ' if you need');
});
});
But, your main problem is that you update $('#pen') in your timer, what is ok, but when you execute the keyup it is update the whole #suggestion so the $('#pen') will loss.
I am working in MVC from last one year and in most of cases i am using JQuery ajax calling for Calling controller method. Now my requirement is that I have a button(Add User) on page on its click i open a Modal popup on which i need to partial view and 2 buttons(Save and Cancel).
After filling form i click on Save button .Now i want to MVC functionality and want to post data using Asynchronous Method of Ajax form. After save i want to reload Partial view with empty form.
Can someone guide me
Thanks in advance.
Youre looking for a javascript only kind of call?
function submitForm()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open(GET, "data.txt", true);
xhr.send(null);
}
and your HTML:
<FORM method="POST" name="ajax" action="controller/action">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
Current Setup
I have an HTML form like so.
<form id="demo-form" action="post-handler.php" method="POST">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
I may have many of these forms on a page.
My Question
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
function getHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
So for example, say the javascript method demoRequest() was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest?
EDIT
Trying to implement a solution from an answer below I have modified my form like so.
<form id="demo-form">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button>
</form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
Button Event Listener
document.getElementById('updateBtn').addEventListener('click', function (evt) {
evt.preventDefault();
// Do something
updateProperties();
return false;
});
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().
Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);
request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest's method send():
var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert(xhr.responseText); }
xhr.open(oFormElement.method, oFormElement.getAttribute("action"));
xhr.send(new FormData(oFormElement));
return false;
}
</script>
</head>
<body>
<form method="POST"
action="post-handler.php"
onsubmit="return submitForm(this);" >
<input type="text" value="previousValue" name="name"/>
<input type="submit" value="Update"/>
</form>
</body>
</html>
This snippet is basic and cannot use GET. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction.
By the way I have used the following code to submit form in ajax request.
$('form[id=demo-form]').submit(function (event) {
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// fire off the request to specific url
var request = $.ajax({
url : "URL TO POST FORM",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
});
// prevent default posting of form
event.preventDefault();
});
With pure Javascript, you just want something like:
var val = document.getElementById("inputFieldID").value;
You want to compose a data object that has key-value pairs, kind of like
name=John&lastName=Smith&age=3
Then send it with request.send("name=John&lastName=Smith&age=3");
I have had this problem too, I think.
I have a input element with a button. The onclick method of the button uses XMLHTTPRequest to POST a request to the server, all coded in the JavaScript.
When I wrapped the input and the button in a form the form's action property was used. The button was not type=submit which form my reading of HTML standard (https://html.spec.whatwg.org/#attributes-for-form-submission) it should be.
But I solved it by overriding the form.onsubmit method like so:
form.onsubmit = function(E){return false;}
I was using FireFox developer edition and chromium 38.0.2125.111 Ubuntu 14.04 (290379) (64-bit).
function postt(){
var http = new XMLHttpRequest();
var y = document.getElementById("user").value;
var z = document.getElementById("pass").value;
var postdata= "username=y&password=z"; //Probably need the escape method for values here, like you did
http.open("POST", "chat.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", postdata.length);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postdata);
}
how can I post the values of y and z here from the form
I'd like to make a popup preview of a textarea, using a PHP function inside the popup.
Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).
Is it possible to do so ?
I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.
I did the following:
function PreviewMe() {
var newWin = window.open("", "_blank");
newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
newWin.document.close();
}
and
<textarea id="myText" ... />
<input type="submit" ... onclick="PreviewMe();">
Obviously it works without reformatting anything, so how to reformat this result in the popup please ?
Would it be possible (and mayber a better option) to use XMLHttpRequest ?
Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end.
In case it might help others, here is what I've done.
Js function became :
function PreviewMe() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("XMLHTTPRequest not supported...");
return;
}
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById('show').innerHTML = xhr.responseText;
}
};
xhr.send("var="+document.getElementById('myText').value+"");
return;
}
Of course page.php includes my PHP function, show is the id of the div where the result is printed.