Really basic AJAX - php

I'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
Here is the html:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>

This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);

It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);

First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>

Related

Sql Querying with Ajax while offline returning blank

I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
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("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?

Data output using Ajax with PHP

I will break this question into paragraphs for easier reference.
I have a script that calls a php file using Ajax; the script is executed once a button is pressed.
The PHP file contains a simple code that plusses a number with 1.
<?php
$response = $response + 1;
echo $response;
?>
However, something goes wrong when the button is pressed multiple times. I have done some research and I can conclude that there is either something wrong with the simple PHP script that I have made, or the code is only executed once per page reload.
I read an article explaining a lot of work using Javascript if I want an Ajax command to execute multiple times during the same script but I don't see the reason that it can't execute multiple times already when the button is pressed.
Question: Is the PHP file "post.php" even getting executed everytime the button is pressed? Is it something with my PHP file?
How can I make the script plus the number by 1 everytime the button is pressed? And is it because I need some extra Javascript to do that?
The rest of the script is here:
<head>
<script>
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<p>This button will execute an Ajax function</p>
<button type="button" onclick="loadXMLDoc()">Press here!</button>
<div id="myDiv"></div>
<script type="text/javascript" src="http://www.parameter.dk/counter/5b0d9873158158e08cad4c71256eb27c"></script>
</body>
If I wasn't clear enough at some point, please pick out the paragraph number and I'll deepen that part.
In your code $response is always 1 because php by default have no state. You can fix it by saving response inside a session.
session_start();
if (isset($_SESSION['response'])) {
$_SESSION['response'] = $_SESSION['response'] + 1;
} else {
$_SESSION['response'] = 1;
}
echo $_SESSION['response'];

Change an image using AJAX

I want to create a login page.
So I put a captcha picture in the login form with following html code:
<img name="captcha" id="captcha" src="captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5"/>
and I put a button that users can click on to change captcha if it is unreadable as follow :
<input type="button" name="new_Captcha_button" onClick="new_captcha()"/>
and I wrote a script as follow which work just in chrome :
<script type="text/javascript">
function new_captcha()
{
document.images["captcha"].src = "captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5";
}
</script>
but it doesn't work in other browsers, so I replace the previous code with the following :
<script type="text/javascript">
function new_captcha()
{
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("captcha").src = xmlhttp.responseText;
  }
}
xmlhttp.open("GET","captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5",true);
xmlhttp.send();
}
So please tell me what changes I need to do in my code to make it correct. I think I need to change just following line :
document.getElementById("captcha").src = xmlhttp.responseText;
Thanks a lot.
<script type="text/javascript">
function new_captcha()
{
document.getElementById('captcha').src = 'captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5&_t=' + Math.random(1);
}
</script>
Do not need to use ajax, function new_captcha() is ok as it is.
You may try to do this
login.php
<div id="captcha_container"></div>
<input type="button" id="btn_recaptcha" value="Recaptcha">
<script>
function ajax_loadpage(loadUrl,output_container)
{
$.post
(
loadUrl,
{language: "php", version: 5},function(responseText){$(output_container).html(responseText);},"html"
);
}
ajax_loadpage("captcha_page.php","#captcha_container");
$('#btn_recaptcha').click(function(){
ajax_loadpage("captcha_page.php","#captcha_container");
})
</script>
______________________________________________________________________________________
captcha_page.php
<img width="212" height="53" src="captcha.php">
captcha.php contains my captcha code, it contains a header ("Content-type: image/gif"); code, so i needed an extra php file on where i can save the image file, thus using my captcha_page.php.
Worked for me :)

How to send javascript variable to php using ajax?

The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>
Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.

How to recognise if user clicked out of text input and run php in that event

How can I use javascript to check, if the user clicks out of my text input class = "foo", and then, if the user has done so, execute a php file.
The easiest way to go about doing this, is to use jQuery.
First, include jQuery in your <head></head> section:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Then add in the following Javascript:
$(document).ready(function() {
$('input.foo').blur(function(){
$.ajax('myScript.php');
});
});
This will setup the input (who's class is foo) to use ajax to run myScript.php whenever someone clicks out of it, which in development terms is called blurring.
Here an example with plain javascript.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function runAjax(){
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","fooscript.php",true);
xmlhttp.send();
}
</script>
<form>
<input name="vorname" type="text" onblur="runAjax()">
</form>
</body>
</html>
Maybe it's a good idea to use a javascript framework like jQuery. I've stolen this example from here.

Categories