I want to prevent the main form to be submitted according to AJAX response.
HTML is like this...
<form action="test.php" method="POST">
<input type="text" name="email" id="email" onblur="ajax_check_email();">
<span id="email_alert"></span>
<input type="submit" name="submit">
</form>
Now I have a js file with ajax query -
function ajax_email_check () {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("email_alert").innerHTML=xmlhttp.responseText;
}
}
var email = document.getElementById("email").value;
xmlhttp.open("GET","ajax/check_email.php?email=" + email,true);
xmlhttp.send();
}
Now the php page returns Email Already Exists or Success.
All goes well but after showing the Text that the "email already exists...!" the main form is getting submitted when I hit submit. It should prevent me. But how am I gonna do that?
You can simply add a flag like var shouldSubmit = false, in your ajax response, if it's okay to submit, change shouldSubmit to true, then add a eventlistener to form
<script>
yourform.addEventListener("submit", function(e){
if(!shouldSubmit){
e.preventDefault();
return false;
}
});
</script>
Just catch the event and stop it.
<form id="myform" action="test.php" method="POST">
<script>
$('form#myform').submit(function(e){
e.preventDefault();
});
</script>
Just add this in form tag onsubmit="return false;"
Like this-
<form action="test.php" method="POST" onsubmit="return false;">
<input type="text" name="email" id="email" onblur="ajax_check_email();">
<span id="email_alert"></span>
<input type="submit" name="submit">
</form>
Related
How can I submit a form on same without refreshing page? Here I'm submitting a pdf to drag and drop container and when I submit the form it's redirecting to upload.php. I need to display the successful message on the same container . I have not enough knowledge about the ajax. Kindly please help me to solve the issue
Here is the drag and drop container below:
Here is the result page (upload.php) below:
HTML Form:
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" multiple name="file[]" accept="application/pdf">
<input class="button-primary" type="submit" value="Submit">
</form>
Upload.php file:
<?php
//echo 'done';
$output = '';
if(isset($_FILES['file']['name'][0])){
//echo 'ok';
foreach($_FILES['file']['name'] as $keys => $values) {
if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'upload/' .$values)) {
$output .= 'Form submited succesfully';
}
}
}
echo $output;
?>
You can prevent the default behaviour of the form on submit, which redirects it.
Try using this:
<form id="form" method="POST" enctype="multipart/form-data">
<input id='file' type="file" multiple name="file[]" accept="application/pdf">
<input class="button-primary" type="submit" value="Submit">
</form>
<p id="response-text"></p>
<script>
$("#form").submit(function (e) {
e.preventDefault();
var xhttp = new XMLHttpRequest();
var data = new FormData();
data.append("file", document.getElementById("file").files[0]);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response-text").innerHTML = 'Form Successfully Submitted';
}
else {
document.getElementById("response-text").innerHTML = 'Form could not be submitted';
}
};
xhttp.open("post", "/upload.php", true);
xhttp.send(data);
});
</script>
Now you can display the desired message wherever you want to display. Here I have displayed on <p> of id response-text
Use the following code
<form method="POST" enctype="multipart/form-data">
<input id='file' type="file" multiple name="file[]" accept="application/pdf">
<input id='submit'class="button-primary" type="submit" value="Submit">
</form>
$("#submit").submit(function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append("file",document.getElementById("file").files[0]);
xhr.open("post","/upload.php",true);
xhr.send(data);
});
i have two php file , test.php and test2.php
in 'test.php' i have a form and i want to get name and echo it with ajax and php here is my code , what is wrong with it?
test.php
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form method="get">
First name: <input type="text" name="fname">
<input type="submit" value="click me" onclick="showHint(fname)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
and test2.php is
<?php
$q = intval($_GET['q']);
echo $q;
?>
The button in the form is a submission input which will result in the page being reloaded. Add return false to your onclick method to prevent this from happening:
<input type="submit" value="click me" onclick="showHint(fname); return false">
Additionally, your showHint function expects a string but you are passing an HTML input. You can get the text value by adding the following to the top of the function:
if (typeof str !== 'string' && typeof str.value !== 'undefined') {
str = str.value;
}
I have two fields in form and onsubmit() event I am calling function. When I click udpate button I could not get the values of "sent", all other values fetched correctly.
In case of insert button, sent is fetched correctly.
I am tracking the values using aler button. Can it be done using firebug too?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
**alert(id);
alert(sent);
alert(submit.name);
alert(submit.value);**
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" />
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label><input type="text" name="id"><br>
<label>Enter the sentence:<input type="text" name="sent"></label><br />
</pre>
<input type="submit" class="submit" value="submit" name="update"/>
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
You're always getting the first sent and id elements because you're using document.getElementsByName, so you need to grab the ones within the form that is submitted. By always getting the first, you will get the values from the insert form even when the update form is submitted.
var sent = form.elements['sent'].value;
var id = form.elements['id'].value;
The above will get the sent and id values from the form that was submitted, based on the form object that was passed as an argument.
You can use console.log(...) and console.debug() with firebug.
See the documentation for more info: https://getfirebug.com/wiki/index.php/Console_API
Not sure what you're trying to accomplish, but you should at least provide us with a copy of ajax_test.php if you want us to test your code. Do you get any error messages in to firebug console?
Also, why not use the ajax features of jQuery? That would make things far easier on yourself. Piao Yishi has a good tutorial on NetTuts+ on how to do that: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Doing so might just solve your problems.
Can anyone help me understand why the code does not work?
Its not change the text in the div to the text that the member write.
And sorry in advance for my English, my English teacher apparently did't do a good job... =/
the first page:
<script>
function showUser()
{
var str = document.forms["myForm"]["users"].value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","act2.php?q="+str,true);
xmlhttp.send();
}
</script>
<form name="myForm" onsubmit="return showUser()" method="post">
First name: <input type="text" name="users">
<input type="submit" value="Submit">
</form>
<div id="txtHint"><b>Person info will be listed here.</b></div>
the second page (act2.php): (corrected the name)
<?php
$q=$_GET["q"];
echo "$q";
?>
The file specified in this line
xmlhttp.open("GET","act2.php?q="+str,true);
is act2.php, but according to your post, you're looking for ajax2.php, could that be it?
You have simply forgotten to "return false" in the showUser method, the form will post as usual before the Ajax call is made
edit:
To clarify, in the onsubmit you have return showUser(), the the showUser method never returns a value, to stop the browser from posting the form. Also, as suggested by other posters, you imply the php file is named ajax2.php but the code actually tries to hit act2.php.
Also, using some sort of framework (jQuery is highly popular) is recommended.
Your function needs to return false to prevent the default action of the form, otherwise your form will be submitted (which is the default action).
simply add a return false at the end of your code.
function showUser(){
// ...
xmlhttp.send();
// prevents the default action (the submit from your form)
return false;
}
or:
<form name="myForm" onsubmit="showUser();return false;" method="post">
Also you can safely drop the IE5/6 compat code.
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
simply becomes:
var xmlhttp=new XMLHttpRequest();
The var in front is pretty important, otherwise xmlhttp will become a member of the global object instead of a scoped variable.
Just to show how you can do the same with less pain and jQuery.
<form name="myForm" action="/act2.php">
<input type="text" name="q">
<input type="submit">
</form>
<div id="txtHint"></div>
<script type="text/javascript">
$(document)
// Link handler for submiting form
.on('submit', 'form[name="myForm"]', function(e) {
// Preventing original form submition
e.preventDefault();
// Send all data from form, to url from form's action attribute (/act2.php) and set received data to div with id txtHint
$.get($(this).attr('action'), $(this).serialize(), function(data, status, xhr) {
$('#txtHint').html(data);
});
});
</script>
I have form which consists of a text field (id="txt1")
and a submit button(id="submit"). Ajax function 'showhint()' is called on 'onclick' event of submit button.
<form action="">
<input type="text" id="txt1" />
<input type="submit" id="submit" onclick="showhint()"/>
</form>
And ajax function
function showhint(){
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmllhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txthint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php",true);
xmlhttp.send();
}
Here gethint.php is page where showhint() function does its work and targeted div to write ajax respone is "txthint" .
what I want is to pass text value(form's) to ajax function. Is there any easy way?
Waiting for response, any usefull response would be highly appreciable.
thaks in adavance
var value = document.getElementById("txt1").value;
xmlhttp.open("GET","gethint.php?value="+value,true);
In gethint.php
echo $_REQUEST['value'];
If I read this properly, you are trying to get the value of the textbox and pass that to your showhint() method.
Try this:
<input type="submit" id="submit" onclick="showhint(document.getElementById('txt1').value)" value="test"/>
Then you can accept the value like this:
function showhint(value) {
// use value here
}
Hope that helps.