Error 404 encountered when attempting to send a JSON object to the server

I've been facing a problem while trying to send a JSON object to the server using AJAX calls. I keep getting a 404 Bad Request error. The issue seems to be related to the fact that I have a form where I convert the form data into a JSON object, but the table in my database has an auto-incremented primary key (id) that is not included in the form fields. Here is the relevant code snippet from my controller:

     var Bus= angular.module('Bus',[]);


   Bus.controller('BusController',function($scope,$http) {

$scope.business = {}

$scope.submitMyForm=function(){
       console.log($scope.business);
        var q=JSON.stringify($scope.business)  
         console.log(q)

            $

            .ajax({
                type : 'POST',
                url : " some url",
                data :JSON.stringify($scope.business),

                success: function(){
                          alert('success');
                           },

                error : function(e) {
                    console.log(e);
                    alert('oops!!');
                },
                dataType : "json",
                contentType : "application/json"
            });
        };
}); 

How can I resolve this issue? Any help or suggestions would be greatly appreciated. Thanks in advance!

Answer №1

Are you receiving a 404 Not Found error or a 400 Bad Request error?

If you are seeing a 404 error, it may be due to an incorrect URL. If it is a 400 error:

Have you verified that the $scope.business object in your debugger contains the correct values?

Additionally, it is recommended to handle these requests in a service rather than an angular controller:

    MyService.service('BusService', function($http) {
      function postFormData(form) {
        var data = angular.toJSON(form);
        // proceed with the $http stuff ...
      }
      return {
        postFormData: postFormData
      };
    });

Inject the service into your controller and call it like this:

    MyService.controller('BusController',function($scope, BusService) {
      $scope.submitForm = function() {
          BusService.postFormData($scope.business);
      };
    });

It would be beneficial to understand the JSON format required by your backend and the JSON being generated by your client to troubleshoot the issue.

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

Ways to verify user login through jQuery post method

I am currently working on a login test application that utilizes jQuery post and PHP. I'm encountering an issue where the application is able to read the input values but fails to send the data to server.php and consequently does not return any data. ...

Converting Salesforce data types to Java types

When transferring data from Salesforce to Java using the partner API, everything seems to be going smoothly. However, there is one issue that is quite annoying. In Salesforce, there is a field that represents currency, with a value of $850,000,000,000. Whe ...

How many times will Angular be used to manage printing?

I have developed a print service using AngularJS. Is there an efficient method to specify the number of times it should be called? Currently, I am able to loop through this code and call it 'n' number of times. PrintService.printElement("printT ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

Steps to modify the border width upon gaining focus

I am struggling to adjust the border width when my input box is focused. Currently, it has a 1px solid border which changes to a 2px different color solid border upon focus. However, this change in border width is causing the containing div to shift by 1px ...

JavaScript - continuously update the image marked as "active"

I have a collection of 4 pictures that I want to rotate through in my web application. Each picture should have the "active" class applied to it, similar to when you hover over an image. .active, .pic:hover{ position: absolute; border: 1px solid ...

What is the best method for sending a JavaScript variable to the server and back again?

I'm currently working on a JavaScript project where I need to build a string. Let's say, for the sake of this example: var cereal = 'my awesome string'; There's also a button on my webpage: <button id="send" type="submit" nam ...

The Json-Jersey error occurs when attempting to deserialize a parameterized root List

While attempting to create a generic function that can convert JSON responses from an API to objects using jersey-json-1.8, I encountered an issue with handling lists properly. I wondered if it could be configured or if jersey-json simply cannot handle par ...

Solving yarn conflicts when managing multiple versions of a package

My software application contains a vulnerability related to a package that has different versions available (1.x, 2.x, 3.x). Since many other packages rely on this particular one as a dependency, updating each one individually is not a viable solution at t ...

Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are: handleAddProduct handleRemoveProduct handleC ...

Error Encountered During Serialization with ASP.Net AJAX and JavaScript

Encountered an error message stating "Out of Stack Space" while attempting to serialize an ASP.Net AJAX Array object. Below is a breakdown of the issue with simplified code: Default.aspx MainScript.js function getObject(){ return new Array(); } ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

Obtaining a list from two distinct elements using Selenium in Java

Seeking guidance on how to have two h3 tags under a div tag with lists only appearing under the first h3 tag and not the second. In the provided image, h3(1) -> v2-43-october-11--2022 h3(2) -> v2-45-january-10--2023 Under h3(1), there are two ul ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Encountering unexpected token < in .Net with Jquery Ajax

I've developed a JavaScript function that interacts with a server-side method function abc() { var Url = "MyService.svc/MyMethod"; var Param = '{"Keyword":"' + Keyword + '","Type":"' + type + '"}'; $.ajax({ ...

Creating distinct identifiers for CSS JQ models within a PHP loop

Can anyone assist me in assigning unique identifiers to each model created by the loop? I am currently looping through a custom post type to generate content based on existing posts. I would like to display full content in pop-up modals when "read more" i ...

Building a table with Next.js

I need assistance in displaying users and their metadata in a table on my website. Here is the code snippet I have: const apiKey = process.env.CLERK_SECRET_KEY; if (!apiKey) { console.error('API_KEY not found in environment variables'); proc ...

What is the best way to display a field depending on a certain condition using Spring Data MongoDB?

Trying to retrieve matching documents based on specified criteria, encountering an issue with the "priceHistory" List field that contains properties for price and date. The objective is to display the "priceHistory" field only if today's price is avai ...

jQuery must provide the complete object rather than just the data within it

What is the best way to retrieve the entire <div class="loan_officer_apply_now_link"><a href="">APPLY NOW!</a></div> At present, only the "a" element content is being returned <a href="">APPLY NOW!</a> Test Code $( ...

Using Java and REST, establish a connection from Android to MySQL purposes

My current project involves working with Android native and MySQL. To connect the two, I am using Java and REST. However, when attempting to run my REST service, I encountered an issue where I did not receive any response (just a blank page appeared). Upon ...