Not getting a response on MDN AJAX example - javascript

I previously attempted to interact with PHP using AJAX (1st time using Javascript to any significant degree) and had no success, so I tried to start with the basics using a Mozilla Developer Network example as a test:
Example - https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
That isn't working either even though I copy-pasted it straight from the site with only one change (setting the url to my test page, running on XAMPP). When I click the button to run the MDN script, the resulting output is the alert "There was a problem with the request".
I'm using Firebug to check the result, and it shows a "200 OK" code for Status. If I understand the script correctly, shouldn't that not lead to an error message?
Here is the code from the example (along with the code from the Foundation framework I was using, in case that's somehow the issue):
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation | Welcome</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('http://localhost:8000/pages/test.html'); };
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
</body>
And here is the code for the test HTML page that I made:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
Test
</body>
</html>
Where am I going wrong?
EDIT - Adding the original PHP script being referenced. I originally tried to use an altered version of the MDN script on this but likewise couldn't get it to work:
<?php
require ('includes/config.inc.php');
require (MYSQL);
$u = NULL;
$P = NULL;
$u = mysqli_real_escape_string ($dbc, $_GET['username']);
$p = mysqli_real_escape_string ($dbc, $_GET['password']);
$q = "SELECT user_id FROM users WHERE (username='$u' AND password=SHA1('$p')) AND active IS NULL";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (#mysqli_num_rows($r) == 1) { // A match was made.
$a = 'True';
print json_encode($a);
} else { // No match was made.
$a = 'False';
print json_encode($a);
}
?>
2ND EDIT - Thanks for the suggestion about the console log, that did it. All I needed to do was enable CORS and now it works fine.

Related

Ajax Post versus GET

I am trying to implement an AJAX Example which perfectly works with the GET request, but I am not able to transmit via POST. What am I doing wrong ? The POST object received by PHP is always empty. Thanks for any advice!
HTML & JavaScript:
<html>
<head>
<title> Create a new user</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function checkUser(){
xhttp = new XMLHttpRequest();
xhttp.open("POST","usercheck.php",true);
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = xhttp.responseText;
alert("Benutzer" + data);
}
}
xhttp.send("username=" + encodeURIComponent(document.getElementById("username").value));
}
</script>
</head>
<body>
<p>User:</p><br>
<input type="text" id="username" name="username">
<button onclick="checkUser();"> Check </button>
</body>
</html>
PHP Code:
<?php
$usernames = array("admin", "gast", "paul");
$validate_pattern = "/^[a-z0-9]{4,20}$/";
if (!isset($_POST["username"])) {
die("{valid:false,message:false}");
}
if (in_array($_POST["username"], $usernames)) {
die("{valid:false,message:'Username is used!'}");
}
if (!preg_match($validate_pattern, $_POST["username"])) {
die("{valid:false,message:'Username wrong.'}");
}
echo "{valid:true,message:false}";
?>
I found the bug in the code. I missed to set the request header, which was not part of the tutorial unfortunately:
xhttp.setRequestHeader('Content-Type','x-www-form-urlencoded');

XMLHttpRequest can get data to display on webpage

I am trying to retrieve data from a web page and then display it on my webpage, nothing fancy atm just display it so it cam be read, however I am not sure how to do this, this is what I have so far(Also sorry if I've not done the formatting properly I'm still new to this):
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title> Night Out In Glasgow!!</title>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<script src="pull.js"></script>
</head>
<body>
<form action = "">
<p><button type = "button" onclick ="getData()">Get The Data</button>
</p>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
This is then my JS which is in a separate file called pull.js, which I have linked to in my HTML, hope this clears up any confusion form original post.
/*jslint node: true, browser: true */
"use strict";
/*jslint node: true, browser: true */
"use strict";
function getData(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://ratings.food.gov.uk/OpenDataFiles/FHRS776en- GB.xml");
xmlhttp.onreadystatechange = checkData;
xmlhttp.send(null);
function checkData() {
if(xmlhttp.status == 4){
if(xmlhttp.status == 200){
//We've got a response
alert(xmlhttp.responseXML);
}
}
else{
//Somethings went wrong
alert("Error: " + xmlhttp.status + ": " +xmlhttp.statusXML);
}
}
}
Try it in this order:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","...");
xmlhttp.onreadystatechange = {
if(xmlhttp.status == 4){
if(xmlhttp.status == 200){
...
};
xmlhttp.send();
I'm not sure with your case, but the same origin policy restricts contents retrieved via XMLHttpRequest to be accessed from a website with different origin. Go check this StackExchange answer

WebWorker not concurrent with 2 XMLHttpRequest to php page with session_start();

On one page i have several DIVs that get filled with data from XMLHttpRequests to different php pages. To keep the UI responsive i started experimenting with webworkers. It seemed however that a faster page kept waiting after a slower page, i.e. the web worker didn't work concurrently.
I've simplified the pages for testing purposes, see code below. It seems that when the 2 back end php pages that provide the data have if (!isset($_SESSION)) session_start(); in them, one page is qeued after the other.
In the example below, there are 2 buttons that each invoke a different web worker that in turn invokes a different php script. PhpA is 10sec slower than phpB. So when you click on button wwA and then on wwB in the main (test.php) script, you should first get a response from phpB. When if (!isset($_SESSION)) session_start(); is in phpA and in phpB this is not the case. Why is this so?
test.php
<?php if (!isset($_SESSION)) session_start();?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<title>test</title>
<script language="JavaScript" type="text/javascript">
<!--
function launchWebWorkerA() {
var worker = new Worker('webWorkerA.js');
worker.addEventListener('message', function(e) {
document.getElementById('outputA').innerHTML = e.data.text;
worker.terminate();
}, false);
worker.postMessage();
}
function launchWebWorkerB() {
var worker = new Worker('webWorkerB.js');
worker.addEventListener('message', function(e) {
document.getElementById('outputB').innerHTML = e.data.text;
worker.terminate();
}, false);
worker.postMessage();
}
//-->
</script>
</head>
<body>
<input type="button" onClick="launchWebWorkerA()" value="wwA" />
<input type="button" onClick="launchWebWorkerB()" value="wwB" />
<div id="outputA">outputA</div>
<div id="outputB">outputB</div>
</body>
</html>
webWorkerA.js
// JavaScript Document
self.addEventListener('message', function(e) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
self.postMessage({'text': xmlhttp.responseText});
}
}
xmlhttp.open('POST','phpA.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
}, false);
webWorkerB.js
// JavaScript Document
self.addEventListener('message', function(e) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
self.postMessage({'text': xmlhttp.responseText});
}
}
xmlhttp.open('POST','phpB.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
}, false);
phpA.php
<?php if (!isset($_SESSION)) session_start();
sleep(10);
echo 'phpA response3';
?>
phpB.php
<?php if (!isset($_SESSION)) session_start();
echo 'phpB response3';
?>
Starting a session will block all other scripts attempting to start the exact same session (based on the cookie). This is one reason why you need to minimize the amount of time a session is opened for. Arguably you could use a database or something like memcache to kludge inter-script communication but it's not really what PHP is about.
Source: ajax multi-threaded

ajax PHP MySQL query

I need help with an ajax call, but I'm a newbie with ajax and I'm not sure as to how to do it.
I have the following PHP code (phonecall.php):
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql="SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$callArray[] = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
print "<div id=\"call\">";
print_r($callArray);
print "</div>"
}
mysqli_close($con);
?>
I want to make a page update in real time automatically anytime something new is posted to the table.
Here is my non-working page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
var ajaxDisplay = document.getElementById('call');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
setInterval(function() { //Broken
ajaxRequest.open(); //Not sure what to put here.
}, 1000);
}
//-->
</script>
</body>
</html>
Your ajaxRequest.open() method takes 3 parameters, as per the XMLHttpRequest specification:
The method of the request (POST, GET, etc)
The file you're sending your request to
Whether or not the request will be asyncronous.
So:
ajaxRequest().open('GET','yourfile.php',true);
Would build an asynchronous GET request to yourfile.php.
You're also missing the ajaxRequest().send(), which would actually send your request to the server.
There's plenty to know about this so I suggest googling it, since you seem to be lacking on the basics.

why isn't my eval turning the json string into an object

When I execute the eval function it doesn't turn my json response into a object it just breaks my code. I've tried parsing with prototype.js and JSON2.js to no avail some please explain what I am doing wrong here?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Inventory Management</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="call.js" type="text/javascript"></script>
<script src="prototype.js" type="text/javascript"></script>
</head>
<body>
<div>
<p id="resp" >new</p>
<script type="text/javascript">
var xhr;
var results=getPlants(xhr,results);
var plants;
function getPlants(xhr,results){
try {
xhr=new XMLHttpRequest();
}catch(microsoft){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
xhr=false;
alert("ajax not supported");
}
}
}
xhr.onreadystatechange= function () {
if(xhr.readyState==4 && xhr.status==200) {
results = xhr.responseText;
}
}
xhr.open("GET","db_interactions.php",true);
xhr.send(null);
alert("sent");
return results;
}
plants = eval('('+results+')');
document.write(typeof(plants));
</script>
</div>
</body>
</html>
You're issuing an asynchronous request. That means the function will return even when the data isn't ready yet. But your call assumes the JSON response is ready when getPlants is called. Which obviously makes results undefined because you aren't waiting for it.
Put your
plants = eval('('+results+')');
document.write(typeof(plants));
Inside the xhr.onreadystatechange function to make it work, or open the connection as synchronous
xhr.open("GET","db_interactions.php",false);
By the way, don't use eval to parse JSON because code may be injected maliciously. Use a JSON parser instead.

Categories

Resources