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

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.

Related

JavaScript and CSS files won't work in html (spring boot app)

I have a problem with a html file not 'loading' js and css files properly. This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create new snippet</title>
<script src="static/js/send.js"></script>
<link rel="stylesheet" href="static/css/button.css">
</head>
<body>
<textarea id="code_snippet" placeholder="//write your code here"></textarea><br/>
<button type="submit" onclick="send()">Submit</button>
</body>
</html>
It is supposed to take some input into the textarea tag and send it to a database when you click on the button. However, the function send() doesn't work at all. Also, the linked CSS doesn't work as well. This is my project structure:
This is the send() function:
function send() {
let object = {
"code": document.getElementById("code_snippet").value
};
let json = JSON.stringify(object);
let xhr = new XMLHttpRequest();
xhr.open("POST", '/api/code/new', false)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
if (xhr.status != 200) {
alert("Something went wrong!");
} else if (xhr.status == 200){
alert("Success!");
}
}
This function works fine when I put it inside of script tag
You should make sure the links are relative or absolute to the home directory.
/absolute path
and use without "/" for relative path
try to access css and js file links from browser.

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');

Not getting a response on MDN AJAX example

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.

having a minor issue with this javascript+ajax

am trying to translate information, when i use the following code, it runs successfully, as i have given the textarea information in prior
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax POST</title>
<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID, tolang) {
if(tolang=="-")return;
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var the_data = 'data='+document.getElementById('txt2').innerHTML+'&to='+tolang;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<textarea id="txt2" rows="20" cols="50">hi wassup</textarea><br/>
<select name="langlist" onchange="ajaxrequest('translator.php', 'txt2', this.options[this.selectedIndex].value)">
<option value="-" selected>-</option>
<option value="ar">Arabic</option><option value="bg">
Bulgarian</option><option value="ca">
Catalan</option><option value="zh-CHS">
Chinese Simplified</option><option value="zh-CHT">
Chinese Traditional</option><option value="cs">
Czech</option><option value="da">
Danish</option><option value="nl">
Dutch</option><option value="en">
English</option><option value="et">
Estonian</option><option value="fi">
Finnish</option><option value="fr">
French</option><option value="de">
German</option><option value="el">
Greek</option><option value="ht">
Haitian Creole</option><option value="he">
Hebrew</option><option value="hi">
Hindi</option><option value="mww">
Hmong Daw</option><option value="hu">
Hungarian</option><option value="id">
Indonesian</option><option value="it">
Italian</option><option value="ja">
Japanese</option><option value="ko">
Korean</option><option value="lv">
Latvian</option><option value="lt">
Lithuanian</option><option value="no">
Norwegian</option><option value="pl">
Polish</option><option value="pt">
Portuguese</option><option value="ro">
Romanian</option><option value="ru">
Russian</option><option value="sk">
Slovak</option><option value="sl">
Slovenian</option><option value="es">
Spanish</option><option value="sv">
Swedish</option><option value="th">
Thai</option><option value="tr">
Turkish</option><option value="uk">
Ukrainian</option><option value="vi">
Vietnamese</option>
</select><img src="http://www.allsaints-sec.glasgow.sch.uk/Images/QuestionMarkIcon16.gif" title="plz save your copy of data, as there will be chances of data loss during translation"/>
</body>
</html>
if you remove the text in textarea before initial load of page, then the translation is not working, as shown in below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax POST</title>
<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID, tolang) {
if(tolang=="-")return;
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var the_data = 'data='+document.getElementById('txt2').innerHTML+'&to='+tolang;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<textarea id="txt2" rows="20" cols="50"></textarea><br/>
<select name="langlist" onchange="ajaxrequest('translator.php', 'txt2', this.options[this.selectedIndex].value)">
<option value="-" selected>-</option>
<option value="ar">Arabic</option><option value="bg">
Bulgarian</option><option value="ca">
Catalan</option><option value="zh-CHS">
Chinese Simplified</option><option value="zh-CHT">
Chinese Traditional</option><option value="cs">
Czech</option><option value="da">
Danish</option><option value="nl">
Dutch</option><option value="en">
English</option><option value="et">
Estonian</option><option value="fi">
Finnish</option><option value="fr">
French</option><option value="de">
German</option><option value="el">
Greek</option><option value="ht">
Haitian Creole</option><option value="he">
Hebrew</option><option value="hi">
Hindi</option><option value="mww">
Hmong Daw</option><option value="hu">
Hungarian</option><option value="id">
Indonesian</option><option value="it">
Italian</option><option value="ja">
Japanese</option><option value="ko">
Korean</option><option value="lv">
Latvian</option><option value="lt">
Lithuanian</option><option value="no">
Norwegian</option><option value="pl">
Polish</option><option value="pt">
Portuguese</option><option value="ro">
Romanian</option><option value="ru">
Russian</option><option value="sk">
Slovak</option><option value="sl">
Slovenian</option><option value="es">
Spanish</option><option value="sv">
Swedish</option><option value="th">
Thai</option><option value="tr">
Turkish</option><option value="uk">
Ukrainian</option><option value="vi">
Vietnamese</option>
</select><img src="http://www.allsaints-sec.glasgow.sch.uk/Images/QuestionMarkIcon16.gif" title="plz save your copy of data, as there will be chances of data loss during translation"/>
</body>
</html>
am not getting the point in here, can anyone tell me why is this problem.
It probably doesn't work, because document.getElementById('txt2').innerHTML is null when you remove text from textarea. Check this function in firefox&firebug for possible errors/warnings. You could also provide some more data about your problem - what exactly happens.
I don't know really why it doesn't work. In fact your code changing innerHTML in the first example just work the fist time on chrome, and in a old IE both work always.
And I don't think innerHTML belongs to a W3C standard, if you change to value both will work always. Like:
var the_data = 'data='+document.getElementById('txt2').value+'&to='+tolang;
and
document.getElementById(tagID).value = request.responseText;
EDIT:
Writing standards compliant code is allways good =)

data transfer using JSON

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

Categories

Resources