I'm having ongoing problems with laravel 4.1 sessions and getting unexpected behaviour.
Depending on how I call the controllers method the session either works or doesn't My app makes a call to a POST route - to add items to a cart which is a session. For some reason the session does not get updated.However if I make a call to the same function with a GET request the function works as expected.
My routes.php contains these two routes:
Route::get('testAdd', array('uses' => 'ProductsController#addToCart'));
Route::post('products/addToCart', array('uses' => 'ProductsController#addToCart'));
Both point to the same method
The method is currently this (for testing):
public function addToCart() {
Session::put("addcarttest", "add to cart");
return json_encode(Session::get('addcarttest'));
}
If I call the function with the POST method (with form data) I get the expected result and the contents of the session.
However If I then check for the session (using a profiler) it does not exist. The data did not persist.
If I then call the same method using the GET route, I get the expected result but importantly the session persists.
I thought maybe the POST method deleted sessions however once it exists it stays there - if I use the GET method and the sessin exists if I then try the POST method example again the session remains in place - so the POST method doesnt delete the session.
This is driving me crazy - I've lost a lot of hours over this and can't see why.
Am I missing something over how Laravel handles POST v GET ? Why would two different methods make a difference to underlying functions?
What do I need to do to make the session work correctly with POST?
Update:
I've now tried database driver for the session and am getting the same behaviour.
I've taken my test a stage further- I created a basic form and submitted to the url and the method worked as expected. My current form data is submitted by jquery ajax and assumed they were fairly identical in behviour.
My jquery submit function is this:
$.ajax({
url: '/products/addToCart',
type: 'POST',
async: false,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
return false;
I set async to false - I assume to await the server response. (doesnt work if true either).
So the problem is a subtle difference between a form submit and an ajax submit. Both methods are hitting the same route and method - one saves the session data - the other one doesnt.
How can I overcome? Jquery submit is essential to this part of the app.
Success!
I found a similar problem relating to laravel 3. For the session to persist in an ajax call I need to return the response correctly.
return json_encode($response);
This is causing the problem. It's not it appears a valid response to enable the session to persist. I changed it to:
return Response::json($response);
This enabled the session to persist!
For some reason a normal form submit or call to the method allows the first one but ajax does not.
I've seen references elsewhere about echo statements in the method affecting the session data but did not think I had any - the return I suppose must behaving similar to an echo
Happy now (till the next problem)
This is the post that triggered the solution:
http://forumsarchive.laravel.io/viewtopic.php?id=1304
i have same issues, but when returning XML Response, not JSON.
I fixed it using session save.
\Session::put('LOGADO.ID_LOJA', $id_loja.time());
\Session::save();
This fixed everything inside AJAX Calls.
This is in reference to the solution that Ray gave.
I had a very similar problem, which your solution resolved. Initially, I had the following on my Controller:
echo json_encode(array('auth' => $auth));
I changed this to:
return Response::json(array('auth' => $auth));
However, this was only part of the solution. In my javascript file, I initially had:
data = $.parseJSON(data);
Which, if I had kept the echo in the controller...would have been needed. apparently Laravel will do some magic behind the scenes when using Response::json() so that the data that is returned is already parsed. Removing that line in my javascript file made everything happy again :)
Related
I'm having ongoing problems with laravel 4.1 sessions and getting unexpected behaviour.
Depending on how I call the controllers method the session either works or doesn't My app makes a call to a POST route - to add items to a cart which is a session. For some reason the session does not get updated.However if I make a call to the same function with a GET request the function works as expected.
My routes.php contains these two routes:
Route::get('testAdd', array('uses' => 'ProductsController#addToCart'));
Route::post('products/addToCart', array('uses' => 'ProductsController#addToCart'));
Both point to the same method
The method is currently this (for testing):
public function addToCart() {
Session::put("addcarttest", "add to cart");
return json_encode(Session::get('addcarttest'));
}
If I call the function with the POST method (with form data) I get the expected result and the contents of the session.
However If I then check for the session (using a profiler) it does not exist. The data did not persist.
If I then call the same method using the GET route, I get the expected result but importantly the session persists.
I thought maybe the POST method deleted sessions however once it exists it stays there - if I use the GET method and the sessin exists if I then try the POST method example again the session remains in place - so the POST method doesnt delete the session.
This is driving me crazy - I've lost a lot of hours over this and can't see why.
Am I missing something over how Laravel handles POST v GET ? Why would two different methods make a difference to underlying functions?
What do I need to do to make the session work correctly with POST?
Update:
I've now tried database driver for the session and am getting the same behaviour.
I've taken my test a stage further- I created a basic form and submitted to the url and the method worked as expected. My current form data is submitted by jquery ajax and assumed they were fairly identical in behviour.
My jquery submit function is this:
$.ajax({
url: '/products/addToCart',
type: 'POST',
async: false,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
return false;
I set async to false - I assume to await the server response. (doesnt work if true either).
So the problem is a subtle difference between a form submit and an ajax submit. Both methods are hitting the same route and method - one saves the session data - the other one doesnt.
How can I overcome? Jquery submit is essential to this part of the app.
Success!
I found a similar problem relating to laravel 3. For the session to persist in an ajax call I need to return the response correctly.
return json_encode($response);
This is causing the problem. It's not it appears a valid response to enable the session to persist. I changed it to:
return Response::json($response);
This enabled the session to persist!
For some reason a normal form submit or call to the method allows the first one but ajax does not.
I've seen references elsewhere about echo statements in the method affecting the session data but did not think I had any - the return I suppose must behaving similar to an echo
Happy now (till the next problem)
This is the post that triggered the solution:
http://forumsarchive.laravel.io/viewtopic.php?id=1304
i have same issues, but when returning XML Response, not JSON.
I fixed it using session save.
\Session::put('LOGADO.ID_LOJA', $id_loja.time());
\Session::save();
This fixed everything inside AJAX Calls.
This is in reference to the solution that Ray gave.
I had a very similar problem, which your solution resolved. Initially, I had the following on my Controller:
echo json_encode(array('auth' => $auth));
I changed this to:
return Response::json(array('auth' => $auth));
However, this was only part of the solution. In my javascript file, I initially had:
data = $.parseJSON(data);
Which, if I had kept the echo in the controller...would have been needed. apparently Laravel will do some magic behind the scenes when using Response::json() so that the data that is returned is already parsed. Removing that line in my javascript file made everything happy again :)
I'm using Joomla for a project, and there's some Ajax requests happening to populate data. I generate a Joomla session token in the PHP view, and tack this onto the URL of the Ajax request endpoint, which is also a PHP page, and validates the token before returning data.
Something like this:
// view.html.php
$script = "var ajaxurl = 'index.php?task=ajaxFunction&".JFactory::getSession()->getFormToken()."=1';";
$document->addScriptDeclaration($script);
// ajax.js
var request = new Request.JSON({
url: ajaxurl,
onException: function(headerName, value) {
// etc.
}
});
// controller
public function ajaxfunction()
{
JRequest::checkToken('get') or die( 'Invalid Token!' );
// do other stuff
}
This works just fine until caching is enabled.
The problem is that the view.html.php file, when Joomla uses its internal caching, is cached with the token already set-- so anytime a browser requests the page, it pulls the cached token along with it, meaning the controller will return an invalid Token error.
I know in earlier Joomla builds caching flat out didn't work. Is there a way to make this work in Joomla 2.5+, short of just disabling the Joomla cache? I can't find any way to exclude a single view from caching.
Perhaps you may want to send the request as POST instead of GET, which won't use Joomla caching.
ajax.js
var userToken = document.getElementsByTagName("input")[0].name;
var request = new Request.JSON({
url: 'index.php?task=ajaxFunction&'+ userToken +'=1',
onException: function(headerName, value) {
// etc.
}
onComplete: function(res) {
// etc.
}
}).post({});
controller
JRequest::checkToken('get') or die( 'Invalid Token!' );
Stick this at the top of your template file (before all other input tags), it will create a hidden input field containing a token, which will eventually be replaced with the non-cached one on render
tmpl/default.php
<?= JHtml::_('form.token'); ?>
Sometimes I work with Ajax and Joomla and really do not have this problem. Well, maybe the way you is working, is maybe better try a diferent way of do the cache, so if you really have no hope , just fork System - Cache from Joomla, and on your fork make it does not cache what you do not want. If in your project is possible to handle how you do your cache, you can also do not use Joomla Cache and use it with Varnish or similar.
I think it should be better than how you're doing: Joomla have one group to include one more "standard" way to work with AJAX, and you can see one Proof of Concept Here:
https://github.com/betweenbrain/Joomla-Ajax-Interface
Discussion here
https://groups.google.com/d/msg/joomla-dev-general/i1syYWshGsY/3udixCaRnRAJ
Also, another aproach about use of Ajax is here
https://github.com/juliopontes/joomla-ajax-handle
By looking at the method signature of JSession::getFormToken() you should be able to force a new token by calling getFormToken(true).
This should circumvent any caching issues you're experiencing.
The way I do it in joomla with a very similar set up is inject the value with JavaScript. The page is cached without the token and JavaScript adds it before making the request
You can pass the value with cookies or another ajax request. Cookies works best fort me
i am trying from my main web page to check and in some cases send a variable via URL like this (http://192.168.0.110/CVAL.CGI?A0=1) this is to modify the status of something in my web page depending on the value seen in the url.
Sounds like you need Ajax.
There are many javascript libraries that can help you with this functionality such as jQuery, Prototype, or one of the many found on this page.
Hope that is what you are looking for and is helpful. Next time post more specific details so we can answer your question correctly the first time. Specific, detailed examples of what you want to do are also helpful.
UPDATED:
Here is an example using the Prototype Javascript library given your example form:
new Ajax.Request('/CVAL.CGI?A0=1', {
method: 'get',
parameters: { anotherValue: 'something' },
onSuccess: function(transport) {
alert(transport.responseText); // this is what the server returned
}
});
This would result in a request to /CVAL.CGI?A0=1&anotherValue=something. Whatever CVAL.CGI returns in response to that request, is available from transport.responseText.
This way, the user never has to leave the page or submit a form but it is all done behind the scenes. Your parameters can be any values you want to send which you can grab from form fields or other user input. You can return responses in JSON to make accessing the return data easier as well. Change method from 'get' to 'post' to do post requests.
I am very new to this javascipt, jquery world and I am having great difficulty getting to grips with it.
I have got the following in my HTML
$(document).ready(function(){
$("#frmEnquiry").validate();
});
</script>
It works although I do not understand, what is going on behind that statement, especially as it validates on each field entry (which is wonderful).
I have action="" in my form definition and a submit button and I have created a process.php file which further validates and sends an email, but I have no idea how I call that php file or where I put the call or what the syntax is for doing it. I am assuming it is based on a return from validate().
Also what is the correct procedure for returning from the PHP file with either success or failure messages.
If anyone can help at a simple syntax level, I would be most grateful as I have looked at so many possible solutions, my head is just totally confused.
I apologise for probably asking a very common question, but when you are just starting, it is difficult finding an example which you fully understand.
Well, there are two general approaches:
Oldschool form processing: you set <form action='process.php'> so your request is submitted to that page. Browser reloads and displays the content that you have rendered in process.php
Ajax-submit: this way you leave action blank, block submitting with something like <form onSubmit = 'return false'> and then send content using one of jQuery's AJAX-methods: get, post or ajax. It looks something like that:
$(document).ready(function(){
if($('form').validate()){
$('form').submit(function{
//Personally I prefer ajax as get and post are just shorthands for this method
$.ajax({
url:'process.php',
dataType:'json',
data:{name:nameVal, value:valueVal}
success: function(){
/*server returned some data, process it as you wish*/
}
});
});
}
});
Don't forget the principles:
PHP is executed server-side
javascript is executed client-side
Thus, PHP will only be executed if you are calling the server, meaningly, if you call an URL (http://mydomain.com/MyPHPpage.php) or if you are calling your server through an AJAX request (which is seemingly the same, except there is no reload client-side).
On the contrary, javascript is called only client-side. So the code used to validate() your form is called only on the client-side (except if you have a specific function behind this that would call the server). Hence, the javascript will use the parameters you gave him to validate the form without calling the server. This is a very good way not to overload your server with un-wanted request (empty fields, wrong e-mail addresses...).
Anyway, you can still have some other checks on your server side (checking in your database if the user exists...) and return another message to the user.
To answer your question, i'll ask some other ones: what are you trying to validate? do you want to check client-side or server-side? which data and for which purpose?
You need an AJAX call to your PHP script. If your form data is valid you would do such a call. You can asign a success callback to the ajax request where you can process the return data from PHP and either update data, display a error message or something else. From PHP you can return an object or an array where you detail if errors occured and of what type. More about AJAX -> http://api.jquery.com/jQuery.ajax/
In your case it is reasonable to perform form validation via javascript by checking the value of each field.
There is no need to send data to the server and receive information about their correctness. This method complicates the validation and is not improve protection against bad data.
I'm trying to submit a form using jquery in symfony 1.4, but CSRF attack detected error pops up each time. This is the code i use to submit the form data:
$.ajax({
type: 'post',
cache: false,
url: $('#assign-form form').attr('action'),
data: (
'activity[id]=' + $('#activity_id').val() +
'&activity[_csrf_token]=' + $('#activity__csrf_token').val() +
'&activity[assigned_to_user_id]=' + $('#activity_assigned_to_user_id').val() +
'&activity[assigned_to_group_id]=' + $('#activity_assigned_to_group_id').val()
)
});
Am i missing something?
Thanks,
Radu.
One thing to look at is whether the Form object that is validating the input is the exact same class as the the one that generated the token. By default, the class is used in the generation of the CSRF token.
If, for example, you had an instance of a subclass of a form used to generate the form html and then you posted to an action that used the ancestor form class, the validation would most likely fail by default.
It's possible to override the token creation if it turns out this is your issue.
Also, have you verified that the value of the token field actually includes a token? A console.log() may help you discover this.
Um...as I look closer at your code, another thing to look at is that you're building a query string to pass in 'data'. Have you tried passing an actual JSON-style object instead?
Usual cause is that the browser is not accepting cookies - have you checked that the cookies are being returned as expected (e.g. iehttpheaders, wireshark, tamperdata)?
Did you configure the secret in settings.yml?
C.
This little issue has driven me mad in the past.
If it's acceptable to you to disable CSRF protection for this particular form (which it often can be), you can add the following to your Form class in /lib/form/... folder:
public function configure ()
$this->disableLocalCSRFProtection();
I believe it's possible to disable CSRF for a particular instance of the form as well if you don't always wish to have it disabled, but I haven't tried this / don't have the code at hand.
Does the session cookie really received it with ajax query ? your session cookie as returned by server should be exactly the same with a plain HTTP request (for instance the first request initiating session management) and with XMLHttpRequest, otherwise you'll get trouble with CSRF.
$('#activity__csrf_token').val()
Did you mean to have a double underscore in that element id?