I am new in AJAX.
I am trying to load some content from my PHP file into the load.html. i made the function on the onKeyUp Event of a textbox.
But its always showing "UNDEFINED" as the output . :(
Please help me
The load.html file
<!DOCTYPE html>
<html>
<head>
<script>
function NickName(nick){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState ==4){
document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
}
}
xmlhttp.open("GET","myphp.php?key="+nick,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="divNick"></div>
<input type="text" id="text_box" onKeyUp="NickName(this.value)">
</body>
</html>
And the myphp.php file
<?php
if(isset($_GET['key']))
{
$key = $_GET['key'];
$choice1 = "Shifar";
$choice2 = "Nidal";
if($key==$choice1)
{
echo "Shifz";
}
else if($key==$choice2)
{
echo "Steavz";
}
else
{
echo "No Match Found";
}
}
?>
Thanks in Advance.
Shifar Shifz
its because you dint specify the correct function name.
You defined a function named NickName and called another named NicKName
updated to comments
its coming as undefined because of another typo u made xmlhttp.reponseText instead of xmlhttp.responseText
There is typo. your function name is NickName you are calling NicKName. K is capital
Change document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
to document.getElementById("divNick").innerHTML = xmlhttp.responseText;
again a typo. reponseText --> responseText
Try like this :
xmlhttp.open("GET","myphp.php?key="+nick,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.status==200 && xmlhttp.readyState ==4)
{
document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
}
}
I think the order is important and NickName is not NicKName
I can see there is a typo error in your function name. When you call the function you have used NicKName but the function is actually defined as NickName. the (k) is capitalized in your calling statement.
Other advice for you, write Ajax like you have done is a very old approach. And most importantly you will have a great deal of coding for many browsers...you are supposed to deal with all the browsers out there. So why don't you use other ajax approach. I advice you to use jQuery $.ajax. Its very simple and handles all the cross-browser compatibility issues.
For eg. the above line of code could be replaced with....
$('#divNick').load('myphp.php?key='+nick);
Just one line. the other is you can also use the $.ajax which can let you do both POST and GET requests as you wish.
Most important you have said you are new to Ajax. If so why don't you already start reading about jQuery...besides its very rewarding in both by saving you time and when you are done, you will see how many job position require jquery as a skill set.
Hope this will help.
Spelling mistake on your ajax code
Instead of - document.getElementById("divNick").innerHTML = xmlhttp.responseText;
You typed - document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
Related
My application gathers some client related information via JavaScript and submits it via AJAX to a php page.
See the code below:
index.php
<html>
<head>
<script>
function postClientData(){
var client_data = new Array(screen.availHeight, screen.availWidth);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == client_data[0]){
document.getElementById("message").innerHTML = "Client data successfully submitted!";
}
}
};
var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
xmlhttp.open("GET", parameters, true);
xmlhttp.send();
}
</script>
</head>
<body onload="postClientData()">
<span id="message"></span></p>
</body>
</html>
ajax.php
<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>
I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. When I try adding the code, I probably get into a endless loop since I don't get my "success" message.
How can I solve this issue?
Correct, IMO I would definitely keep this specific logic separated in the ajax.php file.
If you do really want to merge, add it to the top of index.php (before printing data):
if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
// Execute specific logic and exit to prevent sending the HTML.
exit;
}
I've been learning to use AJAX with the GET request that allows me to access a PHP script with an array of data on a server. I want to be able to send a request that tells the server to run code that will open an application and manipulate some info on this application.
Here is the code I use to firstly communicate with the server, then send a request to the server and finally handle responses from the server.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("cant create that object hoss");
}
else
{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
Here is the PHP I was using while I was learning how to use AJAX. I got the following error when I printed the 'xmldom' variable from the above code to the console and inspected it - "error on line 2 at column 1: Extra content at the end of the document". This may be a different question to my original post, but I thought I'd bring up that this error occurred. This then had a knock on effect for the line 'var message = text.childNodes[0].nodeValue;' which produced the error - "Uncaught TypeError: Cannot read property 'childNodes' of undefined".
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>':
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food, $foodArray))
echo 'We do have '.$food.'!';
elseif($food == '')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
The code that I have been working with to learn AJAX may not be relevant, I just thought I'd post it in case I can use some of this code that has already been written.
To sum up, I want to be able to do be able to send a boolean, or whatever is viable with AJAX, to the server that tells it to run a script. This script will then open a Maya application and run some Python code that I have written.
Thank you in advance!
As soon as you call the PHP file, this begins running code on the server. If you want to run an external application from PHP, take a look at the exec() function:
http://php.net/manual/en/function.exec.php
You have jQuery listed in your question tags. Have you compared the javascript and jQuery code?
The advantages of using jQuery are:
less typing,
simpler structure
automatically cross-browser
easily use Promises interface
Have a look at these examples and see if you prefer the jQuery AJAX methodologies:
Three simple examples
dynamic drop down box?
Chain AJAX Requests with jQuery Deferred
Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..
If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.
I've got an empty div (id="theDiv") in my .html that I'm trying to fill with the content of a text file. It looks like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="Practice.js"></script>
</head>
<body onload="process()">
<p>Connected to server.</p>
<div id="theDiv"></div>
</body>
</html>
I'm trying to print out when each readyState occurs in the process. The javascript looks good to me but when I run the page I get an alert with "NetworkError: A network error occurred." which I assume is probably triggered by the first alert in the script. I have used a linter and still have no idea where in the .js the problem is so I'll put everything here:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if(xmlHttp) {
try{
xmlHttp.open("GET", "Practice.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}catch(e) {
alert( e.toString() );
}
}
}
function handleServerResponse() {
theDiv = document.getElementById("theDiv");
if(xmlHttp.readyState==1) {
theDiv.innerHTML += "Status 1: server connection established <br/>";
}else if(xmlHttp.readyState==2) {
theDiv.innerHTML += "Status 2: request received <br/>";
}else if(xmlHttp.readyState==3) {
theDiv.innerHTML += "Status 3: processing request <br/>";
}else if(xmlHttp.readyState==4) {
if(xmlHttp.status==200) {
try{
text = xmlHttp.responseText;
theDiv.innerHTML += "Status 4: request is finished and response is ready <br/>";
theDiv.innerHTML += text;
}catch(e){
alert( e.toString() );
}
}else{
alert( xmlHttp.statusText );
}
}
}
Sorry for the long code. I'm really quite befuddled so I would be really grateful for any help!
I just copied your source code and ran it all on my own server. There were absolutely no issues with it. I made my own "Practice.txt" file, as well. No problems.
I put the script at the end of the body, and wrapped process() in the closure, which worked; I also took away the closure from process(), and put process() inline as an onload handler to the body tag, just like you did. Once again, no issues.
So, here are some potential causes of your problems:
Is "Practice.txt" in the same directory as your doc that is requesting it?
Is there some configuration in your server somewhere that won't allow you to request that specific resource?
Is, for some strange reason, the fact that your script is external and in the head causing some weird issue?
Have you tried requesting any other resource besides "Practice.txt"? Is so, what were the results?
And lastly... is your server on? Gotta throw that one in there (I assume the server is on, but who knows.)
im having a setback, im making an Html page with javascript, and im using AJAX to call Perl functions. The thing is when my Perl program doesn't need parameters the calling is trivial. But i have a function to open and read a file so i need to give the location of the file to the perl script, thus having to passe it trough a paramenter in the AJAX calling.
Ex working call:
function getOption(){
var selectmenu=document.getElementById("Select1")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing"){
var s = chosenoption.text;
openFile("C:\PerlTest\test.txt");
}
}
}
EX. not working trying to pass parameter:
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Im attempting to pass the paremeter in that way because of this example:
http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201
Can anyone help??
Thanks a lot.
After the sugestion of Kinopiko, that makes sense, i have the following:
HTML-
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
var container = XMLHttp.responseText.split("\n");
if (container.length>0){
for ( i=0; i< container.length-1;i++){
document.getElementById("TxtArea").innerHTML += container[i] + " ";
}
}
}
else{
document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Perl script:
#!c:/Perl/bin/perl
use strict;
use CGI qw/param/;
use URI::Escape;
print "Content-type: text/html\n\n";
my $file = param ('file');
$file = uri_unescape ($file);
open (MYFILE, $file);
while (<MYFILE>) {
chomp;
print "$_\n";
}
close (MYFILE);
Now i dont get error in javascript, but my XMLHttp.readyState is never 4, so i dont get the content of the file.
Maybe im using the encodeURI wrong??
Thanks.
First of all you need to add a question mark:
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+name, true);
Also you need to percent-encode "name" using encodeURI.
On the Perl end, you can use a module like CGI to get the value of the file:
use CGI qw/param/;
my $file = param ('file');
Then
use URI::Escape;
$file = uri_unescape ($file);
open (MYFILE, $file);
should be
open (MYFILE, $file) or die "Cannot open file $file: $!\n";