I have a set of sessions in a page, which I want to remove using AJAX. i.e click on a link, and without having to navigate for a new page, just remove the session, and show
After your comment to @Laurent Wartel's answer, I assume now you get Uncaught SyntaxError: Unexpected token }
. Now it's clear, you have additional parentheses on end of your click()
function.
In addition, you don't wait for document to load before binding click()
event.
Because of this, jQuery tries to bind event to element that wasn't yet rendered. This is a common pitfall.
To run your code after page loads, you have to wrap it info $(function() { ... }
.
Please, read full explanation here as this is basic, yet very important.
To sum up, correct code is as follows:
<script type="text/javascript">
$(function() {
$('#remove_session').click(function(e){
e.preventDefault();
$.ajax({
url: '{{ url('ajax_remove_session') }}',
cache: false,
success: function(html){
// do something on success
}
}).fail(function(event){
console.log(event);
});
});
});
</script>
It seems like somehow you've deleted that line during debugging, because it is there in your original question, but is not present in source code you've sent later.
Example controller:
use Symfony\Component\HttpFoundation\JsonResponse;
public function ajaxRemoveSessionAction()
{
// Destroy the desired session
$session = $this->getRequest()->getSession();
$session->remove('name');
return new JsonResponse(array('success' => true));
}
Example routing:
ajax_remove_session:
pattern: /remove-session
defaults: { _controller: FooTestBundle:Page:ajaxRemoveSession }
Example twig:
<a href="#" id="remove_session">Remove session</a>
<script type="text/javascript">
$(document).ready(function() {
$('#remove_session').click(function(){
event.preventDefault();
$.ajax({
url: {{ url('ajax_remove_session') }},
cache: false,
success: function(html){
// do something on success
}
});
});
});
</script>
These are just examples need testing.
In your AJAX call you use global event
object, which is not cross-browser and shouldn't be used (e.g. Firefox doesn't have it).
Pass event in function call instead:
$('#remove_session').click(function(e){
e.preventDefault();
// rest of your code
});
If you do it that way, jQuery takes care about cross-browser normalization and proper behaviour.
See also this question to learn more about difference between global event
object and event passed into function.
If it still doesn't work
GET
is default)dataType: "json"
to your AJAX request, but this shouldn't be a problem as Symfony's JsonResponse
should already provide neccessary response headers Check other places
:
is; investigate that line; is the code you have posted here the whole
javascript that you have on your page?Try to put the value of the URL's option between quotes :
url: '{{ url('ajax_remove_session') }}',