passing text value to ajax function on clicking submit button - php

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.

Related

php/ajax: form get method not working

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;
}

How To Prevent PHP Form Submission Through AJAX?

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>

Why my simple ajax code does not work?

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>

javascript function not returning value for a particular case

I have a sample script in php and validation are done using javascript. I am generating a inputbox using ajax script on click of a button. When I click submit it checks whether all the boxes are filled or not.
I am validating the boxes using for loop. When the boxes are empty it correctly alerts and I am returning false for the same case. But the problem is when all the boxes are filled it doesn't not return any thing and the function stops working even when I m returning true for this condition.
My javascript code with function is shown below
function addInput(){
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
var newElem = document.createElement ("div");
newElem.innerHTML = result;
newElem.id = "input";
var container = document.getElementById ("main");
container.appendChild (newElem);
}
}
xmlhttp.open("GET","insert.php",true);
xmlhttp.send();
}
var count = '<?php echo $_SESSION['z']; ?>'
function check(){
function validate()
{
for(var i=1; i<=count+10; i++)
{
if(document.getElementById("text"+i+"").value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
}
return 'abc';
}
var flag = validate();
if(flag != 'false')
{
alert("correct");
}
}
MY html code is shown below
<form method="post" action="save.php">
<div id="main">
<div id="input1">
Enter Name </br></br>
<input type="text" id="text1" />
<?php $_SESSION['z'] = 2; ?>
</div>
</div>
</br>
<input type="button" value="add another" onclick="addInput()" />
<input type="button" value="Submit" onclick="check()" />
</form>
<div id="display"></div>
my ajax code is shown below
<?php
session_start();
$q = $_SESSION['z'];
?>
Enter Name </br></br>
<input type="text" id="text<?php echo $q; ?>" />
<?php $q = $q + 1;
$_SESSION['z'] = $q;
?>
the problem is when all the fields are filled it doesn't return anything.
This may occur a lot, and according to the browser used, the click event and submit event will be call at the same time, it's not safe (for exemple, in IE if your submit button call another submit function, the form will be submitted twice...)
You should wire your check function to the onBeforeSubmit event of your form.
It is likely that you get an error when you try to retrieve an item which does not exist on the page.
if(document.getElementById("text"+i+"").value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
Here may be there are no items with ids like "text8", "text9", etc. In that case there will be null reference error when you try to get value of non exisisting element.
Try changing it like this:
var ele = document.getElementById("text"+i);
if(ele && ele.value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
This validates if ele is null or not before accessing the value of it.

PHP Post not working with Ajax

I have a simple form:
<form id="formTest" name="formTest" action="" method="get">
<input id="txtPostcode" name="Postcode" type="text" class="txtBoxSmall" />
<input type="button" name="SubmitTheForm" id="btnSubmit" onClick="TestAjax()" value="submit" />
</form>
My Javascript code is:
function TestAjax(){
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
};
xmlhttp.open("GET","autocomplete.php?value1=aaaaa&value2=fffff",true);
xmlhttp.send();
}
My problem is that in the php file autocomplete.php i can not access the txtPostcode element like so:
$postcodetext = $_GET[Postcode];
But if i get rid of the javascript function in the submit button, and add action="autocomplete.php"
to the form tag it will work, but then of course it is not ajaxed. Can someone tell me why I cant get any
values from $_GET[Postcode] when ajaxing?? I know i can just pass the value of the txtPostcode in the URL,
but i dont want to do it that way, is there something i can do so i can access the textbox via the
$_GET[Postcode] call in php??
Thanks.
You need to change this line:
xmlhttp.open("GET","autocomplete.php?value1=aaaaa&value2=fffff",true);
to include all the values you want to get in $_GET[] in PHP. You can do:
var postcode = document.getElementById('txtPostcode').value;
xmlhttp.open("GET","autocomplete.php?value1=aaaaa&value2=fffff&Postcode=" + postcode,true);
and similar for any additional things you want to access in PHP.
I totally agree with the comments below - take a look at jQuery, it will make your life much easier. Start here for example:
http://docs.jquery.com/How_jQuery_Works

Categories