In dropzone.js , there is an event error, however I can not find any documentation on how to trigger this from PHP.
I have tried sending various header() responses from PHP including, 404, 500, 503, and so on yet this event has not fired.
What I am looking to do, is the server checks the mime to see if it is valid, and if it is not valid, I discard the file, and ideally -- return an error so that dropzone can respond accordingly.
From the javascript side, I have tried the following :
.on("complete", function(file,response) {
console.log(response);
}
.on("error", function(file,response) {
console.log(response);
}
.on("success", function(file,response) {
console.log(response);
}
... however, response is undefined, even if i return JSON or plain text from the php script. It doesn't appear that dropzone.js supports getting the full server response or at least it doesn't elevate it to the custom handler. The ONLY place I have seen any reference to passing a second param on events is here on SO in other questions that are not directly asking this question.
There must be a way to get the server response (as I have done in the past with other uploader javascript such as jQuery POST, and jqUpload, and so on). It seems rather silly that I can't trigger a command to signal the upload failed -- even if the file transfer completed -- as it still needs to wait on the script for a response. --- This means I am likely overlooking something, which is why I am calling for assistance as their documentation reveals absolutely nothing with regards to how a server should respond --- language irrelevant, however in my case, I am using PHP.
Thanks in advance.
<?php
header('HTTP/1.1 500 Internal Server Error');
header('Content-type: text/plain');
$msg = "Your error message here.";
exit($msg);
?>
NOTE: Do not redirect user else it won't run exit($msg)
<script type="text/javascript">
$(document).ready(function () {
Dropzone.options.dropzone = {
maxFilesize: 10,
init: function () {
this.on("uploadprogress", function (file, progress) {
console.log("File progress", progress);
});
}
};
});
</script>
That's it! It should work.
If you send any non-200 response header Dropzone will detect it as an error and fire the error(file, response) event. The error info can go in as JSON and is accessible via response.your_msg_variable
Note that just printing response won't show anything useful as it's an object, you can use console.log(JSON.stringify(responseText, null, 4));
This will pretty print the object upto 4 levels down
Related
So I'm working on a website where I have to implement a chat, currently the whole thing is running on localhost.
I'm getting this error:
SyntaxError: Unexpected end of JSON input
and can't figure out why. I have googled a little but can't find an answer, that actually works. I actually did this yesterday, on another computer and that worked super, but today it won't work and I can't figure out why.
Thank you for the great answers.
$(function() {
updateChat("updateChat", null);
$(".chat-form").submit(function(event) {
event.preventDefault();
if ($(".chat-form input").val() != "") {
updateChat("sendMessage", $(".chat-form input").val());
}
});
setInterval(function() {
updateChat("updateChat", null);
}, 3000);
function updateChat(method, message) {
$.ajax({
type: "POST",
url: "action/chat.php",
data: {
function: method,
message: message
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
})
}
})
Most likely there's an error or warning in your PHP code being displayed, and because you are expecting only json, that causes the syntax error.
There are a few ways to find out what's going on:
open the developer console in your browser and see what the response is the network tab
check your PHP error log
temporarily change your dataType to html and you'll see your console.log(data)
I was getting this error due to my backend php function NOT returning a response as it should have been. It was returning nothing. My parent function that should have been returning the response was calling a child function that WAS returning a response, but the parent function wasn't passing that child return back to the ajax call.
Another possible culprit for these type of errors could be an improper python "shebang" on your back-end (server side) script.
In my particular case I had ajax call to python cgi script via Apache web server and I could not find a more descriptive error message at front-end debug tools. However, Apache logs indicated that the back-end script had problems importing a one of the python scripts because the interpreter did not recognize it. After checking the "shebang" of that back-end script sure enough it had the wrong interpreter specified because I just copied a template file over and forgot to modify it..
So, check your "shebang" at the top of your script to make sure it points to correct interpreter. Example:
For MVC controller you must return a valid JsON
return new JsonResult() { Data = new { test = 123 } };
instead of
return new JsonResult();
I am using a Jquery $.post request to get a JSON response that is generated by PHP. When the request is complete, a success or error message is displayed. During development however, I sometimes have PHP errors which end up being returned instead of the JSON. When this happens, I just get the error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The code I have now looks like this:
var request = $.post(url, data, null, "json");
request.fail(on_failure);
var on_failure = function(jqXHR, text_status, error_thrown)
{
$("#text_status").empty().append(error_thrown);
};
I would like to be able to show the PHP error if one is returned rather than just indicate that there is a PHP error (just to speed up debugging). Obviously, if a non-JSON parsing error such as HTTP 404 occurs, I still want to display that. I found a method here that indicates that I can detect this error with something like this
$.ajaxSetup({
error: function(jqXHR, exception) {
if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
}
}
});
But it doesn't seem like that helps me because it runs for every request rather than individual requests and (as far as I know) it does not allow access to the error message in the returned data.
No sure what version of jquery are you using. Anyway, did you try to remove the json dataType?
var request = $.post(url, data, null);
Doing this jQuery will guess the dataType for you.
I hate to steal mkross1983's credit, but he has not responded to my request to turn his comment into an answer. mkross1983 said:
Have you tried using Firebug under the "Net" tab to see the results of the requests? Sometimes errors can be seen there that can give some clues to the problem
The Firebug "Net" tab has proved to be a valuable debugging tool. This way I can see exactly what request was made and the response sent to it. It even allows me to see the headers and cookies that were sent with the request.
Thank you mkross1983
I've configured FineUploader to use CORS and work with my Amazon Web Services S3 bucket.
The problem I face, is that a successful upload does not return any response content (Status code 204 though, but the response content is empty). So even though the upload happens (I've verified the file is uploaded), the error event is triggered. Presumably, this is because there is no response.
How do I handle this case? Is there a way for me to manually trigger a 'success' by catching this error in the 'onError' callback?
Edit:
I've made some progress digging here. The error seems to stem from handler.xhr.js.
In particular, inside the parseResponse(xhr) function.
try{
response = qq.parseJson(xhr.responseText);
}
catch(error) {
log('Error when attempting to parse xhr response text (' + error + ')', 'error');
response = {};
}
This seems to throw an error since the response is empty.
Does anyone know what a proper response should be? I'm thinking of adding a line here checking for an empty response and then manually plugging in what a correct response should be.
The issue was with the parseResponse() function after all. It expects successful uploads to return the JSON string {"success": true} after a successful upload.
In my case, Amazon returns an empty response with a 204 status code. The 204 status code implies no response is needed.
I've fixed this in my case by modifying the section mentioned in my edit as follows:
try {
if(xhr.status == 204 && xhr.responseText.length == 0){
response = qq.parseJson('{"success": true}');
}
else{
response = qq.parseJson(xhr.responseText);
}
}
Hopefully this will help others who run into this issue in the future.
I have a web app, requesting and sending data via AJAX, and as a response, my server-side sends HTTP status codes, depending on the situation. so for example if a user tries to login while he's logged I probably return a 400 HTTP status code. And eventually i handle it with an alert, etc.
But handling these HTTP Status codes gets too heavy, since I'm making heavy use of AJAX. that means I'll be handling HTTP status code repeatedly with every AJAX request, which will result in duplicated code, and that's a bad practice.
So, what I'm looking for is a way to handle all these errors in one place, so I just handle all 400, 401, etc with the same code.
What i'm currently doing:
Handling the errors manually for each AJAX call. By using the statusCode in$.ajax().
statusCode: {
500: function(data) {
alert('Some friendly error message goes here.');
}
It seems like an overkill for me, as my web app develops, and as I create more ajax calls. I'll be repeating this piece of code again and again.
Currently, the only idea I have in mind is creating a function that will work on top of AJAX, something like:
function doAjax(type,url, data, moreVars) {
//this function is just a SIMPLE example, could be more complex and flexible.
$.ajax({
type: type,
url: url,
data: data,
moreOptions:moreVars,
//now handling all status code.
statusCode: {
//handle all HTTP errors from one place.
}
});
}
doAjax("POST", 'mydomain.com/login.php', dataObj);
You can use $.ajaxSetup() to register global error state handlers.
Description: Set default values for future Ajax requests.
Example:
$.ajaxSetup({
statusCode: {
500: function(data) {
alert('Some friendly error message goes here.');
}
}
});
i've recently tried to get some Response from an URL using jQuery. Therefore I copied a get request sample of jQuery API Get Request Tutorial into my project and tried to run it, but my debugging messages showed me, that it can't go further. I tried the javascript Ajax Library using a simple request, but it didn't work.
So i'm asking you, if you could help me somehow.
And this is all what i do, but there is no response.
var url = "http://www.google.com";
$.get(url, function(data){
alert("Data Loaded: " + data);
});
Did i probably forgot to include a ajax or jQuery library. For a better understanding, i have c and obj-c experince, this is why i think, that a library is missing.
In each sample there is just a short url like "test.php". Is my complete HTTP url wrong?
Thanks for your answers in advanced.
Br
Nic
I have provided an example scenario to help get you started:
<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script
This is probably best to include inside of an external JS file:
//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
$.ajax({
//The URL to process the request
'url' : 'page.php',
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type' : 'GET',
//Any post-data/get-data parameters
//This is optional
'data' : {
'paramater1' : 'value',
'parameter2' : 'another value'
},
//The response from the server
'success' : function(data) {
//You can use any jQuery/JavaScript here!!!
if (data == "success") {
alert('request sent!');
}
}
});
});
You're hitting the Same Origin Policy with regard to ajax requests.
In a nutshell, JS/Ajax is by default only allowed to fire requests on the same domain as where the HTML page is been served from. If you intend to fire requests on other domains, it has to support JSONP and/or to set the Access-Control headers in order to get it to work. If that is not an option, then you have to create some proxy on the server side and use it instead (be careful since you can be banned for leeching too much from other sites using a robot).
As others have said you can't access files on another server. There is a hack tho. If you are using a server side language (as i assume you are) you can simply do something like:
http://myserver.com/google.php:
<?php
echo get_file_contents('http://www.google.com');
?>
http://myserver.com/myscript.js
$.get('google.php',function(data){ console.log(data) });
That should work!
you just can access pages from your domain/server