Following an AJAX post within the MVC framework, the URL becomes excessively lengthy

http://localhost:53435/Blog/BlogIndex?title=blog+title&seo=seo&content=%3Cp%3Econtent%3C%2Fp%3E%0D%0A

the URL listed above

Whenever I click the save button, the page refreshes and the URL appears like that.

I do not want it, how can I resolve this issue?

This is my controller code:

try
            {
                Blog addModel = new Blog();
                content = content.Replace("<p>", "").Replace("</p>", "");
                addModel.BlogPictureURL = pictureData;
                addModel.BlogContent = content;
                addModel.BlogPictureSEO = seo;
                addModel.BlogTitle = title;
                addModel.BlogDate = DateTime.Today;
                addModel.BlogViewCount = 0;
                db.Blog.Add(addModel);
                db.SaveChanges();

                var lastID = db.Blog.OrderByDescending(x => x.ID).Take(1).FirstOrDefault().ID;
                foreach (var item in Tags)
                {
                    Tags newTag = new Tags();
                    newTag.TagsName = item;
                    newTag.BlogID = lastID;
                    db.Tags.Add(newTag);
                }

                db.SaveChanges();

                return RedirectToAction("BlogIndex", "Blog");
            }
            catch
            {
                return RedirectToAction("Error", "Admin");
            }

This is my AJAX code:

function SaveAllData() {
        var blogFile;

        var elem = $(".dz-details").find("img");

        blogFile = elem[0].getAttribute("alt");

        var elemData = $("#tags").val();

        elemData = elemData.split(",");

        $.ajax({

            type: "POST",
            url: "/Blog/AddBlog",
            datatype: "json",
            traditional: true,
            data: {
                title: $("#title").val(),
                seo: $("#seo").val(),
                content: CKEDITOR.instances.content.getData(),
                Tags: elemData,
                pictureData: blogFile
            }

        });
}

If I perform this action without an AJAX post, there are no issues But when using AJAX, something goes wrong.

Answer №1

It appears that your form is still executing a standard form submit rather than an ajax post. This typically occurs when you have implemented javascript code to perform an ajax submission upon the click of a submit button within a form, but neglected to prevent the default behavior, which triggers a form submission upon button click. Based on the provided url, it seems that your form's method is set to GET, resulting in data being submitted via querystring.

Make sure to intercept and block the default behavior from occurring.

Here is an unobtrusive method for binding the click event to your button

<button type="submit" class="btn btn-primary" style="float:right" id="btnSubmit">

and the corresponding JavaScript function

function SaveAllData() {
  // Include your current code for the ajax call here
}
$(function(){
   $("#btnSubmit").click(function(e){
       e.preventDefault();  // Prevents the default form submission
       SaveAllData();
   });
});

Additionally, if the intent is for an ajax form submission, returning a RedirectResult may not be appropriate. Consider returning a json structure containing the necessary url for navigation (if required).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Performing a JSON RPC request using the getJSON method in jQuery

My attempt to send a json-rpc request to a remote server using the jquery getJSON method is not working as expected. Here is the code I am using: json_string=JSON.stringify(obj); var jqxhr = $.getJSON("https://91.199.226.106/ssljson.php?jsoncallback=?", j ...

How can a color gradient blend be applied to geometry on multiple axes using THREE.JS shader?

After referencing Apply color gradient to material on mesh - three.js I successfully implemented a flower shader that applies a vertical color gradient across the Zinnia. The colors transition from red to yellow vertically, creating a gradient based on he ...

Boost Google Pagespeed score by reducing 'Total Blocking Time' in NextJs

I've recently started using NextJS and I'm looking to improve my Google Pagespeed ranking. So far, I've made some good progress in optimizing different metrics. From the screenshot provided, it's clear that the only issue remaining i ...

Experience seamless file uploads with Blobstore and Ajax/Alternative integration

I have a code snippet that currently works flawlessly, but I am interested in converting it to AJAX or any alternative method. This will allow the form submission request to be sent without refreshing the entire page. If possible, I would also like to imp ...

My asp.net MODAL is not showing the data, what could be the issue?

I'm facing an issue where I can't display a gridview inside an ajax modal. Everything else displays fine except the gridview. Oddly enough, when I tried displaying the gridview outside the modal, it worked perfectly. What could be causing this in ...

What is the best way to incorporate animation using Tailwind CSS within my Next.js project?

I have a challenge with placing three images in a circular path one after the other using Tailwind CSS for styling. I've identified the circular path and keyframe style for the images. How do I configure this style in my Tailwind config file and imple ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

Assign local variable in Mongoose using query results

I created a function to query MongoDB for a credential (simplified): var query = Credential.findOne({token: token}); return query.exec(function (err, credential) { if (err) return null; return credential; }); The next step is to use this credent ...

Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32']; $('.grooveTable&apo ...

Convert scipy dendrogram into JSON format for visualization as a d3.js tree structure

Currently, I am working on converting the results of scipy hierarchical clustering into a json format so that it can be displayed in d3.js. You can find an example of what I am trying to achieve here. The code snippet below generates a dendrogram with 6 b ...

Retrieving data from the database without the need to reload the page

Hi there! I have a PHP script that fetches data from a database and I want to display this data within a div element with a "link" class without having to reload the page. Check out the code snippet below: <? include('config.php'); $rs = m ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Tips for handling 429 errors while using axios in a react native application

My React Native app is connected to a MongoDB database using Express and Node.js, with Axios handling client-server communication. The app frequently exchanges data with the database, sometimes up to 4 requests per second when in use. While everything wor ...

Enhance the visual appeal of mandatory input fields in virtuemart by incorporating star symbols

Is there a way to incorporate red stars into the form for mandatory input fields within Virtuemart 1.x? ...

How can I change JSON to an array using Jquery?

Snippet var jsonData = '{"Error":"Only alphabet characters and spaces are allowed in the name"}'; try { // Parsing JSON string into a JavaScript array var dataArr = $.parseJSON(jsonData); // Iterating through the array for (let key i ...

What methods can be used to save mouse coordinates to a remote server?

As a beginner in server-side programming, I have some questions regarding my project built in JavaScript and Node.js. The current functionality involves sending mouse coordinates to the server and redrawing them on every client's screen. However, new ...

Nested routing in Nextjs is encountering issues when implemented with a specific file

I'm struggling with setting up routes in Next.js. When I create the path "/app/[locale]/admin/page.tsx," I can access http://url/admin/ without any issues. However, when I try to set up "/app/[locale]/admin/login.tsx," I encounter an error and cannot ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

How to convert a querydict with multiple objects into lists

When I send an array of JavaScript objects to a Django view via AJAX, the object structure is as follows: [{'oid':'id1','oiid':'iid1'},{'oid':'id2','oiid':'iid2'}] This is ho ...