I have a search page done using Laravel. On that page there is a button which makes an AJAX call to another url. That page is paginated, so the user can be on the first, second or last page.
My problem is, How can I bring the user back to the same page and point that he was.
Or, Is there a way to just call a method to perform some actions on the database?
Thats my Ajax Call:
$.ajax({
url: $(this).attr('data-href'),
dataType: 'html',
success:function(data) {
$('#ajaxResponse').html(data);
$.growl.notice({ title: 'Voto', message: 'Computado com sucesso' });
$(this).find('.fa').toggleClass('fa-heart-o fa-heart');
}
});
I know if i take the $('#ajaxResponse').html(data); bit it is going to perform the change but not update the numbers that i need. Any ideas?
Here is the documentation for pagination in Laravel with JSON. As you can see, when you paginate your data, the resulting JSON object will contain information about the next and previous pages. Update the links your users click with the provided information and they should see the correct data.
You can try to store the actual page in a session key and use a controller to check this key and display the page that you want. In this case you can keep your ajax call as it is and change only your laravel controller ad view.
I read the manual about location hash, but seems I didn't understand it.
I do like this:
$.ajax({
url: "/tst.htm",
success: function(data){
$("#center").html(data.content);
location.hash="#ACHTUNG";
}
});
and when I press 'back' in the browser, I return to the blank browser page, not to the page I created to test how location hash works.
I need a simple answer how to workaround this most common and simple ajax-based task, not please again a reference to the manual.
I have a modal form (using bootstrap) that I use to add a user. This form is wired to a 'addUser' method via RequestMapping in my Controller. Adding a user works fine.
Is there a simple way I can populate the same modal form to edit existing user details after clicking an edit button? Do I have to make an AJAX call to a REST endpoint to populate the form, or is there a better way of doing this?
I'm using Spring Boot.
Thanks,
Jerry
An AJAX request would be your best bet, otherwise you'd have to load all the editable user properties ahead of time when you load the page of existing users and store them in memory or on the page somehow. It's not the most efficient solution though because you're loading all those properties for all users, every time you reload the page. If you only have a handful of users, that might be ok for you, but if you're dealing with a large set of users, then that will make for longer request times.
Yes you can make a ajax request and get the modal details in form of Json or Xml.
Below example retrieve the user details and set it into modal form variables like userName
$.ajax({
type: "post",
url: "Url to get the response",
cache: false,
data:'userId=' + $("#userId").val(),
success: function(response){
var obj = JSON.parse(response);
$('#userName').val(obj.userName);
},
error: function(){
alert('Error while request..');
}
});
I've come across a problem that if I use jQuery's Get method to get some content, if I click back, instead of it actually going back one page in the history, it instead shows the content returned by the Ajax query.
Any idea's?
http://www.dameallans.co.uk/preview/allanian-society/news/56/Allanian-test
On the above page, if you use the pagination below the list of comments you will notice when clicking back after changing a page, that it shows the HTML content used to generate the list of comments.
I've noticed it doesn't always do it, but if you click on a different page a few times and click the back button, it simply displays json text within the window instead of the website.
For some reason, this is only affecting Chrome as IE and Firefox work ok.
Make sure your AJAX requests use a different URL from the full HTML documents. Chrome caches the most recent request even if it is just a partial.
https://code.google.com/p/chromium/issues/detail?id=108425
Just in case you are using jQuery with History API (or some library like history.js), you should change $.getJSON to $.ajax with cache set to false:
$.ajax({
dataType: "json",
url: url,
cache: false,
success: function (json) {...}
});
Actually this is the expected behavior of caching system according to specs and not a chrome issue. The cache only differentiate requests base on URL and request method (get, post, ...), not any of the request headers.
But there is a Vary header to tell browser to consider some headers when checking the cache. For example by adding Vary:X-Requested-With to the server response the browser knows that this response vary if request X-Requested-With header is changed. Or by adding Vary:Content-Type to the server response the browser knows that this response vary if request Content-Type header is changed.
You can add this line to your router for PHP:
header('Vary:X-Requested-With');
And use a middleware in node.js:
app.use(function(req, res) {
res.header('Vary', 'X-Requested-With');
});
You can also add a random value to the end of the ajax url. This will ignore the previous chrome cache and will request a new version
url = '/?'+Math.random()
Just add the following header to the Response headers :
Vary: Accept
I couldn't give different urls for each ajax request as it was an ajax pagination, declaring no cache on headers did nothing, so i included a little javascript in the view only when headers were for the ajax request:
<script>
if (typeof jQuery == 'undefined') {
window.location = "<?php echo $this->here; ?>";
}
</script>
It is a dirty trick, but it works, if the ajax content is normally loaded, the container has Jquery loaded so it does nothing. But if you load the ajax supposed content without the surrounding content, Jquery is missing (at least in my case), so i redirect to the current page requesting a normal GET page with all the headers and scripts.
If you put it in the top of the page, the user won't notice because it won't wait till the page loads, it will redirect as soon as the browser gets this 4 lines...
Replace here; ?> by the current url in your APP, this was a CakePhp 2.X
Still had this problem in 2021 in Chrome.
Problem is doing underlying ajax request to the same url as the one the user is currently on.
I was working in Symfony and the complete fix that did the work for me was
$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('max-age', 0);
$response->headers->addCacheControlDirective('s-maxage', 0);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);
/**
* from https://stackoverflow.com/a/1975677/5418514
*
* The HTTP request header 'Accept' defines the Content-Types a client can process.
* If you have two copies of the same content at the same URL, differing only in Content-Type,
* then using Vary: Accept could be appropriate.
*/
$response->headers->set('Vary', 'Accept');
The #abraham's answer is right.
I just wanted to post a solution for Rails: all you need is just add different path to routes.rb.
In example, I have resource :people and I want to compose index page from ajax parts one of those is list of people. The straightforward way is to create index.js.erb and to load partial via ajax using url: people_path. But here occurs the issue.
So, for Rails, it needs just add a different route, like
get 'people_list', to: 'people#index', as: :people_list, format: :js
If I want to use index method of a laravel controller returns both html and json response, I add a get parameter at the end of the endpoint to pass browser caching:
axios.get(url, {params: {ajax: 1}})
Although I read dozens of answers I could not find a solution.
I'm using MVC 3 with Razor. I have a simple Form with client validation via ajax. This part works fine. My problem is: In the update Action of my Controller I want to redirect to another Action. If the user disables Javacript, this works fine. But with javascript/ajax enabled, the redirectaction doesn't seem to work. Instead it looks like if some kind of partialview or something like that is executed.
My Controller/Action-code:
Function UpdateItem(Item As CItem) As ActionResult
' some validation code, save etc.
if everythingok then
Return RedirectToAction("Updatesuccess")
else
Return RedirectToAction("EditItem")
endif
End Function
My html page looks like (shortened/pseudo):
Logo image
H1
some text
<form>....</form>
When the form is submitted via ajax the new html code is added beyond "some text", so the form is replaced but everything above the replaced form stays on the page.
When ajax/javascript is disabled then after submit a whole new page is loaded. I checked the http headers and noticed, that with ajax there is no redirect (which is logical in some way because it is ajax).
What can I do? I want to redirect to a new page.
Is it possible to disable the ajax-submit and only use the "normal" form-submit?
I like the client validation via ajax while the user enters data and I want to use this, but for me it would be good enough, if the submit would be a "normal" submit.
I hope someone understands what I want and can help me.
Thanks.
I'm not a 100% sure I understand your question, but what the heck, don't downvote me :)
The problem is, redirect works via sending a HttpResponse with the redirect indicated in the headers, which the browser understands. If you submit via AJAX, it's not the browser that handles the request, it's your OWN JS code.
Here is the trick: instead of returning a redirect, return the Url (preferably as json), and then redirect manually using window.location.
I'm not fluent in VB, here is how I'd do it in C#:
var url = new UrlHelper(this.ControllerContext.RequestContext);
var link = url.Action("UpdateSuccess");
return Json(new {link});
and then in jQuery:
$.ajax({ method: 'POST',
url: 'your post url',
success: function(result) {window.location = result.link; },
// ... (passing form etc)
});