I have an ajax/php application which you can download from dropbox.
it's here:
https://www.dropbox.com/sh/zkca8peed97ieiu/AABwKVf_vP6s0BnQpxCcAeWZa?dl=0
the HTML code is rendered but the div tag isn't as I think the page is not interactive because the javascript file foodstore.js won't render.
Does anyone know any fixes?
The app should when typed in tell you whether the current product is in stock or not with the div tag underInput.
Here's the javascript then HTML,
//Create object that's responsible for communicating with server behind the scenes.
var xmlHttp = createXmlHttpRequestObject(); //a function name which is to be built now.
//awesome object which allows you to communicate with server without having to
//refresh the page.
function createXMLHttpRequestObjecct() {
var xmlHttp;
//work for IE!
if(window.ActiveXobject){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
xmlHttp = false;
}
} else { //work for other browsers
try {
xmlHttp = new XMLHttpRequest(); //built-in function doesn't need to be coded itself.
}catch(e) {
xmlHttp= false;
}
}
if(!xmlHttp)
alert("Unfortunately we cannot create the object");
else
return xmlHttp; //function needs return statement otherwise variable won't equal anything
}
/*----------------------------------------SAMPLE CODE FOR EVERY AJAX PROGRAMME ABOVE -------------------------------*/
//Heart of being able to communicate to the server with ajax.
function process() {
//this process function is responsible for taking the object created above
//and sending the request to the server
//xmlhttp is the object we are testing for.
//if 0 and 4 it means the object is free and ready to communicate with server
if(xmlHttp.readyState==0 || xmlHttp.readyState==4) {
food = encodeURIComponent(document.getElementbyId("userInput").value);//document is webpage .value
//is the value that the user types into the input box.
//build-in function to communicate with the server
xmlHttp.open("GET", "foodstore.php?food="+food,true);//creates request to send to the server.
//As php accepts info one of two ways ie GET and POST
//false/true if ajax request should be done asynchronously as in without refreshing the page.
//.open function creates the type of reqeust that we want.
//Communicate with the webserver
xmlHttp.onreadystatechange = handleServerResponse;
//Send to the server
xmlHttp.send(null); //the parameter used is only used with post. we are using get, that's why it's null.
}else {
setTimeout('process()',1000); //is object ready to communicate or busy.
//if busy wait and try again.
}
}
function handleServerResponse() {
//Server will send an XML file in between the <response> tags.
//first we check object for errors.
if (xmlHttp.readyState==4) {//state no.4 when object is done communicating with the server
if (xmlHttp.status==200) { //200 means that communication went okay with the server.
xmlResponse=xmlHttp.responseXML; //extracting xml from foodstore.php so the
//xml response is basically the new xml.
xmlDocumentElement = xmlResponse.documentElement;//documentelement is the root
//element of the xml file. the document element is where we pull everythin else
//from.
message = xmlDocumentElement.firstChild.data; //.data gets data from xml file
//gets the message from the server, in between the response tags.
//Set the inner html, part that shows to the user equals to a blue color messag.e
document.getElementbyId("underInput").innerHTMl = '<span style="color:blue">' + message + '</span>'; //innerHTML is html inbetween the div
///the stuff that shows on the webpage.
setTimeOut('process()',1000);
} else {
alert("Something went wrong!");
}
}
}
//STEPS:
//1. Creates the object for communication
//2. Communicatse with the server
//3. Update your webpage, create an element or do something cool
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()"> <!--Function will be inside javascript and will kickstart ajax programme. -->
<h3>The Chuff Bucket</h3>
<p>Enter the food you would like to order:</p>
<input type="text" id="userInput"/>
<div id="underInput">
</div>
</body>
</html>
and here's the PHP file from the project file , it's foodstore.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
header('Content-Type: text/xml'); //we're going to be generating xml content.
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food']; //store user data in this variable.
//can send things to PHP in one of two ways using either get or post.
//we use get because it's more simple.
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food,$foodArray))//takes two params. name of variable and the array itself.
echo 'We do have '.$food.'!';
elseif($food=='')
echo'Enter a food you idiot';
else
echo'Sorry we have none of '.$food.'in stock!';
echo '</response>';
?>
And basically when you type something in it should tell you whether that item is in stock or not. It won't do that and I can't quite understand why.
I have double checked that the code is typed in correctly. Have I made any syntax errors?
Kind regards,
Related
I have a html page called index.html. Inside it I use js to send JSON to other page (loja.html) and right after that I load this page. I would like to read the contents of JSON on loja.html and use it to populate some html tags. Here's my code:
piece of index.html's
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
}
}
ajax.open("GET", "http://localhost:8080/DBRest/loja.html",true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(dataToJSON(nome,idade));
console.log(dataToJSON(nome,idade));
window.location = 'http://localhost:8080/DBRest/loja.html';
piece of loja.html's js:
window.onload = function() {
alert('alert');
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
alert(JSON.parse(ajax.responseText));
}
}
}
When I load loja.html from index.html none of alerts are displayed. when typed on browser, only first alert is displayed. How can I correctly send data to loja.html from index.html and after it immediately load loja.html?
Javascript lives/executes within the current browser window/location; if loja.html isn't currently loaded, it won't do anything as the javascript on that page hasn't been run. You'll need a server-side component to accept the GET (not POST) request that you're making and store the data. loja.html can then load that via Javascript.
You have a few options to move data between pages:
Store Data in Local Storage
Store Data in a cookie
Add data to the URL via query parameters
Query the database on the new page to retrieve the data.
Without using a SPA, there isn't a direct way to move data from one html page to another html page.
I'm abit confused as to how i will go about doing this, so i'm making a .js file to collect data on a page(100% with js) and i want to POST it to a php file which will then take care of it and insert it into the db etc..
How will i go about doing this? I know you can use jquery in a html document, but i want to use it in a .js file not a .html file.
I've successfully done it using a .html file and importing the jquery file, but i want to do it all in a .js file.
Any help is greatly appreciated. Thank you very much (:
I'd comment, but I can't. Can you post some samples of your code?
What I got is that you are using JavaScript (jQuery) to POST (form data?) over to a PHP file. If you want to use jQuery inside of a .js file, all you have to do is include the jQuery library before you include your .js file, like so:
<script src="jquery.js"></script>
<script src="myExternalScript.js"></script>
And then, inside of myExternalScript.js, you can use jQuery methods.
The external script is aware of your DOM elements, really, just like inline JavaScript would be, so you can still do whatever you want with your form or wherever you are getting the data to POST from.
EDIT: (in accordance to what you commented on this answer)
EDIT 2: I had forgotten to add the request header for POST
If you want to send an AJAX POST request (notice that I set the Content-Type request header, so that the data gets sent correctly):
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://zegita.tk/stargazer/magic.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("n="+user);
If you want to send an AJAX GET request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://zegita.tk/stargazer/magic.php?n="+user, true);
xmlhttp.send();
It is important that you use the correct method, depending on whether you are using $_GET or $_POST in your magic.php file.
Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)
<script type="text/javascript">
function sendJSValsToPHP(){
var xmlhttp;
//These are the variables i am going to post to illustrate the example, what you want
var var_1toPost = 1;
var var_2toPost = 2;
var var_3toPost = 3;
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)
{
//You can get the response text from abc.php file and process it in any of the tags you want by javascript code
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
xmlhttp.send();
}
</script>
The echo'ed data in abc.php will come in the div="myDiv" //as a response.
<body>
<div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
the things echo'ed in abc.php will come in this div
</div>
<button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>
and then in abc.php //file
<?php
$recieved_1 = $_GET['recieve_1'];
$recieved_2 = $_GET['recieve_2'];
$recieved_3 = $_GET['recieve_3'];
//Do your processing here and insert it in the database
//Insert Query OR Update Query (whatever)
// after you have inserted you can get the response in
// the <div> having id="myDiv" Or whatever you want
// Suppose you have successfully inserted data then
$insertedDataBoolean = true;
if($insertedDataBoolean){
echo "Data: " . $recieved_1 . ", " . $recieved_2 .
" and " . $recieved_3 . " inserted successfully.";
}
else{
echo "Data-insertion error.";
}
?>
I am maintaining a console log on my web page to display errors/exceptions and success cases as shown below
So once the user selects valid files and uploads them, a servlet uploads files and returns uploaded path to the console like this
As you can see in my second image the console is also refreshed loosing all the previous messages, I don't want this to happen. How do I do this?
I am populating the div tag with holds the console as follows from JS
else if(FileName1 == FileName3 || FileName1 == FileName4 || FileName2 == FileName3 || FileName2 == FileName4)
{
var err1 = document.getElementById("box");
err1.innerHTML = "Configuration file and Geco script should not be the same as left or right files. Please check your uploads";
err1.style.color = "Red";
}
//else if(FileName1.value)
else
{
var scc1 = document.getElementById("box");
scc1.innerHTML = "Uploading files, the page might refresh";
scc1.style.color = "Blue";
document.myform.submit();
}
the the DIV tag which holds console gets values from servlet as follows
<div id="box">${f1stat}<br>${f2stat}<br>${f3stat}<br></div>
Servlet sends response as follows,
String f2 = "Uploaded file " +fileName+ " at " +uploadedFile.getAbsolutePath();;
request.setAttribute("f2stat", f2);
RequestDispatcher rd = request.getRequestDispatcher("geco.jsp");
rd.forward(request, response);
Finally, all I want to do is to avoid console refresh so that it will not loose its message history.
How to do this?
You could rewrite the upload logic to use ajax request - it's not a lot of work with javascript - use FormData and XMLHttpRequest to send the data to the server, and you'd need to convert your servlet to a web service.
On the other hand, you may attach the already generated data from the console in the request and return them from the servlet (in the current configuration), then prepend them to the new response.
I am currently contracted to a place that cannot use a CMS or PHP, but they want me to build something like a CMS using HTML and JavaScript.
I know it sounds ridiculous but I do not want to be searching for another job these days and they are the nicest people that I have ever worked for - EVER - and I old.
One of the concepts of a CMS is to have global files that you can include at any given time.
As a result, I tried the $.ajax, $.get, etc..., but I was running into issues of Access URI denied and those kind of things for trying to load a file which is one directory level the current directory.
I was able to get the javascript file to load by using the old XMLHttpRequest/ActiveXObject.
However, the script within the div that has been loaded cannot be called. I receive an error of "Can't find variable: mFunc" which is the name of the function that has been loaded into the div.
Here's the code for my html:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>retrieve local file one level up</title>
<script type="text/javascript">
<!--
var createRequestObject = function(){
var req;
if(window.XMLHttpRequest){
// Firefox, Safari, Opera...
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
// Internet Explorer 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert('There was a problem creating the XMLHttpRequest object');
}
return req;
}
// Make the XMLHttpRequest object
var http = createRequestObject();
var sendRequestPost = function(){
var jscript = '../test.js';
// Open PHP script for requests
http.open('GET', jscript);
http.setRequestHeader('Content-Type', 'text/javascript');
http.onreadystatechange = handleResponsePost;
http.send(null);
var mT = setTimeout("mFunc()", 2000);
}
var handleResponsePost = function(){
if(http.readyState == 1){
document.getElementById('mDiv').innerHTML = "Please wait, loading... " ;
}else if(http.readyState == 4 && http.status == 200){
// Text returned from PHP script
var response = http.responseText;
document.getElementById('mDiv').innerHTML = response;
if(response){
// Update ajaxTest2 content
document.getElementById('mDiv').innerHTML = response;
}
}else if(http.readyState == 2){
document.getElementById('mDiv').innerHTML = http.responseText;
}else if(http.readyState == 3){
document.getElementById('mDiv').innerHTML = http.responseText;
}
}
-->
</script>
</head>
<body onload="javascript:sendRequestPost();">
<div id="mDiv"></div>
</body>
</html>
Here is the javascript that loads just fine into mDiv:
<script type="text/javascript">
<!--
var mFunc = function(){
var mScript = document.createElement("script");
mScript.setAttribute("type","text/javascript");
var data = 'alert("gets here");'
mScript.text = data;
var head = document.getElementsByTagName("head")[0];
head.appendChild(mScript);
}
-->
</script>
Yet, after the two seconds have passed, I receive the error.
I am sure that it is probably because the browser just sees this as text within the div, so how do I make it recognize that it is javascript.
I have tried using eval, which I do not want to use, but even returns a parse error.
Thanks in advance
../ has meaning to the local filesystem (on most platforms), but not to HTML or to most webservers. Remember that the URL is just a query string for the server.
Generally speaking, you need to parse the URL to remove the undesired few elements. If you just want scripts that are common across the website, though, they should be referenced from the root, so the relative URL would begin with /.
A quick hack would be /(.*)\/.*/.exec( '/foo/bar/baz.html' )[1]. This doesn't handle the query string following ? or anchor following # but you won't have a query on a static website, and won't have anchors until you get into more advanced techniques. jQuery has a better utility for parsing URLs, also based on regexps.
It's offtopic for this site, but you will have to be very familiar with XHR to implement a JavaScript CMS.
OK, another programmer that I work with, has found a simple solution.
Instead trying to use ajax to load a JavaScript file from a higher directory level and then run a document.writeln or document.getElementById("someDiv").innerHTML -- reverse the steps.
Include the JS file as you would normally:
<script type="text/javascript" src="../../common/header.js"></script>
Within this JS file
function CommonHeader(mPath) {
document.writeln('<header>');
document.writeln(' <div class="PageWidth">');
document.writeln(' <h1>Something<sup>®</sup> <em>Learn about us</em></h1>');
document.writeln(' <nav>');
document.writeln(' <ul>');
document.writeln(' <li id="loginOut"></li>');
The order needs to be for you to call document.writeln at the beginning of the process.
We can now load header.js, footer.js, and whatever other file that we wish to load, along with having an array at the top of each page denoting the path to those files, for lower directory level htmls
dynamicPathArr[0] = "../../";
Then within whatever file, you can call the function to write the date into the page
<script type="text/javascript">CommonHeader(dynamicPathArr[0])</script>
I cannot believe that I did not think of this completely simple solution.
Although this is not SEO friendly, it is good for only updating header, footer, nav, etc... in one location, until everything is finalized.
And thanks you for the response
I have the following code:
xmlDoc=loadXMLDoc("dbbackup.xml");
x=xmlDoc.getElementsByTagName("record");
alert(x);
for (i=0;i<3;i++) {
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
alert("x : "+x[i]);
alert("newtext :"+newtext.nodevalue);
x[i].appendChild(newel);
alert("sd");
}
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
I have created dbbackup.xml in the same location and the XML file looks like:
<sticky>
<record></record>
</sticky>
But after running my script the xml file is not getting updated.
Javascript cannot modify files on disk, it only runs for the client in the client's web browser.
To actually write to and from files on a server, you have to use server-side languages and technologies, like PHP or ASP.
I made this - making XML at client side then using everyday praksis
Mike
function makeSlot() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) showBon(); }
xmlhttp.open("POST","crMakeSlot.php",true);
xmlhttp.send(wrapUp());
}
/***
* make the final transaction - using XML
*/
function wrapUp () {
var transaction = document.implementation.createDocument("","", null);
var operator = document.createElement("operator");
var textblok1 = document.createTextNode(document.getElementById("rText").value);
operator.appendChild(textblok1);
var root = document.createElement("transaction");
root.setAttribute("tstamp", now);
root.setAttribute("sequenceno", zSequenceNo.textContent);
if (parseInt(document.getElementById("zDankort").value) > 0) root.setAttribute("dankort", document.getElementById("zDankort").value);
if (parseInt(document.getElementById("zCash").value) > 0) root.setAttribute("cash", document.getElementById("zCash").value);
if (parseInt(document.getElementById("zCredit").value) > 0) root.setAttribute("credit", document.getElementById("zCredit").value);
if (parseInt(document.getElementById("zCheck").value) > 0) root.setAttribute("check", document.getElementById("zCheck").value);
if (parseInt(document.getElementById("zGiftcard").value) > 0) root.setAttribute("giftcard", document.getElementById("zGiftcard").value);
if (parseInt(document.getElementById("zVoucher").value) > 0) root.setAttribute("voucher", document.getElementById("zVoucher").value);
root.appendChild(operator);
var divObj = document.getElementsByTagName("div");
/***
* when column value is 4, then we have our data complete - next cycle
*/
for (ix = 0; ix < divObj.length; ix++) {
switch (divObj[ix].getAttribute("column")) {
case "1": var row = document.createElement("row"); row.setAttribute("item",divObj[ix].textContent);
case "2": row.setAttribute("price",divObj[ix].textContent);
case "3": row.setAttribute("quantum",divObj[ix].textContent);
case "4": root.appendChild(row);
default: break;
}
}
transaction.appendChild(root);
return(transaction);
}
SomeKidWithHTML is right.
JavaScript is designed to only modify a file, in memory, that is loaded inside a browser framework.
Think of the browser as a sandbox that your kids (html, xml, etc.) can play in. As long as Johnny (xml) is in the sandbox playing, all is well. But if Johnny were allowed to play outside of that sandbox, just think of the havoc that could be done on your machine by websites.
There is NO WAY a JavaScript can permanentally affect a file on your local machine, by itself. It can only play inside the sandbox (locally, it can make calls to Java, or an other API, to affect change, but that's a whole other deal).
JavaScript is client side only. If you expect it to affect a server, it can only do it through calls back to the server. At the server you will need some kind of programming (asp.net, java, php, html, others) to receive and answer that call and do something with it.
JavaScript, by itself, is very powerful... but only inisde the sandbox (browser). For it to affect anything else outside of that browser it must depend on other programs already in place and ready to receive those requests.
And this is all in the name of security, mostly.
You can collect data from the web page in client side and send them to the server (ajax), which will then generate the xml file and send back a link to the file (ajax). Use javascript to generate a download link using the link returned by the server.
This is the way I do to solve the problem in one of my project.