PHP Post not working with Ajax - php

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

Related

How can I change a label dynamically on a page, based on input from a text box?

I'm trying to create a more friendly input form where I ask for a user's name in a text box, and based on the information typed in, I would like to echo this to a display a little lower on the page, to personalize the page a little farther.
I'm trying to use AJAX, but am open to any better options out there...
<script>
function myFunction()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",document.getElementById("fname");,true);
xmlhttp.send();
}
</script>
<p>Contact's first name <input type="text" id="fname" onkeyup="myFunction()">
<div id="myDiv">Contact's</div> phone number <input type="text" id="phn"></p>
use this simple code
<script>
function myFunction(val){
document.getElementById("myDiv").innerHTML = val;
}</script>
<p>Contact's first name <input type="text" id="fname" onkeyup="myFunction(this.value)">
<div id="myDiv">Contact's</div> phone number <input type="text" id="phn"></p>
Okay let me get this properly.
1) User types his name
2) User has to submit the name (Add a button)
3) Using AJAX (Only if you have to store the name to DB dynamically, that's a good choice)
4) Update the user name if AJAX was success, or show a error
5) If you just want update name on page, no need for AJAX. (Well I don't see the use of it unless you are just trying to learn things)
HTML
<form id="user-form">
<div>
<span>Contact's first name</span>
<input type="text" id="fname" name="fname">
</div>
<div>
<span>Contact's phone number</span>
<input type="text" id="phn" name="phn">
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
<p id="user-name">User name</p>
JS
var userForm = document.getElementById("user-form");
userForm.onSubmit = function(e){
e.preventDefault();
var name = document.getElementById("fname").value;
var phone = document.getElementById("phone").value;
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)
{
document.getElementById("user-id").innerHTML = name;
}
}
xmlhttp.open("POST","file.ext",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=" + name + "&phone=" + phone);
}
I would recommend you to start using jQuery library. It would simplify things a lot
I would use jQuery for your ajax as it has some cross browser compatible functions such as $.get.
Apart from that I don't really see any other recommendation I could provide apart from a small syntax error:
xmlhttp.open("GET",document.getElementById("fname");,true);
You should remove the semi-colon:
xmlhttp.open("GET",document.getElementById("fname"),true);
As #Hitham commented, sending a request on every keyup is probably not wise. You should add a button and use the click event to send the information, or use a form and use the submit event. However, if this is a test exercise then it shouldn't be a problem.

PHP Ajax with a form

I have a form that let user to choose where them come from..
I have list out the country list by select box..
and i success to do it onchange and use ajax to read out all the state list..
actually i have two php file.. one is the main one that contain all the code include the form.. another one is generate state list.. my ajax code and form are in the main php
this is the one that generate state list...
$cID = $_GET["country"];
$sql = "SELECT * FROM States WHERE CountryID=$cID";
$result = $db->get_results($sql);
if (isset($result)) {
foreach ( $result as $states ) {
?>
<input type="checkbox" name="chkState[]" value="<?=$states->StateID?>" /> <?=$states->StateName?><br />
<?php
}
}
this is part of my code that read out..
but my problem is...
where i submit the form..
i only get the variable of country.. i cannot take the data of state that use ajax to generate out...
sample of my form
<form action="" name="place">
<select name="cboCountry" class="drop" onchange="showState(this.value)">
//some php code the list out the country
</select>
<div id="txtHint">
</div>
<input type="submit" name="submit" value="submit" />
</form>
and here my ajax code
<script>
function showState(str)
{
alert('xxx');
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","state_list.php?country="+str,true);
xmlhttp.send();
}
</script>
so when i submit the from with a save button... i only get the date of country and state are missing.. any body can help me? or having any way to do what i want?

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>

how to access ajax returned value in php

Hi I am really new to web development. I would like to know how I can access a ajax returned value in php.
When i select an option from my drop down i get another dropdown using ajax. But I would like to use the value on the page using php.
Practice Name :
<select name="practiceName" id="practiceName" onchange="showAssociate(this.value)">
<option value="">Select an option</option>
<option value="abc">abc</option>
<option value="xyz">xyz</option>
</select>
<p>
<div id="associate">
</div>
The ajax code is:
function showAssociate(str)
{
if (str=="")
{
document.getElementById("associate").innerHTML="";
return;
}
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)
{
document.getElementById("associate").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getAssociate.php?q="+str,true);
xmlhttp.send();
}
The ajax is returning the desired drop box and values in the div 'associate' but how can i use those values in php while submitting the form? I just need to access and echo it somewhere on the screen. please do help.
Thanks in advance.
If you want the data that was retrieved via ajax to be sent along with the form, you can populate a hidden input, so that the data will be transported in the form submission.
<input type="hidden" id="data" name="data" value="" />
In the Javascript, populate its value:
document.getElementById("associate").innerHTML=xmlhttp.responseText;
document.getElementById("data").value = xmlhttp.responseText;
On the PHP side when you handle the form submission, it will be present in $_POST['data'] (assuming the form's method is POST).

passing text value to ajax function on clicking submit button

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.

Categories