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>
Related
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?
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.
I am have a hard time learning how to use ajax and jquery to post a button without reloading the page. Specificly: The form is still reloading the page and no variables are being updated.
Here is the code I am stumbling through.
What I used before I tried Jquery/AJAX. Just php
// $_POST['selected_dir'] is set when you click on a folder or link within the explore(r).php
if (isset($_POST['selected_dir']))
{
// last selected folder/directory
$current_dir = $_POST['selected_dir'];
// current_dir is the folder we are looking inside of.
// we make it a $session so that if we click a different submit (RELOAD)
// within the page it will remember $current_dir;
$_SESSION['selected_dir'] = $current_dir; //
}
else // if $_post isint set but $_session is
if (isset($_SESSION['selected_dir']))
{
$current_dir = $_SESSION['selected_dir'];
}
else
{
// default folder/directory
$current_dir = "$root"; //'D:\Hosting\538\html';
}
<form action='explore.php' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
value='submit'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
class='submit_into_link'/>
</form>
so that worked great except everytime you click the image or the link the page reloads.
I finally came to the conclusion i need to use jquery and ajax and I never even used javascript up till now. Ive been reading through tutorials and i cant really connect the dots to make this work
I have this in my header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
I have this at the top of my page within the body
$.ajax
({
type: 'POST',
url: 'explore_be.php',
data: data, success:
success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
I have a few questions about the code above. I'm not sure how to use it.
Do I need to put this ajax code inside an onclick function? seems like some examples ive looked through in jquery use something like this..
$(document).ready(function()
{
$(".flip").click(function() // this is a piece of code i got from w3schools.com
});
.flip above is a class. I have seen them use button when talking about
<button>
but what about a button within a form with a specific input id? Or should i just add to the form input
onclick="clicked()" then put the ajax in that function? Does the ajax need be in the $(document).ready(function()) as well?
What should i put for datatype?
I put my php code in the explore_be.php file.
explore_be.php
// $_POST['selected_dir'] is set when you click on a folder or link within the explore(r).php
if (isset($_POST['selected_dir']))
{
// last selected folder/directory
$current_dir = $_POST['selected_dir'];
// current_dir is the folder we are looking inside of.
// we make it a $session so that if we click a different submit (RELOAD)
// within the page it will remember $current_dir;
$_SESSION['selected_dir'] = $current_dir; //
}
else // if $_post isint set but $_session is
if (isset($_SESSION['selected_dir']))
{
$current_dir = $_SESSION['selected_dir'];
}
else
{
// default folder/directory
$current_dir = "$root"; //'D:\Hosting\538\html';
}
Is that all there is to the code behind page?
I changed my forms to have no action but added an onclick They are still reloading the page. What do I need to do to the form inputs to stop that?
My new form looks like this
<form action='' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
onclick='clickity()'
value='submit'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
onclick='clickity()'
class='submit_into_link'/>
</form>
Any help is greatly appreciated.
you can do it like this:
html
<form action='explore.php' method='post' id='myForm'>
jquery
$('#myForm').submit(function(event){ //added event
event.preventDefault(); //added to prevent submit
$.ajax
({
type: 'POST',
url: 'explore_be.php',
data: data, success:
success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
});
edit: remove the onclick events you added in your edit
<form action='javascript:;' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
onclick='clickity();'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
onclick='clickity();'
class='submit_into_link'/>
</form>
Firstly change this and tell me if it's ok and also tell me why you need 2 submits on the same form?
You are trying three things at a time. which will make things complex to find where the error lies. Just use ajax without jquery with a small example. Then extend it.
<html>
<head>
<script type="text/javascript">
function getdata(str)
{
if (str.length==0)
{
document.getElementById("result").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("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<input type='submit' onclick='getdata(input)'>
<div id='result'>
</div>
<body>
HOW do i get this to work
onsubmit
, instead of
onclick with a button?
I have a form:
<form id="form">
<label>Email:</label>
<input type="email" name="email" id="email" class="iput" placeholder="jane#doe.com" reguired="required"/>
<input type="button" id="nbut" onclick="loadXMLDoc()" value="NEXT">
</form>
the button works fine to call and process the javascript:
function loadXMLDoc() {
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('response').innerHTML=xmlhttp.responseText;
document.getElementById('step1').style.display = "none";
document.getElementById('step2').style.display = "block";
}
}
var em = document.getElementById('email');
var em1 = em.value;
xmlhttp.open("GET","bin/process.php?email="+em1,true);
xmlhttp.send();
}
This only works with a button onclick, I can not get it to work onsubmit and don't know why..
onsubmit is a <form> element event.
You could very simply remove the onclick attribute from the button and change your form to
<form id="form" onsubmit="loadXMLDoc(); return false;">
The return false prevents the default event handler (form submission) from executing.
When using onsubmit you should also return false:
<form id="form" onsubmit="loadXMLDoc(); return false;">
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