I'm trying to upload a file via Ajax.
var fd = new FormData();
fd.append('file', file);
var xhr = $.ajax({
url: 'https://www.mywebsite.com/it/file/upload/',
type: 'POST',
dataType: 'json',
data: fd,
cache: false,
contentType: "application/json; charset=utf-8"
processData: false,
success: function(result, message, xhr)
{
console.log(result);
}
});
For the moment, the upload PHP script simply displays file data
header('Content-Type: application/json');
echo json_encode($_FILES['file']);
die();
As stated here, I am forced to use contentType:"application/json; charset=utf-8" because contentType:false causes a 404 (Not Found) error.
Unfortunately, this solution avoids the 404 error, but the displayed file data is null.
You should use this. It is working for me.
$.ajax({
type: 'POST',
url: $(this).attr('action'), //url_to_php_script
data: new FormData(this),
contentType: false,
processData: false,
success: function (data) {
//do necessary cleanups on success
},
error: function (e) {
//do necessary cleanups on failue
}
});
You will be able to get uploaded image in PHP using $_FILES
It should be ok the way you're doing it, however...
If you set contentType to false, than you will force jquery not to set the content type for you. If it is not set, it will default to `application/x-www-form-urlencoded; charset=UTF-8'.
That means you are sending your data using an url encoded string.
You can't easily send a file in an url encoded string.
Most likely the method on the server side is set up to read the form parameters from the url. Therefor if you set `contentType' to false, the server won't recognise the url, resulting in a 404.
Try setting up the server method to accept post data, remove the url parameters and read the posted form from the $_POST and $_FILES variables.
If you can't figure it out, update the question with the servers' method so we can see how the method is set up.
Related
I'm having a problem trying to implement an AJAX request into a pre-existing website that I didn't create.
I have no problems sending the data to PHP as a GET request, however POST requests and trying to access $_FILES is returning null.
Here is the AJAX:
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP:
<?php echo json_encode($_POST['someData']); ?>
I believe the cause of the issue might lie within the htaccess file or be related to some other redirect that is in place on the site. This website was built by a past staff member at the company, and I've had this same problem using AJAX POST with several other sites built by them.
As changing from POST to GET works fine I don't think there is any problem with my very simple code.
Is there some way I can test if the data is going missing due to a redirect, or could there be some other cause?
First check the browser dev tools ctr+shift+J and see if there is a redirect. If not then
You need to set your datatype to json and depending on what version of JQUERY you are using you might have to use "type" instead of "method" if your JQUERY version < 1.9.0
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "json",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP code:
header("Content-Type: application/json", true);
If that doesnt work then make sure your URL is absolutely correct. No extra slashes or spaces.
I have managed to figure this out, there is a 302 redirect in place for all .php extetensions to a url without the extension. There was also an error in my code.
Changing the URL in the AJAX to "post-data" without the .php extension allows me to see $_POST in PHP.
My other problem with not being able to access files came down to the way I was trying to send FormData with AJAX.
My original code to do this was:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: ({someData, fData}),
success: function(data) {
console.log(data);
}
});
The problem being that you can't send FormData and other variables at the same time. Instead I have to append my other data to the FormData:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
fData.append("someData", someData);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: fData,
success: function(data) {
console.log(data);
}
});
This is my first time trying to deal with blob data.
I'm trying to send the blob image url via ajax to php for uploading the icon but it's not working, I am not sure if I'm even doing it correctly, can someone help me out?
console.log(apk.app.icon_url); // Prints: blob:http://localhost/9ca5a837-fdb4-4288-a21a-18e9650e6ac5
let data = new FormData();
data.append('icon', apk.app.icon_url);
$.ajax({
url: "testicon.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert(data); // PHP array returns empty
}
});
I am trying to make a request to this file : http://traitdesign.com/work/tattva/get.php
this is the code I have so far:
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
}).responseText;
}
getRemote();
well the issue is response headers is empty it doesnt return any results. any help would be appreciated. thank you
Try with JSONP
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
dataType: "jsonp",
});
}
getRemote();
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
Problem is 'Same Origin Policy'. but you can escape from it. but some security issues will remain.
Please check this. http://enable-cors.org/server_php.html
header("Access-Control-Allow-Origin: *");
Include this line into your get.php file.
I think the best in your case would be to write simple ajax action on your server like:
print(file_get_contents('http://traitdesign.com/work/tattva/get.php');
And make ajax call to your new action. It will got through your server so additional server work will be done but you then don't need to care about security policy.
Use JSONP with callback. Also return the value once the call is done.
function getRemote() {
var jqXHR = $.ajax({
type: "GET",
dataType: "jsonp",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
crossDomain: true
});
return jqXHR.responseText;
}
getRemote();
I got the error:
request failed: URI too long (longer than 8190)
I've seen other posts on StackOverflow for this one. Those posts recommend:
Not changing Apache settings (agree)
Using post, not get
Not using jsonp with post
I'm using jQuery's AJAX to POST:
$.ajax({
url: "test.php",
dataType: "json",
data: paras,
type: "POST",
success: function(ret){callback(ret);}
});
It's my impression you can use json just not jsonp. Correct? If so, why might I still be getting the error?
You should try setting proccessData to false.
From the docs:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
so to prevent the data being added to the url:
$.ajax({
url: "test.php",
dataType: "application/json",
data: paras,
type: "POST",
proccessData: false, // this is true by default
success: function(ret){callback(ret);}
});
Honestly, I thought this was automatic, but since your url is too long it's worth a shot.
I ran into this issue when using jQuery to submit large forms, and was able to solve it by adding this plugin.
For example, using the following code to submit the form after adding the plugin resolved the issue for me:
$(formSelectorHere).ajaxSubmit({
url: myURL,
type: 'post',
contentType: "multipart/form-data",
data: $(this).serialize(),
success: function(data) {
function(data) {
//success code here//
}
});
If you're not using this to submit a form, this may not be relevant to you and won't solve your problem, but that's the most common situation where this issue appears, so I figured it was worth mentioning. (The plugin should also be able to submit a form using JSON, but haven't personally tested it).
As the answer to this question says, I have this block of code to query the best buy api:
$.ajax({
type: "GET",
url: "http://api.remix.bestbuy.com/v1/products(search=camera)?apiKey=" + apiKey + "&format=json&callback=?",
cache: true,
success: function(data) {
alert('success');
},
dataType: 'json'
});
The code runs fine, but returns an error message from best buy:
"Couldn't understand '/v1/products(search=camera)?apiKey=myApiKey&format=json&callback=jQuery16209624163198750466_1312575558844'"
If I leave out "callback=?" the url returns products just fine when I go to it on the browser, but in the code it throws a javascript error:
"XMLHttpRequest cannot load http://api.remix.bestbuy.com/v1/products(search=camera)?apiKey=myApiKey&format=json. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin."
set dataType to jsonp
$.ajax({
type: "GET",
url: "http://api.remix.bestbuy.com/v1/products(search=camera)?apiKey=" + apiKey + "&format=json",
cache: false,
crossDomain:true,
success: function(data) {
alert('success');
},
dataType: 'jsonp',
});
Update: Found a solution, but it's not ideal. I'd rather not use php, but it works.
I have a php file that grabs the data:
$requestUrl="http://api.remix.bestbuy.com/v1/products(search=camera)?format=json&apiKey={$apiKey}";
$data=file_get_contents($requestUrl);
echo $data;
Then I grab that file with jquery:
$.ajax({
url: "js/getBestBuy.php",
dataType: "json",
success: function(data) {
alert('success');
}
});
The Remix query parser can't handle an underscore in the JSON Callback. If you have a callback without an underscore it should work. Keep in mind, the Remix cache ignores the value of the JSON callback, so if the query is identical except the callback has changed, you will get a cached response (ie. the "couldn't understand . . ." error). Change the query slightly and you will get a fresh response.