How to react on Response from a form post in JavaScript - javascript

I want to create a Login-Screen in HTML where the user can fill out his username and password. After that he sends the Data with a submit to the server which validate the data. If the Login is correct he sends back a message in JSON format with an id, like this:
{"id":"37"}
Now my question: How can i get this information in Javascript? I want to check the id and, if it's OK, redirect the user to a new HTML screen.
I'm working with PhoneGap to create a Android Application, so the only things I can use are HTML, CSS and JavaScript. To send the POST i use the HTML <form> tag, not a special JavaScript. If I test it in Firefox it works, I fill out my Username and Password and then the Message with the id is shown. Now I want to react on this response with JavaScript. Can somebody help me?
AJAX Code:
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) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST",url,true);
xmlhttp.send(login);

A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.
var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a function that will be called for every key and value at every level of the final result.
now access the id property like myObject.id

Related

Cannot read property 'getElementsByTagName' of null

I've been searching around for answers to this particular problem for about two days now. I can't seem to figure out what's going on with it. All this seemed to have worked in the past but isn't working anymore.
XML:
<ZipCodes>
<results>
<city>Chicago</city>
<state>IL</state>
<timezone>-6</timezone>
</results>
javascript:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","_checkzip.php?zip="+str,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("results");
i=0;
document.forms["signup"]["City"].value=(x[i].getElementsByTagName("city")[0].childNodes[0].nodeValue);
document.forms["signup"]["states"].value=(x[i].getElementsByTagName("state")[0].childNodes[0].nodeValue);
document.forms["signup"]["TimeZone"].value=(x[i].getElementsByTagName("timezone")[0].childNodes[0].nodeValue);
and the error I get is
Cannot read property 'getElementsByTagName' of null
when I try x=xmlDoc.getElementsByTagName("results"); The xml is deffinetly coming in on the network response when I look at the debug in Chrome.
You can use an event handler on an XMLHttpRequest's onreadystatechange to make sure the request is done. If the status of readyState is 4, the operation is complete.
Currently you're asking for data that hasn't been transmitted yet.
Apart from ensuring that xmlhttp.readyState==4 && xmlhttp.status==200, this error can also occur if you outputed any content, letter, character or string before sending your xml data from the server. For instance Assuming that in java you have a method/function called sendXMLdata, and then in your servlet you printed the string "connected" before calling the method:
....
out.println("Connected");
String data="My Name"
sendXMLdata(response,data);
....
Then the output when viewed from browser source will be this:
Connected
My Name
So this will certainly give you an error since the browser would not be able to parse the string "connected" since it is not the write format to render xml data.

Loading a text file into javascript

I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.

Send or get data from mysql using php ajax jquery - what is the secure method?

I have use Ajax and jquery for get data from database and send data, but when we use ajax or jquery methods, web page source view ,we can see details like below;
Ajax
<script type="text/javascript">
function showUser()
function showUser()
{
var str = document.getElementById('txtusername').value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="<span style='color:#FFF;font-size:10px;'>Enter username</span>";
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","chkusername.php?q="+str,true);
xmlhttp.send();
}
</script>
In here you can see the get method and what are the sending values and also more things. I want hide these thing from source view, help me ..
You can't. Anything on the client side (HTML, CSS, JavaScript) is free for the user to see.
That's why anything security-related is on the server side, where it can be trusted (for the most part).
It's not a security risk if the user knows that to log in you go to /chkusername.php?q=username (or whatever). It is one, however, if you don't properly sanitise the input.

Get a PHP variable with javascript?

I have a Javascript game running within a HTML5 canvas. Now I'd like to pass on a variable that is stored in an object in PHP to my program. What I'd like to have would be a function in my js like getVariable = function(){script that gets the variable from PHP and returns it as a string}
Any hints?
#Valentin - simply use javascript ajax call(Or jquery call if you like) to get the values from the php script. If your game has different values for different players you can start a session and persist the values across many calls to the script.For example -
Let say you want to get the health of the player from player.php which looks like
session_start();//start the session
if(!isset($_SESSION['health']))
$_SESSION['health'] = $var;//If there is no value for player health in the session
//initialize the default value
switch($_GET['x']){
case 'health' :
echo $_SESSION['health'];
break;
default :
echo $var;
break;
}
?>
and the corresponding pure javascript would be -
var health;
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)
{
health=xmlhttp.responseText;
}
}
xmlhttp.open("GET","player.php?x=health",true);
xmlhttp.send();
You could do the same in a much simpler fashion using the awesome jQuery -
var health;
var reqData=["x" : "health"];
var xhrObj = $.get("player.php",x)
.done(function( response ) {
health=response;//The echo text from server
})
.fail(function() {
alert('error');
});
You can learn more about jquery and ajax here -->
jQuery API
www.w3schools.com/ajax/‎ for the ajax tutorial
Javascript and the browser don't care what language you're using on your server to generate the HTML/JS, all they care about is what is generated in the end.
To do what you're thinking, you'd have 2 ways to do it:
Print the contents of the variable to the page when initially generating it.
Use an AJAX call to a script on your server that echo's the value, then parse it in JavaScript. If you do this, though, you'd have to use the session or a database, or another means of keeping state between pages.

Run entire PHP-file from Javascript with AJAX

on $(document).ready(function() in index.php, the below AJAX is executed, running the file getData.php:
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("dataSuccess").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getData.php",true);
xmlhttp.send();
In the getData.php file, data is gathered from MySQL and put in JS-arrays:
var guestData = new Array("<? for ($j=0;$j< sizeof($guestData);$j++) { print ($guestData[$j]); ?>","<?php } $j = $j+1; ?>");
And finally, store the data in my js arrays into LocalStorage:
var guestDataCols = new Array();
guestDataCols = guestData[0].split(",")
var arrayIndex=0;
for(arrayIndex=0;arrayIndex<guestData.length-1;arrayIndex++)
{
localStorage.setItem(arrayIndex, guestData[arrayIndex]); // storing
}
EVERYTHING works! But the problem is that my AJAX code doesn't seem to run through the entire getData.php file since LocalStorage in yet empty after the php-file is executed via AJAX. However (and this is a big one), if I simply refresh getData.php in another window, data is stored perfectly and evernything works. I've also tried using jQuery for this as suggested in another Stack Overflow question
$('#dataSuccess').load('getData.php'); //instead for the AJAX code
but with the exact same and somewhat mediocre result. So my questions is, why isn't the AJAX script running the entire php file and HENCE, why is no data stored in LocalStorage?
JavaScript on an HTML page is not run when called by an XMLHttp request. The browser doesn't parse the pages that JavaScript receives over XMLHttp requests and therefore does not run the JavaScript. You would have to output to the browser for it to be run. Your best bet would be do have the PHP return the data you need and then extract it from the XMLHttp request. For example, the getData.php could return a JSON string containing the data you need. Then on the page with the XMLHttp request, you could parse that JSON string and save it to the localStorage on that page.
I think you're looking for jQuery.getScript

Categories