The Bootstrap modal form fails to properly handle the POST method when sending data to the server

I am encountering an issue with a button that triggers a modal form

 <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Add Material</a>

The modal appears as shown below:

https://i.stack.imgur.com/J39x9.png

Everything works fine when working locally (localhost), here is the modal form structure:

<div class="modal fade" id="agregarProducto">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">               
                <h5 class="modal-title">Add Material</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-dismissible alert-info">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <strong>Disclaimer!</strong> <a> to add more than one unit, enable </a><strong>add quantity.</strong>
                </div>
                <form id="myForm">
                    <label>Add Quantity</label> &nbsp;&nbsp;
                    <input type="checkbox" id="idcheckcantidad" />
                       <input type="text" class="form-control" name="cantidad" id="idcantidad" disabled="disabled" />
                    <br />
                    <label>Product Code</label> &nbsp;&nbsp;
                    <input type="text" class="form-control" name="codigoproducto"  id="idcodigoproducto" autofocus="" />
                    <br />  

                </form>
            </div>            
             <div class="modal-footer">
                <input type="button" value="Add Material" class="btn btn-primary" id="btnSubmit" />
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>                
             </div>
         </div>
    </div>

When you click submit on my modal, it triggers the following JavaScript code:

   <script>
        $(document).ready(function () {
            $("#btnSubmit").click(function () {

                var myformdata = $("#myForm").serialize();

                $.ajax({
                    type: "POST",
                    url: "/Despachos/AgregarProducto",
                    data: myformdata,
                    success: function () {                     
                        $("#agregarProducto").modal("hide");
                        window.location.href = '@Url.Action("Create", "Despachos")';
                    },
                    error: function (xhr, text, error) {
                    console.log(xhr.status + " => " + error);
                    }
                })
            })
        })
    </script>

This code calls a method in my controller named AddProduct:

   public JsonResult AgregarProducto(int codigoproducto, int? cantidad)
        {
            //Checking existing products in detail
            var despachotmp = db.DespachoDetalleTmps.Where(o => o.Email == User.Identity.Name && o.Kn_CodigoProducto == codigoproducto).FirstOrDefault();

            if (despachotmp == null)
            {
                //Find product 
                var producto = db.Productoes.Find(codigoproducto);

                if (producto == null)
                {
                    ViewBag.Error = "Please select a valid material";
                    return Json(false);
                }

                if (cantidad == null)
                {
                    despachotmp = new DespachoDetalleTmp
                    {
                        v_Nombre = producto.v_Nombre,
                        Kn_CodigoProducto = producto.Kn_CodigoProducto,
                        Email = User.Identity.Name,
                        d_Cantidad = 1,
                    };

                    db.DespachoDetalleTmps.Add(despachotmp);
                }

                if (cantidad != null)
                {
                    despachotmp = new DespachoDetalleTmp
                    {
                        v_Nombre = producto.v_Nombre,
                        Kn_CodigoProducto = producto.Kn_CodigoProducto,
                        Email = User.Identity.Name,
                        d_Cantidad = Convert.ToInt16(cantidad),
                    };
                    db.DespachoDetalleTmps.Add(despachotmp);                   
                }
            }

            else
            {
                if (cantidad == null)
                {
                    despachotmp.d_Cantidad += 1;
                    db.Entry(despachotmp).State = EntityState.Modified;                   
                }

                if (cantidad != null)
                {
                    despachotmp.d_Cantidad += Convert.ToInt16(cantidad);
                    db.Entry(despachotmp).State = EntityState.Modified;                   
                }
            }

            db.SaveChanges();

            var jsonResult = "Json Result";
            return Json(jsonResult);
        }

While everything operates correctly locally, upon deploying the solution on my web server, the form stops responding when I attempt to submit. This problem arises after transitioning to bootstrap styling for the first time. Is there something wrong with my implementation? Any guidance would be greatly appreciated.

Can anyone offer assistance?

Answer №1

The issue might lie in the URL path, where "/Despachos/AgregarProducto" on the server may not correspond to the same directory as "/Despachos/AgregarProducto". Consider utilizing

'@Url.Action("AgregarProducto", "Despachos")'
in your ajax URL instead.

 <script>
        $(document).ready(function () {
            $("#btnSubmit").click(function () {

                var myformdata = $("#myForm").serialize();

                $.ajax({
                    type: "POST",
                    url: '@Url.Action("AgregarProducto", "Despachos")',
                    data: myformdata,
                    success: function () {                     
                        $("#agregarProducto").modal("hide");
                        window.location.href = '@Url.Action("Create", "Despachos")';
                    },
                    error: function (xhr, text, error) {
                    console.log(xhr.status + " => " + error);
                    }
                })
            })
        })
    </script>

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

What order does JavaScript async code get executed in?

Take a look at the angular code below: // 1. var value = 0; // 2. value = 1; $http.get('some_url') .then(function() { // 3. value = 2; }) .catch(function(){}) // 4. value = 3 // 5. value = 4 // 6. $http.get('some_url') ...

Obtain the height and width of the original images from the href and assign them to your attributes using jQuery

Hey there pals, I'm currently on a mission to fetch the dimensions (height and width) of an image from a hyperlink and then insert those values into its attribute. This task has got me going bonkers! Here's my snippet: <figure> <a ...

Executing 'npm run bundle' with Webpack results in an ERR! with code ELIFECYCLE

As someone new to using Webpack with AngularJS apps, I am eager to learn but facing some challenges. Following the guide by Ken Howard has been helpful, but I encounter an error when attempting to run the bundle. Article by Ken Howard that I've been ...

A guide on invoking a spring controller method using ajax

Below is the Controller method snippet: @RequestMapping( value={"/home"},params="userAction=loadHomePage",method=Request.POST) public String viewPage(@ModelAttribute("dataForm") formData, Model model,HttpServletRequest req)throws Exception{ ... } Can any ...

An error occurred while processing the JSReport request

I am encountering an issue while trying to utilize the jsreport API for rendering a report template. The error I am facing is as follows: { body: "{"body":"\"{\\\"template\\\":{\\\"shortid\\& ...

How can I remove markers from google maps?

I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new on ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

How to Refine Database Queries in Laravel Without Using Conditional Statements

I am currently facing the challenge of filtering users in my database using numerous if / elseif statements, and I'm on the lookout for a more efficient method. At present, I find myself writing if statements for every possible query based on the foll ...

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

The Microsoft.Azure.WebJobs.Script encountered an issue while attempting to cast an object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest' during the return process

I recently encountered an issue with my Azure Function written in JS that is triggered by the Service Bus and generates files to Blob Storage. When attempting to return an HTTP result, I received the following error message: System.Private.CoreLib: Except ...

What is the best way to incorporate a particular locale from AngularJS I18n files with bower?

After successfully downloading the angular I18n repo by using bower install angular-i18n, it is now located in my bower_components directory and has updated the bower.json file with angular-i18n : 1.5.3 as expected. However, I am facing an issue where a s ...

The functionality of enabling and disabling dynamic behavior in AngularJs is not functioning as anticipated

As a newcomer to AngularJS, I may have some basic questions. I am currently working on implementing dynamic behavior for a button click event, but it's not functioning as expected. Could this be due to an issue with scope? Below is my HTML code: < ...

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 ...

The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from f ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

What is the technique used by express.js to handle ReferenceError?

// Here is a sample code snippet app.get("/test", (req, res) => { return res.status(200).send(SOME_UNDEFINED_VAR); }); If a ReferenceError occurs, express.js will automatically send a 500 error response. express.js logs the ReferenceError to std ...

Enhancing the functionality of radio buttons through event changes and optimizing related features

I am searching for a more efficient method to reuse functions that serve a similar purpose. For example, I would like to modify various radio buttons that toggle a hide class on different divs. JSFiddle Link How can jQuery be used to create a reusable fu ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

Scripting in jQuery to create dropdown menus

I've encountered a unique issue on my website where a user's selection from one list should update the values in another list: <form id="form1"> <div> <select id="workField"> <option value ...