I am trying to upload an xml file to an external URL that will process the file and give feedback on any missing or incorrect information with that XML file. The feedback needs to be in XML format. I am trying to use XHR to do this. It seems I can make the call but the IT people at the remote site say they are not receiving the XML document. The remote site does send feedback with an error. Will someone take a look at my code to see if I have missed something? It is almost like there is a missing link between my form and the actual upload process. Thank you in advance for your help!
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var file = input.files[];
var fd = new FormData();
fd.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'External URL', false);
xmlHttp.onreadystatechange=function()
{
if((xmlHttp.readyState==4)&&(xmlHttp.status == 200))
{
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("Records");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;
}
}
xhr.send(fd);
</script>
<form action="External URL"
enctype="multipart/form-data" method="Post">
<input type="file" name="file">
<input type="submit" value="Upload File"/>
</form>
Related
Help guest...
i make web using framework Codeigniter and also using ajax XMLHttp Request to load some data from DB.
if i open the link Like this
localhost/web/topsales
every things is OK like this. Images
but if i add slash in end of url
localhost/web/topsales/
the result is error. Ajax load and duplicate the pages view like this image
i use AJAX XMLHttp Request for load the data:
function showdata()
{
var idunit = document.getElementById('idunit').value;
var month = document.getElementById('month').value;
var year = document.getElementById('year').value;
var xmlhttp;
document.getElementById("result").innerHTML = "<div class='text-center'>Loading...</div>"; //xmlhttp.responseText
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("result").innerHTML = xmlhttp.responseText; //xmlhttp.responseText
}
}
xmlhttp.open("POST","showresult",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("idunit="+idunit+"&month="+month+"&year="+year);
}
please i need help, thanks so much for some advice.
carica.html
<td>
<input type="file" size="30" onchange="preview()" id="upload_immagine">
</td>
<td>
<div id="divImmagine" > </div>
</td>
filejavascript.js
function preview()
{
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)
document.getElementById("divImmagine").innerHTML=xmlhttp.responseText;
}
image=request.getParameter("upload_immagine");
document.getElementById("divImmagine").innerHTML=image;
xmlhttp.open("POST","stampaAnteprima.php", false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("image="+image);
}
stampaAnteprima.php
<?php
$file_temp=($_FILES['image']['tmp_name']);
echo"$file_temp";
?>
The line of javascript image=request.getParameter("upload_immagine"); returns nothing. How do I get the value to pass to php and then read the file via $_FILES['image']['tmp_name'] in practice it would be image? Do you have any advice?
This will allow you to send files to php.
You can add more eventlisteners to display the upload progress and error handling.
function UploadPhoto(){
var file = document.getElementById('upload_immagine').files[0];
var formdata = new FormData();
formdata.append("image", file);
var req = new XMLHttpRequest();
req.addEventListener("load", function(event) { uploadcomplete(event); }, false);
req.open("POST", "stampaAnteprima.php");
req.send(formdata);
}
function uploadcomplete(event){
// Your php reply = event.target.responseText
}
I am working on a webpage that needs to store data on the server in a .json file.
Here is what I have tried so far:
Javascript code:
// variable j = our json
var j;
function loadDoc(){
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){
j = xmlhttp.responseText;
}
}
xmlhttp.open("GET","things.json",true);
xmlhttp.send();
}
loadDoc();
function rewrite(){
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
};
};
xhr.open("POST", "write.php", true);
xhr.send("data=" + j);
};
The PHP file:
<?php
$data = $_POST['data'];
file_put_contents('things.json', $data);
?>
Note, in other parts of my code the j variable is changed.
My problem is that after the PHP script is making the JSON file blank. Am I doing anything wrong? Is php receiving the JSON properly? If so, how can I fix that?
Cheers!
If you vote down, please tell me why.
To POST data like an HTML form, add an HTTP header with setRequestHeader(). (w3school page)
so it must be :
xmlhttp.setRequestHeader("Content-type","application/json");
I want php to return a value to ajax. I'm following W3 schools example but no joy.
Here is the javascript/ajax code:
function createReport() {
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) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).
It may be that the problem occurs because of the order that you set the ajax, you did:
XMLHttpRequest/onreadystatechange/open/send
is preferable (if you do not follow this order may occur several flaws in older browsers):
XMLHttpRequest/open/onreadystatechange/send
Note: do not worry, the "open(...)" does not start listeners.
Listeners only work after the "send(...)"
Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.
Try this:
<script>
function XHR(){
if(window.XMLHttpRequest){//outers browsers
return new XMLHttpRequest();
} else if(window.ActiveXObject){//IE
try{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(ee) {//IE
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee) {}
}
}
return false;
}
function createReport(){
var xhr = XHR();// call ajax object
if(xhr){
xhr.open("GET", "test.php", true);//setting request (should always come first)
xhr.onreadystatechange = function(){//setting callback
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("report").innerHTML=xhr.responseText;
} else {//if the state is different from 200, is why there was a server error (eg. 404)
alert("Server return this error: " + String(xhr.status));
}
}
};
xhr.send(null);//send request, should be the last to be executed.
} else {
alert("Your browser no has support to Ajax");
}
}
</script>
<div id="report">Report will be placed here...</div>
<script>
createReport();//prefer to call the function after its div#report
</script>
To prevent cache, replace:
xhr.open("GET", "test.php", true);
by
xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);
At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.
With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
Possible factors:
Missing <script></script> tags
Make sure you have JS enabled.
Make sure your browser supports it.
You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from W3 Schools Website (example) and slightly modified to prove this works.
Result when clicking on the Change Content button:
return this to ajax - as per your PHP code.
<!DOCTYPE html>
<html>
<head>
<script>
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 && xmlhttp.status==200)
{
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
Other possible factors:
If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
If on a hosted service, make sure PHP is available for you to use.
Files are not in the same folder as executed from.
try{
request = new XMLHttpRequest();
}catch(trymicrosoft){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request = false;
}
}
}
if(!request)
{
alert("Error initializing XMLHttpRequest!");
}
function Create_Ajax_Query(LinkToFile,Parametrs)
{
window.document.body.style.cursor='progress';
request = new XMLHttpRequest();
var url = LinkToFile;
var params = Parametrs;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = newinfo;
request.send(params);
}
function newinfo()
{
if(request.readyState==4 && request.status == 200){
window.document.body.style.cursor='default';
alert(request.responseText);
}
}
Hope its useful!
The code looks correct. it runs just fine on a local environment.
I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:
function createReport() {
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() {
console.log(xmlhttp); //to show the entire object after statechage.
console.log(xmlhttp.readyState); //to show specific parameter.
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
Below is the response from server (as per google chrome rest-client):
Below is the code snippet I'm using to post some data to our server. I want to get back data as xml ouput.
Keeping in mind the concept of same origin policy i uploaded this piece of code onto our sever as a html page, but not getting any response.
Is there anything wrong with my code or is my approach wrong?
<html>
<head>
<script type="text/javascript">
function getToken()
{
var xmlhttp;
var txt,x,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("stage 1");
xmlhttp.onreadystatechange=function()
{
alert("stage 2");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("stage 3");
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("token");
alert("stage 4");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML=txt;
}
}
alert("stage 5");
xmlhttp.open("POST","http://abc.mysite.com:9090/myapi/xxx",true);
xmlhttp.send("op=login&pass=xxx");
}
</script>
</head>
<body>
<center><h2>UserPreview:</h2></center>
<br />
<div id="myDiv"></div>
<br />
<button type="button" onclick="getToken()">GetToken</button>
<div data-role="footer" data-position="fixed" data-theme="a"><h4>Ver: 1.1(17112)</h4> </div>
</body>
</html>
<response><token>8768768768768768</token></response>
You have to take into account that: for AJAX calls, you can only access the same hostname (and port / scheme) as your page was loaded from. The same domain always and the same PORT:
How exactly is the same-domain policy enforced?
In the past I use this for the IE version, I suppose for possible compatibility issues:
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
I always put the code like this:
var THEURL="http://mysite.abc.com:8080/myapi/xxx"
var data="op=login&pass=xxx";
http.open("POST",THEURL, true);
http.onreadystatechange = function(){
};
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", data.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(data);
Can't you use jquery? It is much more efficient.
To make an ajax call:
http://api.jquery.com/jQuery.ajax/
For example:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
The sooner you use Jquery the sooner your work will get faster.
If the element called token in your xml file is an xml element, and not an attribute then you replace the following lines by -
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
by -
txt += (window.ActiveXObject)?x[i].childNodes[0].text : x[i].childNodes[0].textContent;
I didn't ask you wheter your XHR is returning you the XML properly or not.