I am trying to get a piece of data from server using JSP technology. I am using JSON object to do so. On client side i am using XMLHttpRequest to get the data.
To check whether it works properly, i wrote a piece of code as follow:
<head>
<script type="text/javascript">
function test(data) {
if(data){
var jsonObj= eval('(' + data + ')');
var Question= jsonObj.Question;
document.write(Question);
}
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseText != null && this.responseText)
// success!
test(this.responseText);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
function xyz(){
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("POST", "fetch.jsp", true);
client.send();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br><br><input id="Q" type="button" onclick="xyz()" >
</body>
on server side i did as follow:
<%#page import="net.sf.json.JSONObject"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% JSONObject jsonObj= new JSONObject();
jsonObj.put("Question","What is your name?");
jsonObj.put("Opt1","ji");
jsonObj.put("Opt2","ji");
jsonObj.put("opt3","ma");
jsonObj.put("opt4","sa");
String str= jsonObj.toString();
response.setContentType("text/plain");
response.getWriter().write(str);
%>
Unfortunately i am not able to get the response.
You are writing your JSON into the body of an HTML document, and then sending the HTML document as the response.
Don't do that. The response should be just the JSON.
You need to write with content type application/json.
Also don't use eval in test function.
When the data is json the test function can access the data as the json object!
In the event of parsing a string use.
JSON.parse(string).
But don't use eval
Related
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');
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
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
So i'm trying to parse this json with javascript and it reads it from the webpage correctly however it just freezes when reaching the JSON.parse.
Here's what the webpage outputs:
{
Players: 18,
maxPlayers: 32,
Map: "jb_summer_redux_v3"
}
Here's what the full code is:
var xhr = new XMLHttpRequest();
var url = "http://in.nickparksdev.com/info.php";
document.write("Loading....");
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.write(xhr.responseText);
var jsonResponse = JSON.parse(xhr.responseText);
document.write("Test: " + jsonResponse.Players);
}
}
xhr.send();
Here's what that document.write(xhr.responseText); outputs:
{"Players":19,"maxPlayers":32,"Map":"jb_summer_redux_v3"}
Any help on this would be great :)
Your page return HTML not JSON
Output :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Players</title>
</head>
<body>
{"Players":15,"maxPlayers":32,"Map":"jb_summer_redux_v3"}</body>
</html>
You have to output only the JSON not HTML.
In my testing, JSON.parse does return the correct object from that string. However, your file is HTML with JSON in it.
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.