I have a single entry into my site: http://mysite.com/index.php?this=that&andthis=that. I use it for all tasks such as originally displaying a page, submitting a form, and ajax calls. I then route it to the appropriate task.
Are there any reason why it is preferred to have another entry into the the site for ajax calls such as http://mysite.com/ajax.php instead of index.php?
As I know in my modest experience, there is no technical reason for separating the both behaviors.
But you might need to have some specific treatment, like when you have an ajax request you need to handle errors and display them to the user differently.
e.g: for exceptions, you may need to enclose your code in a try catch, and return the error message in a json format:
try{
// your AJAX request code here
} catch (Exception $e){
// threat error here
$msgErr = $e->getMessage();
echo json_encode( array( "success"=>"failure", "msg" => $msgErr ) );
}
and you show the message to the end user in an alert message box, so once you have such needs it more logic to make a separate entry point for ajax request in order to automate your behavior instead of making again every time.
I hope I've made my tought clear enough, if not I would be happy to try again.
I hope it helps.
Related
We use Varnish (likely to switch to Cloudflare) to cache the HTML of our pages. Occaisionally we would like to display a message to the user, which is flashed in the session: Session::flash('user_message', 'You cannot perform that action');.
The next page loads, and then there's an AJAX (to /ajax/message) call to check the server if there's a message to flash. Obviously the page load will absorb the flashed message, so what we've done in the BaseController is this:
if (Session::has('user_message') && !str_contains(Request::getPathInfo(), '/ajax/message')) {
Session::flash('user_message');
}
Our AJAX call simply states:
$response = [];
if (Session::has('user_message')) {
$response['user_message'] = Session::get('user_message');
}
return json_encode($response);
Which works, however, the next time a page loads, it will display the same message again! I've tried numerous things (such as Session::forget('user_message')) but to no avail. I'm at my wit's end to solve what should be a really trivial task. Does anyone know of a better way to do this or what's going wrong?
Thanks!
So, I have a form om my webpage which insert into a database. It throws a die(mysql_error()) into a blank page if not all fields have a value. I want this error message pasted over my form, but not loose the values already inputed. I have thought about both reloading the page with a page.php?error=... and making code to check if all fields have value (which will be long and feels unnecessary since what I want is already on my screen.
Do you think something like if(field1 has no value | field2 has no value | ....){ don't do anything and do rest is the best and most effectiv?
But if I want show which field is missing aswell, it will be a LOT of code...
You don't really want to output the exact die() error message, as the user won't be able to understand it, and chances if they would understand it, they're potentially the kind of users you don't want being able to see it!
Not really sure of your situation (as you didn't post any code) but from what you've said I'd suggest using try & catch, and handling any errors that occur, for example:
try {
// perform your database query
} catch (SQLException $error_msg) { // catch the error if goes wrong
//$error_msg contains the information from the error
return 'We`re sorry, your form submission could not be handled at this time.';
}
// if we got to this stage, there were no problems
return 'success';
That way, you can verify the reasons why the Exception occured, catching the real error message so they don't see it, then returning some other output back to the user in a format that they can understand.
in all of your input fields set the html value attribute to value = <?php echo #$_POST['fieldname'] ?>
also, instead of using die, use $error = mysql_error(); and then echo $error later on
Is it a good practise, to use the php session object, to store several of my variables, can be arrays of request results.
I need this method, because I would like to do the request in a php file, store the result and immediately, (depending on result) redirect to a page,
It's probably not the best way, that's why I'm asking
thx for any advice,
edit: structure:
index.html
handler.php
view1.php
in index.html, I've got a
<form action="handler.php" ...
in handler.php, I construct a request and get a result,
if ($result->success)
header("location ./view1.php");
else
echo 'failed';
in view1.php, I would like to list the result array
Webshops do it - so why shouldn't you?
Some of the larger eCommerce frameworks store complicated data and objects in sessions and PHP handles this pretty well.
That's what sessions are for! So the general answer is "Yes: it's a good practice".
Here are some alternatives, however:
Consider using ajax calls to update parts of the loaded page without reloading it;
Cookies - not good for big amount of data, but generally can live longer than a session. Not useful in your particular case, however;
SQL servers are usually well-optimized, and when your query returns lots of rows and you cut those into sections with a LIMIT clause, or just repeat exactly the same request soon after the first time, the subsequent requests aren't of such a big load for the database server.
I just seen your update to the question.
AJAX can do the trick for you the best. I can imagine it all done within a single web page:
form data is submitted by an AJAX call to you handler.php, which..
returns either a JSON-packed array of results or a short string NOT FOUND, for example.
Then, the JS on your page either creates a new DOM element - a table, or a set of div's, with the returned results, or just creates a new div with some sad toon face and a "we didn't find anything' message.
// set session
session_start();
$_SESSION['my_session'] = array('var1' => 'value1', 'var2' => 'value2'); // your result list
session_write_close();
// get Session
echo ($_SESSION['my_sesson']['var1']);
if ($result->success)
header("location ./view1.php");
else
echo 'failed';
This is not good practice to use redirects to route requests. You can do it without additional request from the user.
Like this:
if ($result->success) {
include(dirname(__FILE__) .'/'. 'view1.php');
} else {
echo 'failed';
}
Thus, all variables from handler.php will be available in view1.php.
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.
I am using Cakephp but this is a MVC/php doubt
letting the view display the message
vs
echo 'Invalid Data'; exit;
I would like to know is there any pitfalls in the second case like memory leak etc.. Which one is better
EDIT
In case of a ajax call is exit good. and what about memory leak and other issues . Are all variables deallocated
You should use a custom ExceptionHandler (set_error_handler / set_exception_handler) and throw an Exception if you encounter any errors (CakePHP should already provide an ExceptionHandler). Make some space in your view and if the ExceptionHandler/ErrorHandler has a message, show it there to let the user know.
Your second code will just produce a blank page containing the little text. Every user will appreciate if you show the message inside your usual page layout instead of producing a blank page (which looks broken to most people).
The Cake tools to signal errors to the user are session messages and error views.
For "passive" actions like view actions, you should throw a 404 or similar, possibly more specialized error, e.g. if the requested model does not exist:
function view($id) {
$data = $this->Model->read(null, $id);
if (!$data) {
$this->cakeError('error404');
}
...
}
See Error Handling with CakePHP.
For any POST action, you should return the user to the view and display an error message using $this->Session->setFlash('Error!') and appropriate error messages for each invalid form field. That's the default behavior of baked views and controllers.
Terminating the whole script with exit makes for a miserable user experience.
In general, you should avoid exit. Exit is an abnormal termination, and programs should not terminate abnormally. Even if an error occurs, there are still many things that needs to be done - cleanup, logging, notifying the user etc. After all, your operating system doesn't reboot every time it cannot open a file.
performance-wise (AJAX cals)
Use exit().
user experience-wise (standard site nav)
Show the error in a proper formated page keeping the user within your site.