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.
Related
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.
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>';
?>
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.
I need to fetch the data from the XML file. That XML file would contain simply details of a user, i.e. datails can be anything.. user name and email id.. or date of birth.. etc..
Here I create a HTML source code having 2 text boxes.. Details are :-
First text box I enter the name: ABC
In the second text box, the email id of that user must appear by fetching the XML content automatically.
I have read about the http get request and post request but unable to make them.
Kindly help me..
Here is the HTML code : -
<html>
<head>
<title> Sample XML page </title>
</head>
<body>
<div align="right">
<h1>
Sample try page
</h1>
<form name="login">
Username:  
<input type="text" name="userid"/>
<br>
<br>
Email:  
<input type="text" name="Email"/>
<br>
<br>
<input type="button" " value="Submit"/>
</form>
</div>
</body>
</html>
Here is the XML code : -
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<student>
<details>
<Name> student1 </Name>
<email> student1#abc.com </email>
</details>
<details>
<Name> student2 </Name>
<email> student2#abc.com </email>
</details>
</student>
From W3 schools
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","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
That is how you turn the XML into a Javscript object from a URL.
Hope this can help you bit as part of JavaScript -
<script type="text/javascript">
var useName;
var email;
function httprequest()
{
debugger;
useName = login.txtUserId.value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "name.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
var x = xmlDoc.getElementsByTagName("CD");
debugger;
for (i = 0; i < x.length; i++)
{
if (useName == x[i].getElementsByTagName("detail1")[0].childNodes[0].nodeValue)
{
login.txtEmail.value = x[i].getElementsByTagName("detail2")[0].childNodes[0].data;
}
}
}
</script>