I've been messing around with SWF Upload, and I really like it. I was able to apply it very easily to my file upload class with very little issue. The problem I am having, however, is that I need to be able to send back errors to the uploader so a user knows if their file actually wasn't completely uploaded due to issues such as it being too large, or of the wrong format, ect. I read through the PHP example script that the writers of SWF Upload provide, but I cannot figure out how to pass back the errors to it. This is there error handling function:
/* Handles the error output. This function was written for SWFUpload for Flash Player 8 which
cannot return data to the server, so it just returns a 500 error. For Flash Player 9 you will
want to change this to return the server data you want to indicate an error and then use SWFUpload's
uploadSuccess to check the server_data for your error indicator. */
function HandleError($message) {
header("HTTP/1.1 500 Internal Server Error");
echo $message;
}
So the uploadSuccess function is expecting a response from the server. How would I go about encoding and sending that said response using "header()"?
If I use this:
header("HTTP/1.1 200 Uploaded File was Successful");
SWF Upload returns success, but that message does not come through to the uploadSuccess function.
I was also looking for a way to display an error message from the server. Based on the comments above, I was able to get this to work by updating the uploadSuccess() function in handlers.js to:
if (serverData != null && serverData != "ok"){
progress.setError();
progress.setStatus(serverData);
} else {
progress.setStatus("Complete.");
}
Meaning, if the response is anything other than "ok" it will be displayed as an error. This feels pretty hacky. I'd much rather be able to send a non-200 response from the server and have it show the error message from that, but as far I can tell that's not possible. Also, the way I've got it set up wouldn't work for custom messages that aren't errors.
Related
I'm creating a global high score table. The JavaScript sends the username and score to the PHP through some AJAX functions and POST. The PHP script then takes the variable, and compares the score values to the file on the server. It then puts the new score where it should go on the score table, and rewrites the file.
I had it working last night, but now, when I call the function, it displays my code instead, and firebug gives the error, "No element found". I'm not sure what I did between then and now, but I just can't figure this one out.
This is my first time using PHP and AJAX, so I'm not sure where or what the error is.
Any help would be appreciated!
The exact error:
Timestamp: 4/13/2013 1:59:18 PM
Error: no element found
Source File: file:///C:/wamp/www/ajax.php
Line: 84, Column: 3
Source Code:
?>
If I cannot help you solve this issue, I will delete this answer, but I wanted to post it like this so you can better read my suggestions.
Start by changing your HandleResponse function to this:
function HandleResponse(response)
{
console.log(response);
document.getElementById('ResponseDiv').innerHTML = response;
}
and post the result that appears above the error, in firebug.
What we are doing here is adding a way for us to see if any data was actually returned from the AJAX request. A call to console.log tells the browser to print the given argument to the console (in your case, firebug).
UPDATE 1
In your comments, you stated that nothing displayed when you logged the value of response. This means that you received nothing back from the server (in terms of data, at least).
My next suggestion is that you change the call to MakeRequest to the following:
<input type='button' id="test" onclick='MakeRequest("*");' value='Global Highscore Table'/>
Like before, leave the console.log line in the HandleResponse method, and post the result that appears above the error in firebug.
Here, we are setting your MakeRequest to make a request that passes a wild-card query parameter. At the time of this suggestion, I did not realize that the requested file expected two arguments, nor that passing a wild-card would error the script. However, this was still a good thing to do, as we found a new error, which tells us that the request is being received.
UPDATE 2
Now, cut and paste everything from your "ajax.php" file to your notepad or another, similar application. Then, set the following to be the only content of the "ajax.php" file:
<?php echo "Request received and response sent"; ?>
Again, post the result of the console.log.
Here, we are taking a step back from fixing the complex code, and we are going back to the basics. All we want to do, here, is verify that we can both send the request and receive a response.
If "Request received and response sent" is successfully returned as the response of the request, then we know that the error lies in ajax.php, and not in the request. If it is not, we know that there is a problem with the request (be it a server issue or the request, itself). If the latter is the case, there could still be a problem with ajax.php, but we must first fix the request.
UPDATE 3 (final solution)
Issue was found to be due to not correctly running on the local server.
I am trying to make a simple AJAX calling in PHP and have a problem with Internal error 500. When I click on the link, so the data are successfully loaded - this I see through FireBug, but I got the error above. It's on localhost.
When I try to set to the URL of a browser the address, that is called by AJAX, so the content is successfully loaded.
Where I should start to search the problem - or what could be wrong?
EDIT: in apache log is nothing weird, looks fine.
If after checking your php error log you don't find any issues, could it be your javascript AJAX call expects results to be returned in a specific format like JSON?
If this is the case, you need PHP to set the correct content type header when it is responding to the AJAX call, like so:
header('Content-type: application/json');
So in context, this might look something like:
$some_data = array(
'user_id' => 47,
'first_name' => 'Mike',
);
header('Content-type: application/json');
echo json_encode($some_data);
Look in the PHP error logs, or perhaps even your web server's error log.
Or if your script spews out errors to the client (which it hopefully doesn't do, at least not in production), try taking a look at the response in Firebug.
You most likely have a bug in your PHP. It doesn't matter if it is an AJAX call. Look at your server logs.
Before this question gets stamped as a duplicate, I am sorry! I've read ALL the duplicate questions and if anything, it has confused me even more. So maybe this question is slightly different.
I've written a little Javascript library that makes ajax calls and fetches and parses information from the graph facebook API.
This enables me to pretty much show all my page status' on my web page. However I'm just about to launch, and I have done as much testing as I can.
However. I'm sure errors will occur, and I've written many error catches blah blah blah.
What I want to do, is save all my errors in a xml file.
So when an error occurs, I want the javascript to load the xml file from the server, add the errors, then save the changes.
I know how to load the xml doc using XmlHttpRequests, And I'm sure I can figure out how to modify the xml just by using dom manipulation.
All i really want to know is. How do i save these changes? does it save automatically?
Or do i have to "somehow" pass the updated xml version to php and get that to save it?
Im not quite sure how to go about it.
I would use mySQL and php but that means "somehow" passing the error information to php, then saving it.
However id much prefer XML seeing as I'm the only person that will be reading the xml file.
Thanks very much.
Alex
Or do i have to "somehow" pass the updated xml version to php and get that to save it?
Yes, you'll want to use an XML HTTP request to send the XML DOM to the server where PHP can save it:
function postXML(xmlDOM, postURL, fileName, folderPath){
try{
// Create XML HTTP Request Object
oXMLReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");
// Issue Synchronous HTTP POST
oXMLReq.open("POST",postURL,false);
// Set HTTP Request Headers
if(fileName != null){ oXMLReq.setRequestHeader("uploadFileName", fileName); } // What should file be named when saved on server?
if(folderPath != null){ oXMLReq.setRequestHeader("uploadDir", folderPath); } // What folder should file be saved in on server?
// SEND XML
///WScript.Echo(xmlDOM.xml);
oXMLReq.send(xmlDOM.xml);
return oXMLReq.responseText;
}catch(e){
return "postXML failed - check network connection to server";
}
}
I have been searching the internet and the jqGrid documentation, but I can't find anything about the format of a JSON response to a create, update, delete (CRUD) operation. Surely there should be a JSON message that is returned from PHP to jqGrid to tell it whether the CRUD operation was successfull? What is the format of this message and how would you code the javascript for the jqGrid to respond to that message? I'm not a very good programmer, so complete code answers would be greatly appreciated.
Thanks
You don't need to use a response for create, delete and update.
E.g. if you do an create operation you are calling an "ajax operation" which adds your data into a database.
There are now two possibilites:
Create Operation succeeds
just return nothing, means empty string
(as long as a 200 response is received by jqgrid, everything is fine)
Create Operation failed
just throw an Exception with a modified response header
If jqGrid receives an non 200 response code it shows you an error itself!
try {
// insert something in your db
// ok = true means everything fine
// ok = false means something unpredictable happened
if (!$ok) {
throw new Exception('error');
}
} catch (Exception $e) {
header("Status: 500 Server Error caused by dbinsert jqgrid");
var_dump($e->getMessage());
}
Sorry for the code, but it was the fastest I get out of my brain now :)
I use jqGrid in combination with the Zend Framework and ZF uses 500 Response codes for Exceptions by default (at least my template)
After a successful update/delete/create you have to refetch the whole jqGrid data.
jQuery("#your_jqgrid_id").jqGrid().trigger('reloadGrid');
There is afaik no other mechanism. (Used it last about 6 months ago, maybe that changed)
If you want to implement your own error/success handling, just define your own message in whatever format you want and handle it in the ajax success function callback.
If you need more code and it is not urgent, just drop me a comment.
One additional advice: Don't expect to understand jqGrid immediatly. Take your time, try some things, play with it. It will take some time before you feeling comfortable with it.
Should I rely on http status codes? Or should I use some kind of special response?
My server is running PHP and producing simple JSON responses.
I'd personally say you should do both! Return an appropriate 4xx/5xx status code to show something went wrong and include a message into your JSON response.
E.g. for a successful request:
{
"success": "true"
}
And for fail (e.g. 405 Method not allowed):
{
"success": "false",
"message": "Requested data not available"
}
It could be better if , you can go with an Entity with Two Properties as : Status & Message.
You inherit your query result entity from the above entity.
If the operation is successful then Set the Status to True else set Status to False and set appropriate error message into the Message property of above entity.
Remember that it is better you don't put exact database errors into the client side displays. That may increase the chances of hacking attacks, instead you can log the exact message on the server so that the concerned people can check the messages, if something goes wrong.
So, if Status=True then only the client can further process the message (like accessing the properties or displaying them etc.), else if Status=False, then the error text set at the data access logic, into the Message property will be displayed.