Sachin
Sachin

Reputation: 3782

Change url on AJAX call

I am making a blog app, and in that I want to provide the a Save button which will update the changes to the DB via Ajax call. This is fine as long as I am saving a previously created blog, but I am having problems when I make the blog for the first time.

The issue is that for any new blog I have the same url which is

blogs/new/

However but for editing or publishing blogs which have already been created I have a url like this

blogs/1/my-first-blog/

Here 1 is the author id and second field is the slug value. I make use of these values when I save this form via Publish or Preview button. What I want to do is to somehow set these values when I make the save AJAX call. So that when the user presses publish the blog is already saved in the DB and these variables are sent to the view and it can work correctly.

Upvotes: 2

Views: 4002

Answers (3)

LetTheWritersWrite
LetTheWritersWrite

Reputation: 99

I'd like to update this information with the fact that front end frameworks solve this problem with routing now. VueJS being one example. https://router.vuejs.org/

Upvotes: 0

Nick Benedict
Nick Benedict

Reputation: 557

Pass the author id, slug value, and the text for the blog being created to the web service or webmethod, and do the creating of folders and saving the blog data in the service.

Then you can just edit the string you want to pass to window.location.

var id = "userid945";
var slugvalue = "foo";

var url = "/blogs/" + id + "/"+slugvalue+"-first-blog/

window.location = url;

Upvotes: 1

chawkinsuf
chawkinsuf

Reputation: 1401

Well, in order to change the url after the AJAX call completes you would set:

window.location = '/blogs/1/my-first-blog/';

However, maybe AJAX is not the best option to process this request. If you are simply going to redirect to a new page after the request completes, why are you using AJAX?

It would be a more standard practice to submit the form without AJAX and send a redirect header for the new page if the request is successful.

Upvotes: 2

Related Questions