Messing with some code from W3 schools with PHP and Ajax. I've got a database that I am pulling last names from. I want to be able to store that last name in a variable and print it out at the bottom of the page. Since the names are dynamically created from the database, there is no "value" to reference to capture the variable that way.
The code works by the user beginning to type a name into the textbox, and the AJAX function autocompletes. If the user selects a name as the one they were searching for, how do I capture that as a variable?
<!DOCTYPE html>
<html>
<head>
<script>
//Ajax tutorial - http://www.w3schools.com/ajax/
function showHint(str)
{
var xmlhttp;
if (str.length==0){
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("browsers").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getName.php?q="+str,true);
xmlhttp.send();
}
</script>
<?php
$msg = "";
$name = "";
$test = "Test.";
if (isset($_POST['enter'])) //check if this page is requested after Submit button is clicked
{
$name = trim($_POST['']);//What do I need to select here?!?
}
?>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="3-searchName.php">
Search by Last Name:
<!--
<select name="drop" onchange="showHint(this.value)">
<option value = "">Enter last name here</option>
</select>
-->
<input type="text" list="browsers" name="drop" value="" onkeyup="showHint(this.value)" />
<datalist id="browsers" >
</datalist>
<input name="enter" class="btn" type="submit" value="Submit" />
<br/><br/>
User information will show here when the button is clicked.
<br/>
<?php echo $name ;?>
<br/>
<?php echo $test ;?>
</form>
</body>
</html>
You can use the onblur action on the text input. The assumption is that when the user leaves the input they have found the name they want. Then you can grab the value and use it however you want. You can also verify the selection via ajax if you wanted to be sure it is a valid database selection. Using the select does some of this for you by the onchange action and the dropdown is populated from the select.
Related
I have written a code that contain a text box and submit button. When I hit the enter with text box value it should go to another page(q.php) using ajax, and it should return values from there to here(home.php)
here is my code. (home.php)
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(str) {
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","q.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form onsubmit="return myFunction(document.getElementById('fname'))">
Enter name: <input type="text"id="fname" name="fname">
<input type="submit" value="Submit">
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
My next page(q.php)
<?php
$q = $_GET['q'];
echo $q."Some Content from this page";
?>
My answer is using html+jquery+php:-
<html>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script><!-- add jquery library -->
<form method="post">
Enter name: <input type="text"id="fname" name="fname">
<input type="submit" value="Submit" class= "abc">
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
<script type = "text/javascript">
$(document).ready(function(){ //when your page is rendered completly
$('.abc').click(function(e){ //when you click on submit button this function will run
e.preventDefault();//to prevent normal submission of form
if($('#fname').val() !== ''){ //check name field have some value
$.post('q.php',{'q':$('#fname').val()},function( data ){ //send value to post request in ajax to the php page
$('#txtHint').html(data); //print the response coming from php page to the result div inside your html code
});
}
});
});
</script>
And in php file:-
<?php
$q = $_POST['q'];
echo $q."Some Content from this page";
?>
Sorry, I'm new here so please forgive any bad formatting :)
I want that when the delegate from delegate.php types something in their input field and click submit, a pop up window will appear on chair's page containing the content of delegate's input field.
I've tried using AJAX but it doesn't seem to work, any help is much appreciated. I have attached delegate.php and chair.php here
delegate.php
<html>
<head>
<script src = "jquery-1.11.3.min.js"/>
<script type="text/javascript">
function validate()
{
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("textContent").innerHTML=xmlhttp.responseText;
}
};
a = document.getElementById("textContent").value;
alert(a);
xmlhttp.open("GET", "temp.php?="+a, true);
xmlhttp.send();
}
</script>
<title>Delegate Page </title>
<h1> Welcome Delegate </h1>
</head>
<form>
<input type="text" name="contents" id="textContent" name="text">
<input type="submit" onclick="validate();">
</form>
</html>
chair.php
<?php
$text = $_GET['textContent'];
print '<h1>'.$text.'<h1>';
?>
At the moment I have two files, index.htm and accessdata.php.
This is what I have in index.htm:
<html>
<head>
<script>
function postData() {
var xmlhttp=new XMLHttpRequest();
var url = "accessdata.php";
var checkBoxes_formData = new FormData(document.getElementById("checkBoxes"));
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(checkBoxes_formData);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<button type="button" onclick="postData()">POST</button>
<form id=checkBoxes>
<table>
<tr><input type="checkbox" name="opt1" value="blue" checked> Blue</td>
<tr><input type="checkbox" name="opt2" value="yellow"> Yellow</td>
</table>
</form>
<p id="result"></p>
</body>
</html>
and this is what I have in accessdata.php:
<?php
$opt1=$_POST['opt1'];
echo $opt1;
echo "bla";
?>
Now, on
<p id="result"></p>
"bla" shows up, but not "blue", or "yellow".
What am I doing wrong?
THE CORRECT HTML CODE BELOW!!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>POST PHP XMLHTTPRequest</title>
<script>
function postData() {
var xmlhttp=new XMLHttpRequest();
var url = "accessdata.php";
var checkBoxes_formData = new FormData(document.getElementById("checkBoxes"));
xmlhttp.open("POST",url,true);
xmlhttp.send(checkBoxes_formData);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<button type="button" onclick="postData()">POST</button>
<form id="checkBoxes">
<input type="checkbox" name="opt1" value="blue"> Blue
<input type="checkbox" name="opt2" value="yellow" checked> Yellow
</form>
<p id="result"></p>
</body>
</html>
blue doesn't show up because you are claiming:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
But FormData objects encode data as multipart/form-data.
Remove the code that explicitly sets the content-type and let the browser generate it for you. (Don't try to explicitly set it to multipart/form-data, you have to specify what the boundary marker is going to be in the header too).
yellow doesn't show up for the same reason, but also because:
You are only looking at opt1 and it is associated with the name opt2 and
Checkbox controls are only successful (i.e. will be in the data that gets submitted) if they are checked (which the yellow one is not by default).
Complicating matters further, your HTML is invalid. Use a validator. You can't have an input as a child of a table row, you need to create a table data cell between them. (Note that it looks like you are trying to use a table for layout, you should probably get rid of the table entirely).
Tap to create a note
You should try this…
<form method=post action=accessdata.php>
<input type=checkbox value=blue name=opt1>blue
<input type=submit value=submit name=send>
</form>
In accessdata. PHP
if❨isset❨$_POST[`send']❩❩ {
$color=$_POST[`opt1'];
echo $color."bala";
}
I'm just exploring ajax to learn it.
I try the following JavaScript test code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Ajax Demo</title>
<meta name="" content="">
<script type="text/javascript">
function aa(){
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.open("GET","getprod.php",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
</script>
</head>
<body>
<form>
<input type="text" name ="txta" onchange="aa();"> </input>
<br>
<div id ='myDiv' style="width: 400px;height: 300px; overflow-y: auto;border: #e87517 1px solid">
<?php
$mysqli=new mysqli('localhost', 'root', 'password', 'ajax');
if ($mysqli->connect_errno) {
die("Connect failed". $mysqli->connect_error);
}
$mysqli->set_charset("utf8");
if ($result = $mysqli->query("select id, name from test;")){
while ($row = $result->fetch_assoc()) {
echo $row['id'], " - " , $row['name'], "<br>";
}//while
}//if
$result->close();
$mysqli->close();
?>
</div>
</form>
</body>
</html>
And a few Row For "getprod.php".
<?php
echo "123";
?>
When I change the value in textbox, Ajax returns me the string "123", as desired and places it in div, but after few seconds, div is again filled with results from MySQL, that's not desired.
1) What's wrong in my code? (Goal is: When I change value in textbox, only returned string from ajax - "123" must be appear in div container permanently.)
2) Textbox change event occurs when it loses focus or when I press ENTER on keyboard. How to fire change event without this action?
Thanks in advance.
There is nothing in the code you posted that will cause the page to reload.
"without this action" - but when? Consider using oninput event - http://www.w3schools.com/jsref/event_oninput.asp .
Try changing onchange event to onkeypress or oninput.
Hello, I made an autocomplete function when key enter is pressed. This part works. But I also have a dynamic add button to duplicate this input. The duplicate input uses a form post. BUT now when I press enter my page refreshes and I don't want this because my autocomplete doesn't work anymore. Any idea on how I could fix it? Here the code of my input :
<td>
<span id="numpro" >
<form method="post" action="">
<input onclick="addRow(this.form);" type="button" value="+" />
<input type="text" id="name" name="add_name"onkeypress="return handleEnter(event, this, 'task');"/>
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)):
?>
<p id="oldRow<?=$product['id']?>">
<input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php
endwhile;
}
?>
</form>
</span>
</td>
Here is my code for the enter key :
//------------------COMPLETE CLIENT DESC DIMANCHE----------------------
function handleEnter(e, obj, field){
if (e.keyCode == 13 || e.which == 13){
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)
{
tempArrayInJS = JSON.parse(xmlhttp.responseText);
$("#client1").val( tempArrayInJS[0]['cliName']);
$("#desc1").val( tempArrayInJS[0]['proDescription']);
}
}
xmlhttp.open("GET","completeclient.php?q="+obj.value,true);
xmlhttp.send();
}
//Enter was pressed, handle it here
Here the code of my autocomplete :
//------------------AUTO COMPLETE NUMÉRO DE PROJET----------------------
$(document).ready(function(){
//-------AUTO COMPLETE DIMANCHE PROJET-----
$("#name").autocomplete({
source:'getautocomplete.php',
minLength:1
});
If I forgot to show you some code just tell me. Or if I'm unclear I'll try to explain better . Thanks for help!
I would inspect browser console to see what kind of requests are going on there, but I assume that with enter browser is submitting also the form that is around your html:
<form method="post" action="">
Try to put e.preventDefault() to not trigger default enter key behaviour.