Upload files with Ajax in CodeIgniter with Jquery not working - javascript

I'm trying to make a file upload with Ajax in CodeIgniter but my Jquery code doesn't seem to be getting the data from the form although it seems like the file is in the POST message.
This is my controller:
public function upload_images(){
$files = $_FILES;
$data=array();
if(!empty($_FILES)){
$_FILES['userfile']['name']= $files['userfile']['name'];
$_FILES['userfile']['type']= $files['userfile']['type'];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'];
$_FILES['userfile']['error']= $files['userfile']['error'];
$_FILES['userfile']['size']= $files['userfile']['size'];
$this->upload->initialize($this->set_upload_options());
$uploaded=$this->upload->do_upload();
echo json_encode($data);
}else{
echo 'empty';
}
}
This is my view:
<div class="main-content" >
<h1><?php echo $name=$_POST['name']?></h1>
<div class="form-group">
<?=#$error?>
<div id="formulario_imagenes">
<span><?php echo validation_errors(); ?></span>
<?=form_open_multipart(base_url()."index.php/ticketadmin/upload_images",'id="form_upload_front"')?>
<input type="file" id="foto1" name="userfile" /><br /><br />
<input id="btnsavefront" type="submit" value="Upload" />
<?=form_close()?>
</div>
</div>
</div>
The Javascript:
$(document).on('click','#btnsavefront',function(event){
//alert('hola soy el boton guardar');
//event.preventDefault();
$('#form_upload_front').submit(function(){
//event.preventDefault();
var fileId = document.getElementById('foto1');
console.log(fileId);
var formData = new FormData(),
dir_url='<?php echo site_url('ticketadmin/upload_images');?>';
formData.append('foto1', fileId.files[0]);
//console.log(formData);
$.ajax({
url: dir_url,
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
/*dataType: "json",*/
success: function(data){
//console.log(data);
}
});
});
//$('#form_upload_front').submit();
});
And this is the header from Network
Remote Address:192.168.33.10:80
Request URL:http://fbpostester.com/index.php/ticketadmin/do_upload
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:345809
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBV6NO2YxjAQZBFNN
Cookie:ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%222f96b04f42abccfe2403af1c17527312%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A12%3A%22192.168.33.1%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A109%3A%22Mozilla%2F5.0+%28Windows+NT+6.1%3B+WOW64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.143+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1409332543%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D31089f37bfc2cd6b239ad6ef538e1f02e9743309
Host:fbpostester.com
Origin:http://fbpostester.com
Referer:http://fbpostester.com/index.php/ticketadmin/do_upload
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Request Payload
------WebKitFormBoundaryBV6NO2YxjAQZBFNN
Content-Disposition: form-data; name="userfile"; filename="PROPUESTA 2B.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryBV6NO2YxjAQZBFNN--
Response Headersview source
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:840
Content-Type:text/html
Date:Fri, 29 Aug 2014 17:15:50 GMT
Keep-Alive:timeout=5, max=100
Server:Apache
Vary:Accept-Encoding
X-Pad:avoid browser bug
X-Powered-By:PHP/5.3.10-1ubuntu3.13

Well let me help you,
So here is your form
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
here is your javascript
function submitFile(){
var formUrl = "url of your php";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data, textSatus, jqXHR){
//now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
},
error: function(jqXHR, textStatus, errorThrown){
//handle here error returned
}
});
}
hope this code was helpfull

Related

Can't send file via ajax ( print_r($_FILES); Array ( ) )

I'm trying to send file, it works with common form confirm, but don't with XHR.
Here my HTML:
<form action="ajax/upload.php" method="post" name="form1" enctype="multipart/form-data" id="id1">
<input type="file" name="input1">
<input type="submit" name="submit1">
</form>
<form action="ajax/upload.php" method="post" name="form2" id="id2">
<input type="file" name="input2">
<input type="submit" name="submit2">
</form>
JS:
document.querySelector('#id2').onsubmit = function(e) {
e.preventDefault();
var file = document.querySelector('#id2 input[type="file"]').files[0];
var xhr = new XMLHttpRequest();
xhr.open("POST", "ajax/upload.php", true);
var boundary = String(Math.random()).slice(2);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.send(file);
}
PHP:
echo '<pre>';
var_dump($_REQUEST);
echo 'print_r($_FILES); <br>';
echo 'Result: <br><br>';
print_r($_FILES);
print "</pre>";
I send same file, responses for common submit:
array(1) {
["submit1"]=>
string(31) "Отправить запрос"
}
print_r($_FILES);
Result:
Array
(
[input1] => Array
(
[name] => CRC75.otf
[type] => application/vnd.oasis.opendocument.formula-template
[tmp_name] => /tmp/phpbNWcgk
[error] => 0
[size] => 411456
)
)
For AJAX:
array(0) {
}
print_r($_FILES);
Result:
Array
(
)
I can't understand why, file attached exist:
document.querySelector('#id2 input[type="file"]').files[0]
File { name: "CRC75.otf", lastModified: 1529516347000, webkitRelativePath: "", size: 411456, type: "application/vnd.oasis.opendocument.formula-template" }
Headers of AJAX request looks normal
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.5
Connection: keep-alive
Content-Length: 411456
Content-Type: multipart/form-data; boundary=44316423440108066
Host: localhost
Referer: http://localhost/
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/61.0
P.S.: It's the requirement that I cannot send a POST request.
You can't send a File directly in the send() parameter, you need to use a FormData object.
document.querySelector('#id2').onsubmit = function(e) {
e.preventDefault();
var formdata = new FormData;
var file = document.querySelector('#id2 input[type="file"]').files[0];
formdata.append("input2", file);
formdata.append("submit2", "Отправить запрос");
var xhr = new XMLHttpRequest();
xhr.open("POST", "ajax/upload.php", true);
xhr.send(formdata);
}
Don't use xhr.setRequestHeader() to set the Content-type header. This is done automatically by the browser. If you do it yourself, the boundary you specify won't match what it's actually sending.

Use python requests to login to website using ajax json post

I'm new to python and I'm having trouble generating the right code to use python requests to login to a website.
The form code from the website
<form autocomplete="off" class="js-loginFormModal">
<input type="hidden" class="js- redirect" name="redirect" value="bn_vLe6OsoRXl4E4LEaOwGkUCvazta7iTkG81ShqumA." />
<input type="hidden" name="token" id="token" value="MTQ4OTg2MzYwMzCaZm653OAL-mKayzhg_4wCyEBXDqZBQUJxdbLLF- foi6EdPeKBgIVz97pUew9YgKPmxiW2NDzrAewdtIJWrBM." />
<input type="hidden" name="remember_me" value="1" />
<input type="hidden" name="from" value="pc_login_modal_:login">
<div class="leftSide floatLeft loginColumnLeft-en">
<p class="signinError" style="display:none;"></p>
<p id="signinLoggingin" style="display:none;">Logging in...</p>
<div><input id="usernameModal" placeholder="Username (6+ characters)" class="js-signinUsernameModal signup_field" name="username" maxlength="50" type="text" value=""></div>
<div><input id="passwordModal" placeholder="Password (6+ characters)" class="js-signinPasswordModal signup_field" name="password" type="password" value=""></div>
<div class="loginAccessRemember">
<input type="checkbox" checked id="signinRemember" />
<label for="signinRemember">Remember me on this computer<br />
<span class="loginAccessRememberInfo">(not recommended on public or shared computers)</span>
</label>
</div>
<div id="signinSubmit" class="orangeButton buttonBase js-loginSubmitModal">Login</div>
<div class="leftCol">
<ul>
<li>
<li><a id="signinForgotpassword" href="/front/lost_password" onclick="ga('send', 'event', 'Login Page', 'click', 'Lost Password');">Forgot Username or Password?</a></li> |
<li><a id="signinConfirmationEmail" href="/front/resend_confirmation_email" onclick="ga('send', 'event', 'Login Page', 'click', 'Resend Confirmation');">Resend confirmation email</a></li>
</ul>
</div>
</div>
<div class="rightSide floatRight loginColumnRight-en">
<h2 class="loginAccessTitle-en">Not a free member yet?</h2>
<span class="loginAccessMessage loginAccessMessageRight">Here's what you're missing out on!</span><br /><br />
<ul class="clearfix">
<li><i class="mark registerSprite enabled"></i><span class="tab1">Download Videos</span></li>
<li><i class="mark registerSprite enabled"></i><span>Post Comments</span></li>
<li><i class="mark registerSprite enabled"></i><span class="tab3">Add Favorites</span></li>
<li><i class="mark registerSprite enabled"></i><span class="tab4">Create Playlists</span></li><br>
<li>And many more!</li>
</ul>
<br/><a class="buttonBase greyButton" id="signupButtonId" href="/create_account_select">Sign Up</a>
</div>
</form>
This is the ajax statement referred to by the javascript "js-loginFormModal"
function loginAjax() {
$j.ajax({
type: "POST",
url: "/front/authenticate",
cache: false,
dataType: "json",
data: $j(".js-loginForm").serialize(),
success: function(a) {
if (a.premium_redirect_cookie == "0") {
if (a.redirect) {
document.location.assign(a.redirect)
} else {
$j(".signinError").show().text(a.message)
}
} else {
$j.ajax({
url: premiumRedirectCookieURL,
cache: false,
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function() {
if (a.redirect) {
document.location.assign(a.redirect)
} else {
$j(".signinError").show().text(a.message)
}
}
})
}
}
});
return false
}
head.ready(document, function() {
var a = false;
$j(".js-loginSubmit").on("click", function(b) {
b.preventDefault();
loginAjax()
});
$j("input.js-signinUsername, input.js-signinPassword").on("keydown", function(b) {
if (!a) {
if (b.which == 13) {
loginAjax()
}
a = true
}
});
$j("input.js-signinUsername, input.js-signinPassword").on("keyup", function(b) {
if (a) {
a = false
}
})
});
My current python code (Python 2.6.6) that is giving me a result of "{"message":"Session timed out - reload and try again"}"
#!/usr/bin/python
from requests import Session
import requests
http_proxy = "http://ip:3128"
https_proxy = "http://ip:3128"
ftp_proxy = "http://ip:3128"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
"ftp" : ftp_proxy
}
session = requests.Session()
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}
payload = {
'remember_me': '0',
'username': 'user',
'password': 'pass'
}
login_link = 'website/front/authenticate'
link = 'http://website'
login = session.post(url=login_link, data=payload, allow_redirects=True, headers=headers,proxies=proxyDict)
print (login.text)
response2 = session.get(url=link, headers=headers,proxies=proxyDict)
#print response2.content
#print(r2.text).encode('utf-8').strip() #TEXT/HTML
#print(r.status_code, r.reason)
I think I'm missing things from my payload. I don't know if I need to specify json as the formatting of the payload or if I have to serialize anything.
The solution was the following
#!/usr/bin/python
from requests import Session
import requests
import json
import re
http_proxy = "http://ip:3128"
https_proxy = "http://ip:3128"
ftp_proxy = "http://ip:3128"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
"ftp" : ftp_proxy
}
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive',
'Content-Length': '209',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Host': 'www.website.com',
'Origin': 'http://www.website.com',
'Referer': 'http://www.website.com/login',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
login_link = 'http://www.website.com/front/authenticate'
link = 'http://www.website.com/'
with requests.Session() as r:
s = r.get(url=link, proxies=proxyDict)
token = re.findall(r'token" value.*', s.text)[0]
token = token.split('=')[1]
token = token.split('"')[1]
redirect = re.findall(r'redirect" value.*', s.text)[0]
redirect = redirect.split('=')[1]
redirect = redirect.split('"')[1]
payload = {
'loginpage': '1',
'redirect': redirect,
'token': token,
'username': 'user',
'password': 'pass'
}
login = r.post(url=login_link, data=payload, allow_redirects=True, headers=headers, proxies=proxyDict)
print (login.content)

AJAX post to PHP empty

I have checked the other questions - this is not a duplicate.
I have tried all of the solutions I could find and implement.
I am trying to send data from task.php → showCats.php
task.php:
<script type="text/javascript">
$(document).on("click", ".btnCat", function () {
var filter = $(this).data("id");
alert(filter);
$.ajax({
type: 'POST',
url: 'showCats.php',
data: {'filter': filter},
});
$('div.container-fluid').load('showCats.php');
});
</script>
showCats.php:
$area = $_POST['filter'];
$sql = "select AID,name,surname,street_name,house_number, area, plz,poster,visible from addresses WHERE area LIKE '$area' AND visible LIKE 'show' ORDER BY AID DESC";
$rs = mysqli_query($con,$sql);
$str = '';
while ($res = mysqli_fetch_array($rs)) {
$str .= '
<div class="col-md-9">
<div class="task col-md-12 well" id='.$res['AID'].'>
<div>
<button class="btn btn-danger btn-xs btnDelete" id='.$res["poster"].' onclick="refresh()" data-id="'.$res['AID'].'">x</button>
</div>
<div>
<span>'. $res["name"].'</span>
<span>'. $res["surname"].'</span><br>
<span>'. $res["street_name"].'</span>
<span>'. $res["house_number"].'</span><br>
<span>'. $res["plz"].'</span>
<span>'. $res["area"].'</span>
</div>
</div>
</div>';
}
echo $str;
?>
var_dump($_POST); returns NULL, even though I can see the post value under Developer Tools in Chrome.
My GET:
Request URL:https://example.com/showCats.php
Request Method:GET
Status Code:200 OK
Remote Address:xxx:443
Response Headers
view source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Fri, 15 Jul 2016 18:43:56 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx/1.6.2
Strict-Transport-Security:max-age=31536000
Transfer-Encoding:chunked
Request Headers
view source
Accept:text/html, */*; q=0.01
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8,de;q=0.6
Connection:keep-alive
Cookie:PHPSESSID=vudgbb33574tfod2vu48hst830
Host:example.com
Referer:https://example.com/tasks.php
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
X-Requested-With:XMLHttpRequest
My POST:
Request URL:https://example.com/showCats.php
Request Method:POST
Status Code:200 OK
Remote Address:xxx:443
Response Headers
view source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Fri, 15 Jul 2016 18:43:56 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx/1.6.2
Strict-Transport-Security:max-age=31536000
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,de;q=0.6
Connection:keep-alive
Content-Length:12
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:PHPSESSID=vudgbb33574tfod2vu48hst830
Host:example.com
Origin:https://example.com
Referer:https://example.com/tasks.php
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
filter:Turgi
You are trying to send data from task.php -> showCats.php ! your code does that very well by using this:
$.ajax({
type: 'POST',
url: 'showCats.php',
data: {'filter': filter},
});
The problem is when you do this : $('div.container-fluid').load('showCats.php'); a GET request will be sent to the server! so It's normal to find that var_dump($_POST) return NULL.
If you want to show/get the response you can use the success event like this:
$.ajax({
type: 'POST',
url: 'showCats.php',
data: {'filter': filter},
//A function to be called if the request succeeds.
success: function(data) {
$('div.container-fluid').html(data)
},
//A function to be called if the request fails
error: function(xhr, status, error) {
alert('An error occurred:'+error);
}
});
setting a datatype parameter tells what kind of data you are sending.
type: "POST",
dataType: 'json',
I would concur with those comments above. Loading the program a second time does not report the values of the database call. Further, wouldn't AJAX normally return values to the calling program with an echo of json_encode, instead of just echoing the variable to a run of the PHP page that does not get viewed?

MVC dropzone doesn't upload files in IE

Please help. I'm working on a MVC project using dropzone upload multiple files based on this sample http://venkatbaggu.com/file-upload-in-asp-net-mvc-using-dropzone-js-and-html5/.
I have this work on Chrome, but I could not figure out why it doesn't work on IE 11. When I debug in VS2013, it doesn't seem to trigger the SaveUploadedFile action. Again, it works in Chrome. Below is the codes in my MVC project:
View:
#Styles.Render("~/Content/css")
<div class="container">
<div class="jumbotron">
<form action="~/PhotoAlbum/SaveUploadedFile/#Model.AlbumID" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
</div> <!-- /container -->
<style type="text/css">
.dz-max-files-reached { background-color: red; }
</style>
#section scripts {
#Scripts.Render("~/bundles/dropzonescripts")
<script type="text/javascript">
//File Upload response from the server
Dropzone.options.dropzoneForm = {
maxFiles: 20,
init: function () {
this.on("maxfilesexceeded", function (data) {
var res = eval('(' + data.xhr.responseText + ')');
});
this.on("onSuccess", function (data) {
alert("Upload successfully!");
});
this.on("onError", function (data) {
alert("Upload Failed!");
});
this.on("addedfile", function (file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-info glyphicon glyphicon-remove-sign'> Remove </button>");
alert("Upload Failed!");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
}
};
</script>
}
Action:
public ActionResult SaveUploadedFile(int id)
{
EZone_PhotoAlbum ezAlbum = repoAlbum.GetPhotoAlbumByID(id);
bool isSavedSuccessfully = true;
string fName = "";
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}\\", Server.MapPath(sMapPath + "\\" + ezAlbum.AlbumFolder)));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "original");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, fileName1);
file.SaveAs(path);
}
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
.Headers:
General:
Remote Address:[::1]:80
Request URL:http://localhost/eZone/PhotoAlbum/SaveUploadedFile/2
Request Method:POST
Status Code:200 OK
Response Headers: view parsed
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 5.1
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
WWW-Authenticate: Negotiate oRswGaADCgEAoxIEEAEAAABDh+CIwTbjqQAAAAA=
Date: Fri, 26 Jun 2015 16:01:30 GMT
Content-Length: 26
Request Headers view parsed
POST /eZone/PhotoAlbum/SaveUploadedFile/2 HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 3501896
Authorization: Negotiate oXcwdaADCgEBoloEWE5UTE1TU1AAAwAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAABXCiOIGAbEdAAAAD6cslqGeHsjhn4ZY5uX0W2mjEgQQAQAAAPUXp1AtIpqEAAAAAA==
Origin: http://localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarySvGz79kd1fOGLop0
Accept: application/json
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
Referer: http://localhost/eZone/photoalbum/Detail/2
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Request Payload
------WebKitFormBoundarySvGz79kd1fOGLop0
Content-Disposition: form-data; name="null"
------WebKitFormBoundarySvGz79kd1fOGLop0
Content-Disposition: form-data; name="null"
------WebKitFormBoundarySvGz79kd1fOGLop0
Content-Disposition: form-data; name="file"; filename="IMG_0057.JPG"
Content-Type: image/jpeg
------WebKitFormBoundarySvGz79kd1fOGLop0--
.Response:
{"Message":"IMG_0057.JPG"}

How to send header to remote site via anyorigin.com using ajax request?

I am trying to send customized header to a remote website using anyorigin.com service but for some reason the user agent header is not passed to remote site!
Prove that header is not send comes from response i get back from www.whatsmyuseragent.com which shows different user agent then the one i send!
could any one tell me why user agent header is not passed to remote website ?
<html>
<head>
<script src="http://anyorigin.com/jquery-1.4.2.min.js"></script>
<script>
$.ajax({
url: 'http://anyorigin.com/get?url=http://www.whatsmyuseragent.com/&callback=?',
xhr: {
withCredentials: true
},
type: 'GET',
dataType: "json",
success: displayAll,
beforeSend: setHeader
});
function displayAll(data){
// alert(data.contents);
document.myform2.outputtext2.value = data.contents ;
}
function setHeader(xhr){
xhr.setRequestHeader("User-Agent","Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3");
}
</script>
</head>
<body>
<br>
<form id="myform2" name="myform2" action="./5.php?Id=&title=" method="post">
<td><textarea rows="14" cols="15" name="outputtext2" style="width: 99%;"></textarea> </td>
</form>
</html>

Categories