Upload file with AJAX - ajax

I have the script:
#
var xmlhttp;
var params = "file=Not sure what is it";
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if (xmlhttp.status==200)
alert('Upload done');
else
alert('Error!!!');
}
}
xmlhttp.open("POST", "http://localhost/ajax2.php", true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
#
This script send a POST request to server, now I just wonder that how can I set params as a file content to upload?

You can't do this solely with JavaScript, for security reasons. Try SWFUpload, Uploadify, or similar. These are Flash-based solutions that you can interact with via JavaScript.

Look how this library does it

Related

Taking value from text-field and sending it with AJAX request Javascript

I am trying to sync both client-side and server-side scripts that the client intakes a value from the textbox and sends it to the server, upon which the server displays that input as a cookie.
Here is the code that I have so far
function loadCookie() {
//[1] make a new request object
var xhttp = new XMLHttpRequest();
//[2] set the request options
xhttp.open("GET", "index.html", true);
//[3] define what you will do when you ge a response (callback)
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input_response").innerHTML = this.responseText;
}
};
//[4] finally send out the request
xhttp.send();
}
I have the and the button but I am having issue of the page re-loading itself instead of taking the value of the input and showing it as a cookie in the server. I'm suspecting it is having to do with the URL by the index.html

Send post data from Phonegap (Cordova) to server

I have a form in my Cordova app:
<form id='transport' method='POST' action='' enctype='application/json'>
<input type='hidden' id='data' name='data' value='' />
</form>
and I sent to server (pure js):
postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';
document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user/';
document.getElementById('transport').submit();
but the data variable is empty when received on server.
On server I'm using Codeigniter.
Works perfectly in a web scenario, why not in Cordova? I know there is not the cross-domain problem, and I have allowed all domains (*) in config.xml.
Thanks.
Fixed! Just remove te slash (/) at the end of the URL.
This is because Codeigniter - with this slash - is expecting another parameter (due to its nature url-based) and if there is not, all the variables inside the controller (such as POST data) are null.
So this:
postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';
document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user';
document.getElementById('transport').submit();
it's correct.
You can achieve this with pure JS by using xmlhttp.
This one omits the wrapping of the data variable, so you get first_name and last_name as their own parameters.
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
params = "first_name=" + first_name + "&last_name=" + last_name;
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
You can also send the data as JSON like this:
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//Not sure if you need the Content-length here or not.
xmlhttp.send(JSON.stringify({"data"=>{"first_name"=>first_name, "last_name" => last_name}}));
}
I find this approach cleaner than using an invisible form when it isn't really needed.

Looking for an extremely simple AJAX script

I need a very basic, simple and lightweight AJAX script.
Does anyone have a shell of such a script they can share?
Here's what I have:
I have a PHP script on the server that echo's the current date and time on the server
I just need the javascript that calls the php script and loads the echoed text string into a js var so I can use it in my app
(the reason I need the server's clock is that all visitors to the site have to work off the same clock. The app does not work for visitors outside the server's timezone.)
Thanks for helping out.
JQuery is perhaps the right answer for AJAX but you can also do this in plain old Javascript as follows:
<html>
<head>
<script type="text/javascript">
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");
}
//the callback function to be callled when AJAX request comes back
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("POST","<<url of web address>>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
You can find a simple example here:
AjaxCall = function(Data, WebServiceURL, Callback) {
var request;
var url = WebServiceURL;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
Callback(request);
} else {
alert("Sorry, an error occurred. " + request.responseText);
}
}
};
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(Data);
} else if (window.ActiveXObject) {
url += "?" + Data;
request = new ActiveXObject("Microsoft.XMLHTTP");
if (request) {
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
Callback(request);
} else {
alert("Sorry, an error occurred. " + request.responseText);
}
}
};
request.open("GET", url, true);
request.send();
}
}
};
The the ajax functionality in jQuery is great but does mean a greater page download for one simple Javascript function.
You can find a downloadable fully worked example on my blog here:
http://www.willporter.co.uk/blog/simple-ajax-script.aspx
It uses ASP.NET on the server side but you should get the idea.
jQuery has made very simple ajax methods for you to use. You can find more information about them here.
Sample:
$.ajax({
type: 'GET',
url: '/SomeUrl/On/The/Server',
data: { SomeValue: 10 },
success: function(data, status)
{
// On Success
},
error: function(data, status)
{
// On Error
}
});
Look into this maybe : http://www.scriptiny.com/2011/01/simple-ajax-function-example/
jQuery is a more reliable library overall, but the lightest-weight AJAX methods I have found are the extremely simple Feather AJAX, coming in at 1.6 KB (with room for compression), or a one-liner snippet that I can't guarantee.
The risk of extremely lightweight libraries is that if they break, you're relying on the owner to fix it instead of a team of developers.
An alternative approach to solving your problem is to based your times on UTC instead of server-local time. You can even show the client local times based on that utc time, with a little work.
May I suggest AJAX Generator?
I am developer, and it is commercial tool but it has demo as well.
What you could do with that tool is:
put annotation on your PHP function
run AJAX Generator on PHP source file
include generated JavaScript file in HTML page and use PHP service as if you were calling function
To make it more clear, here is example code:
//example.php
<?php
//#WebService
function getServerDate(){
return date('m/d/Y h:i:s a', time());
}
?>
Now run generator on: example.php
Output would be two files: example_service.php and example_caller.js
Now you need to:
add example_service.php in same directory where is example.php and
include example_caller.js in index.html
Sorry for posting image instead of HTML code, but it wasn't showing properly.

Ajax doesn't work on remote server

when I Implemented chatting Function , I use Ajax to send messages between file to another .
so ,
it is working well on local host .
but , when I upload it in to remote server it doesn't work.
can U tell me ,why ?
is an Ajax need Special configuration ?
Ajax code :
function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
var xmlhttp
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e){
try{
xmlhttp=new XMLHttpRequest()
}
catch(e){
alert("Your Browser Does Not Support AJAX")
}
}
}
err=""
if (GP==undefined) err="GP "
if (URL==undefined) err +="URL "
if (PARAMETERS==undefined) err+="PARAMETERS"
if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if (RESPONSEFUNCTION=="") return false;
eval(RESPONSEFUNCTION(xmlhttp.responseText))
}
}
if (GP=="GET"){
URL+="?"+PARAMETERS
xmlhttp.open("GET",URL,true)
xmlhttp.send(null)
}
if (GP="POST"){
PARAMETERS=encodeURI(PARAMETERS)
xmlhttp.open("POST",URL,true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
xmlhttp.setRequestHeader("Connection", "close")
xmlhttp.send(PARAMETERS)
}
}
Two points really,
Firstly, If the URL is on a different domain, default security model in your browser might stop that working.
Secondly, have a look at JQuery, this bulk of code would be reduced to 2 or 3 lines.
Have a look here: http://docs.jquery.com/Tutorials

How to make XMLHttpRequest work over HTTPS on Firefox?

When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP.
But when sent over HTTPS, different browsers gave different results:
On Firefox 3.0.2:
- The GET request doesn't reach the web server.
On IE 7:
- The GET request reached the web server.
Does this have something to do with Firefox 3 getting stricter with untrusted certificates?
Is there a way around this?
I've already added the URL as an exception in Firefox's Certificate Manager.
The error console doesn't report any error.
I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown.
Using both absolute and relative URL path doesn't work.
Here's the code snippet:
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
// we won't be handling any HTTP response
xmlHttp.onreadystatechange=function()
{
// do nothing..
}
// send HTTP GET request
try
{
xmlHttp.open("GET", "/[relative path to request]", true);
xmlHttp.send(null);
}
catch (e)
{
alert('Error sending HTTP GET request!');
return false;
}
Thanks,
Kenneth
Try placing your closure after the open:
// send HTTP GET request
try
{
xmlHttp.open("GET", "/[relative path to request]", true);
}
catch (e)
{
alert('Error sending HTTP GET request!');
return false;
}
// we won't be handling any HTTP response
xmlHttp.onreadystatechange=function()
{
// do nothing..
}
// Then send it.
xmlHttp.send(null);
A little googling found confirmation:
http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html
Although that document says to attach the function after .send(null), I've
always attached after open.
By any chance, are you requesting a non-HTTPS URL in an HTTPS page? Do any messages appear in the error log/console?

Resources