Sending ajax parameter to PHP script - javascript

I am working on a file drag and drop, and would like to use the same PHP page. I want to trigger the PHP script page using an action variable so it will go into the following if statement:
..
elseif ($_POST['action'] == 'uploadFile')
{
TrackEvent('CHANNEL_ACTIVATE');
echo "upload file";
}
I have an ajax call that is triggered using ondrop:
var data = new FormData();
data.append('action', 'uploadFile');
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.open('POST', 'channelEdit.php');
request.send(data);
$(this).unbind('click').click(function (e) {
});
$( "#fileList" ).trigger( "click" );

while you are sending post data in ajax you have to add setRequestHeader in request
So change your script as below :
var data = new FormData();
data.append('action', 'uploadFile');
var request = new XMLHttpRequest();
request.open('POST', 'channelEdit.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //<------Add this line
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.send(data);
$(this).unbind('click').click(function (e) {
});
$( "#fileList" ).trigger( "click" );

Related

Get JSON from Web Service Using JavaScript

I get this error when I click the button in HTML to use my JavaScript.
myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
JS:
function ajaxFunction() {
console.log("ajaxFunction()");
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Broken");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var form = document.getElementById("myform");
var titleParagraph = document.getElementById("home_title");
titleParagraph.innerHTML = ajaxRequest.responseText;
form.style.display = "none";
}
}
var value1 = document.getElementById("field1").value;
var value2 = document.getElementById("field2").value;
var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
console.log(url);
// Call sign in web service
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
var jsonResponse = JSON.parse(ajaxRequest.responseText);
console.log("RESPONSE:");
console.log(jsonResponse);
}
This JSON is what I get when I go to https://webapp.azurewebsites.net/users/value1/value2
[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example#example.com"}]
ajaxRequest.open("GET", url, false);
Third parameter says if the request is asynchronous or not. So by looking at your code it should be synchronous.

FormData object, doesn't seem to be uploading my file...

Im following this guide to use aJax to upload an image, mainly so I can have a progress bar. But for some reason the PHP script doesn't seem to receive a file!
Here is my JavaScript:
function submitFile() {
var form = document.forms.namedItem("imageUpload");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
console.log("uploaded!");
doc("imageResponse").innerHTML = xhr.responseText;
} else {
console.log("error!");
doc("imageResponse").innerHTML += "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
}
};
//Progress
/*
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100);
document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%";
}
};
*/
//Send data
xhr.send(formData);
}
And here is my PHP file which receives the file:
<?php
session_start();
print_r($_FILES);
?>
Currently that PHP file is returning an empty Array... it should have my file!
Array ( )
I managed to fix my code, here is the working version for anyone with the same problem. I decided to make a new form using JavaScript and append the file field value to this new form.
I did this mainly for my situation.
function submitFile(file,buttonId) {
//Generate a new form
var f = document.createElement("form");
f.setAttribute("method", "POST");
f.setAttribute("enctype", "multipart/form-data");
//Create FormData Object
var formData = new FormData(f);
//Append file
formData.append("image", file.files[0], "image.jpg");
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
document.getElementById(buttonId).innerHTML = "UPLOAD COMPLETE";
//console.log("uploaded!");
} else {
//console.log("error!");
alert("Error " + xhr.status + " occurred when trying to upload your file");
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
document.getElementById(buttonId).innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById(buttonId).style.backgroundSize = (currentPercentage+1) + "% 100%";
if (currentPercentage==99) {
document.getElementById(buttonId).innerHTML = "Processing image";
}
}
};
//Send data
xhr.send(formData);
}

JSON data Post to server in Titanium for Android / iOS

I'm trying post my JSON data to server but it fails when i submit the data. it gives me error code 403. i tried this method in ADT for android it worked. it's not working on titanium only.
Here's my code.
function postData() {
Ti.API.info("JSON Data :" + JSONStringData);
var url = "http://www.vrsweb.in/hotels/admin/ws/orderItems.php";
var xhrpost = Titanium.Network.createHTTPClient();
xhrpost.setTimeout(5000);
xhrpost.open('POST', url);
xhrpost.setRequestHeader("Content-Type", "application/json");
xhrpost.setRequestHeader('charset', 'utf-8');
xhrpost.setRequestHeader("enctype", "multipart/form-data");
xhrpost.send(JSONStringData);
xhrpost.onerror = function(e) {
Ti.API.debug(e.error);
if (platform == 'android') {
var toast = Titanium.UI.createNotification({
message : 'Cannot Connect to server please check your internet Connection!',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
}
if (platform == 'iphone') {
alert('Cannot Connect to server please check your internet Connection!');
}
Ti.API.info("Status code :" + xhrpost.status);
};
xhrpost.onload = function() {
if (xhr.status == 200) {
Ti.API.info("XHR Status : " + xhrpost.status);
data = JSON.parse(this.responseText);
Ti.API.info("Response from server :" + data);
if (platform == 'android') {
var toast = Titanium.UI.createNotification({
message : 'Table booked Successfully!',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
}
if (platform == 'iphone') {
alert('Table booked Successfully!');
}
} else {
Ti.API.info("XHR Status : " + xhrpost.status);
}
};
}
I don't understand what am i doing wrong.
And i am Collecting data through JSON Get Method from the server and adding it to array. Converting that array into JSON and posting it to server.
Here's how i get Order id from server and saving it to array.
aButton.addEventListener('click', function() {
name = textUser.value;
qty = textPass.value;
price = textConfirmPass.value;
type = textEmail.value;
var url = "http://vrsweb.in/hotels/admin/ws/placeOrder.php?tName=" + id + "&wName=" + logName;
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(5000);
//xhr.autoEncodeUrl = false;
xhr.open('POST', url);
xhr.setRequestHeader('User-Agent', 'My User Agent');
xhr.send();
xhr.onerror = function(e) {
Ti.API.debug(e.error);
var toast = Titanium.UI.createNotification({
message : 'Error! Can not book table! ',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
Ti.API.info("Status code :" + xhr.status);
};
xhr.onload = function() {
if (xhr.status == 200) {
Ti.API.info("XHR Status : " + xhr.status);
oID = JSON.parse(this.responseText);
Ti.API.info("Response from server :" + oID);
var id = oID;
tempData = {
oId : id,
itemName : name,
qtyPerPlate : qty,
qtyPerKg : '0',
pricePerPlate : price,
pricePerKg : '0',
type : type
};
arrayOBJ.push(tempData);
orderData = {
Item : arrayOBJ
};
JSONStringData = JSON.stringify(orderData);
Ti.API.info("Data Added :" + orderData);
var toast = Titanium.UI.createNotification({
message : 'Added Data!',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
} else {
Ti.API.info("XHR Status : " + xhr.status);
}
};
Ti.API.info("id :" + id);
Ti.API.info("name :" + logName);
});
I got it working. Here's what i changed.
xhrpost.setRequestHeader('User-Agent', 'My User Agent');
xhrpost.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
There is no need to set charset and enctype so remove it and then try to call.

html5 upload multiple files with javascript

here is the upload logic in js
var upload = function(){
if(_file.files.length === 0){
return;
}
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.upload.addEventListener('progress', function(e){
_progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';
}, false);
request.open('POST', 'upload.php');
request.send(data);
}
I run the function every time user selected something, but I only got the first file if user selected multiple files.
That's because you're only adding the first file to your data object:
data.append('SelectedFile', _file.files[0]);
You need to add all your files in the _file.files collection
Something like:
for(var i = 0 ; i < _file.files.length; i++ ) {
data.append('SelectedFile'+i, _file.files[i]);
}
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
Instead of this code, try something like this:
var data = new FormData();
for (var i in _file.files) data.append('SelectedFile'+i, _file.files[i]);

How to translate AS3 urlrequest.data POST request to javascript XHttpRequest (formdata)

I have a piece of AS code that must be translated to javascript. Most of the things work okay now but only uploading (in chunks) fail. I get a message back from the server "Different file size". I think the way javascript post raw data differs from AS3's UrlRequest with FormData.
For example:
AS3: urlRequest.data = [ByteArray]
JS : Formdata.append('data', [FileBlob] )
Does this have the same result?
The AS3 code is:
private function sendData() : void
{
this._filePieceReadyToUpload = false;
this._bytesToSend = new ByteArray();
this._fileStream.readBytes(this._bytesToSend, 0, this._fileStream.bytesAvailable);
this._currentOperation = this.OP_DATA;
this._urlRequest = new URLRequest(_uploadScriptPath + "?op=" + this.OP_DATA + "&secure=" + _loginSecureHash + "&user_id=" + _userId + "&crc=" + this._headerCRC + "&size=" + this._bytesToSend.length + "&position=" + this._piecePosition + "&md5=" + this._fileCurrent.$md5 + "&api_id=" + _apiID);
this._urlRequest.method = URLRequestMethod.POST;
this._urlRequest.data = this._bytesToSend;
this.startURLRequstLoadTimer();
return;
}
Translated into this (javascript):
o.uploadFileBlob = function( blobFile, iBlobPos, sCrc )
{
var fd = new FormData();
fd.append( 'data', blobFile ),
xhr = new XMLHttpRequest(),
sGetVars = 'op=data'+
'&secure='+o.apik_secureHash+
'&user_id='+o.apik_userId+
'&crc='+sCrc+
'&size='+blobFile.size+
'&position='+iBlobPos+
'&md5='+
'&api_id=4';
xhr.upload.addEventListener("progress", function(e) { $d('progress'); }, false);
xhr.addEventListener("load" , function(e) { $d('upload complete'); }, false);
xhr.addEventListener("error", function(e) { $d('failed '+xhr.status+': '+xhr.statusText+' : '+xhr.responseText);
//alert( xhr.getAllResponseHeaders().toLowerCase() );
}, false);
xhr.addEventListener("abort", function(e) { $d('upload abort'); }, false);
xhr.open('POST', o.apik_address+'?'+sGetVars, true );
xhr.onload = function(e) { $d('xhr loaded'); };
return xhr.send(fd);
}
Can explain somebody to me what the difference is between the AS and JS version. Is a POST field 'data' in javascript the same as urlRequest.data in AS? What am I doing wrong?

Categories