I've been searching for an answer to this for several days now, but if I missed the answer in another post, let me know.
I'm trying to get into Ajax, so I have a very simple form in my index.php, with separate php and javascript files:
index.php
<div id="ajax-test">
<form action="ajax/ajax.php" method="POST">
<textarea name="someText" id="some-text" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
main.js:
function getXMLHttpRequestObject() {
var temp = null;
if(window.XMLHttpRequest)
temp = new XMLHttpRequest();
else if(window.ActiveXObject) // used for older versions of IE
temp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return temp;
}// end getXMLHttpRequestObject()
function loadDoc() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
};
ajax.open("POST", "ajax/ajax.php", true);
ajax.send();
}
ajax.php:
<?php
print_r('\'' . $_POST['someText'] . '\' is what you wrote');
?>
Whenever I try to print, it prints: " '' is what you wrote " - what am I missing/not doing/doing incorrectly that isn't allowing me to access the content of someText? I've changed my naming convention, swapped from single quote to double quote, tried GET instead of POST, but nothing worked.
You can try to set a header request and also put the data inside the send. Here an example as like as-
ajax.open("POST", "ajax/ajax.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("someText="+document.getElementById('some-text').value);
This is probably beacuse of the error
Undefined index: someText in C:\xampp\htdocs\ssms\sandbox\ajax\ajax.php on line 3
You had a couple of issues with your code which i don't have time to list out now. This should work fine, plus i used the onkeyup() function to display the text live without even clicking on the submit button.
The Index File
<div id="ajax-test">
<form method="POST" onsubmit="return false;">
<textarea onkeyup="loadDoc()" name="someText" id="someText" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
<script type="text/javascript" src="main.js"></script>
The Main Javascript file
function _(x) {
return document.getElementById(x);
}
function ajaxObj ( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function loadDoc() {
var someText = _("someText").value;
var ajax = ajaxObj("POST", "ajax/ajax.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
}
ajax.send("someText="+someText);
}
The PHP AJAX File
if(isset($_POST['someText'])){
$someText = $_POST['someText'];
echo "\"$someText\"" . ' is what you wrote';
exit();
} else {
echo "An error occured";
exit();
}
Related
I want to make a page that the user put any word on textbox and returns all books with that word in (books is in mysql and i am gone to convert the query in xmlconvert.php)
<form id="keyword" >
<input type="text" name="value" id="book"/>
<br/>
<button onclick="showhint(functionvalue())">Search By Title</button>
</form>
there is the a function to get the word that user put and send it to ajax showhint();
<script>
function functionvalue() {
var bookname = document.getElementById('book').value;
return bookname;
}
</script>
there is the ajax code that get the responsetext from xmlconvert.php file where I got the q where is the word that user put and make a query with that word and return the books in xml
<script type="text/javascript">
function showhint(str) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("keyword").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","xmlconvert.php?q="+str,true);
xmlhttp.send();
}
</script>
I don't know if my thought is correct let me know if I can do that and how is possible to make it.
Sorry my English is not so good
You are assigning your new XMLHttpRequest to the variable ajax but then calling its commands with other names. If you named it ajax, you need to do ajax.readyState, ajax.status, ajax.open, ajax.send, etc.
So this should work:
<script type="text/javascript">
function showhint(str){
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function{
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("keyword").innerHTML = ajax.responseText;
}
};
ajax.open("GET","xmlconvert.php?q="+str,true);
ajax.send();
}
</script>
Need to make the following changes:
ajax.onreadystatechange should be a function definition so include () after the function keyword
XMLHttpRequest should be referenced through ajax var.
So the correct code would be:
<script type="text/javascript">
function showhint(str) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("keyword").innerHTML = ajax.responseText;
}
};
ajax.open("GET","xmlconvert.php?q="+str,true);
ajax.send();
}
</script>
I am trying to display contents of a php file on my html page using ajax.
I have an html file with the following ajax code :
get_ajax.html
<form action="">
First name: <input type="text" id="txt1" onblur="show users(this.value)">
</form>
<p>Username: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = newXMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
user.php
<?php
echo $_GET["u"];?>
It doesn't display the username on my get_ajax.html page.
Is there something wrong with my code?
First check the existence of user.php and verify the proper path,by the way why don't use Jquery,it is easy and straight forward.
Here is an example using jquery :
var str = 'something';
$.get('user.php',{u:str},function(serverResponse){
$("#txtHint").html(serverResponse); //this should add the value something to the DOM
});
Appears you have type in your code as below
- onblur , you are making a call to "show users(this.value)"
- there is a space between "show" and "user" , even u correct the space , you dont have a function "showuser" anywhere.
- your function to make the ajax call is "showHint"
- next you need a space between "new" and "XMLHTTpRequest()"
<form action="">
First name: <input type="text" id="txt1" onblur="showHint(this.value)"/>
</form>
<p>Username: <span id="txtHint"></span></p>
</form>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
I want to use Javascript to validate my input username if it is correct or not showing result on realtime.
Here is index.html code:
<html>
<head>
<script>
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
Type a username: <br>
<input id="hint" type="text" name="username" oninput="showHint(this.value)"><p id="hint"></p>
</body>
</html>
Here is the demo3.php code:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","root","123456","mini");
$username = $mysqli->real_escape_string($_REQUEST['input']);
$sql = "SELECT username FROM `users` WHERE username='$username'";
$result = $mysqli->query($sql);
if($result->num_rows){
echo "Valid username";
}else{
echo "Invalid username";
}
?>
</body>
</html>
I use the oninput event example from w3cschools, and I am wondering why my result do not show what I expect?
And if I assign $username with static variable, demo3.php result seems to be correct feedback, not from index.html.
Plus, I am wondering how to validate multiple forms, such as password and email within the same validation php file.
Ex:
input1 -> check username ->output check result
input2-> check password ->output check result
input3-> check email->output check result
New to javascript.All the tutorial seems to provide only one demo, not multiple examples.
Since your input is being placed in the URL, you will need to use the GET parameter other than POST (which does not use the URL):
xmlhttp.open("GET", "demo3.php?input=" + str, true);
Now it should be able to pickup your input for $_REQUEST['input'] or $_GET['input']
The problem is that you are using the ID "hint" twice. ID is a unique identifier, so you NEVER should use it more than once in the same page. And you should avoid using inline handlers. You need to change your javascript to:
<script>
window.onload = function() {
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
document.getElementById("hintInput").onkeyup = function() {
showHint(this.value)
}
}
</script>
and your HTML:
<input id="hintInput" type="text" name="username"><p id="hint"></p>
You can get rid of window.onload if you place your script tag before closing the body tag.
this is my first question here (usually I like to find my own ways to solve problems) but I just can't find problem in my file upload code. It's supposed to use AJAX. I simplified everything so it would be easier for you to read. Here is HTML form:
<form id="fileForm" enctype="multipart/form-data" method="POST" action="php/uploadfile.php">
<p>Insert file: <input type="file" id="fileUp" name="fileUp" />
<button type="submit" id="uploadButton" onclick="sendFile();">Upload</button></p>
</form>
Now here goes javascript sendFile() function:
function sendFile()
{
var forma = document.getElementById("fileForm");
var failas = document.getElementById("fileUp");
var uploadButton = document.getElementById("uploadButton");
forma.onsubmit = function(event)
{
event.preventDefault();
}
uploadButton.innerHTML = "Uploading, please wait!";
var newFile = failas.files[0];
var formData = new FormData(forma);
formData.append("fileUp", newFile, newFile.name);
alert(newFile.name);// Here it says filename.jpg it means everything is ok at this stage
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST", "php/uploadfile.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(formData);
}
And php:
<?php
echo var_dump($_FILES);
?>
It should alert contents of $_FILES, but it says array(0){} even if I try $_REQUEST. So, if anyone could suggest what may be wrong, it would be appreciated :]
I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>