Encountering an Ajax Issue with Laravel 5.4

I encountered the following error:

"{"status":"error","msg":"Category was not created"}"

Below is my Controller Function where I execute the action :

    function create_category(Request $request){
            if($request->ajax()){
                $category_name = $request->input('create_category');
                DB::table('tbl_smscategories')->insert($category_name);
                $response = array(
                    'status' => 'success',
                    'msg' => 'Category created successfully',
                ); 
                return Response::json($response);
            }else{
                $response = array(
                    'status' => 'error',
                    'msg' => 'Category was not created',
                );
                return Response::json($response);
            }
        }

I received this error message

"{"status":"error","msg":"Category did not created"}"

Here is my ajax Code for performing the action :

<script type = "text/javascript">

    $('#add-order').click(function(e) {
        e.preventDefault();
        
        var inputcreate_category = $('input[name="create_category"]').val();
        var token = $('input[name="_token"]').val();
        var data = {
            create_category: inputcreate_category,
            token: token
        };

        var request = $.ajax({
            url: "/create-category",
            type: "POST",
            data: data,
            dataType: "html",
        });

        request.done(function(msg) {
            var response = JSON.parse(msg);
            console.log(response.msg);
        });

        request.fail(function(jqXHR, textStatus) {
            console.log("Request failed: " + testStatus);
        });
    }); < /script>

I got this specific error regarding category creation "{"status":"error","msg":"Category did not created"}"

HTML Element :

<form method="post" action=" {{ route('createcategory') }} " enctype="multipart/form-data" method="post">
    {{ csrf_field() }}
    <div class="form-group">
        <label>Category Name</label>
        <input type="text" name="create_category" id="create_category" class="form-control" placeholder="Enter Category Name">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary" id="create">Create</button>
    </div>
</form>

Answer №1

The issue has been successfully resolved!

Below is the Controller Function where I executed the necessary actions :

function add_new_category(Request $request){
    if($request->ajax()){
        $category_name = $request->input('new_category');
        $data = array(
            'name' =>  $category_name,
            'store_id' =>  2,
        );
        DB::table('tbl_cat')
            ->insert($data);
        $response = array(
            'status' => 'success',
            'msg' => 'Category added successfully',
        ); 
        return json_encode($response);
    }else{
        $response = array(
            'status' => 'error',
            'msg' => 'Failed to add category',
        );

        return json_encode($response);
    }
}

Here's the ajax Code responsible for the functionality :
<script type = "text/javascript">
    /*Code For Adding Category*/
    $(document).ready(function(){
        $('.category_form').submit(function(e){
            e.preventDefault();
            $.ajax({
                url:$(this).attr('action'),
                type:"POST",
                data:$(this).serialize(),
                success:function(result){
                    json_data = $.parseJSON(result);
                    alert(json_data.msg);
                },
                error:function(xhr, status){
                    json_data = $.parseJSON(result);
                    alert(json_data.msg);
                }
            })
        })
    }) 
< /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

Is there a specific minimum height that should be set for the equalHeight function to apply?

Despite trying everything, I can't seem to achieve the dreadful layout my designer has given me without using JavaScript! The issue lies with the positioning of the div #backgr-box, which needs to be absolutely positioned behind the #contenuto ( ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

I encountered an ECONNREFUSED error while attempting to fetch data from a URL using NodeJS on my company-issued computer while connected to the company network. Strangely

After searching through forums and conducting extensive Google searches, I have come across a problem that seems unique to me. No one else has posted about the exact same issue as far as I can tell. The issue at hand is that I am able to successfully make ...

"Encountering an issue with Express.json where it fails to parse the

Receiving JSON POST data from an IoT API that includes multipart form-data. Occasionally, an image file may be included but I only want to focus on the JSON part: POST { host: '192.168.78.243:3000', accept: '*/*', 'content-le ...

Issue submitting form with tinymce textarea multiple times via ajax

Struggling with submitting a form using ajax with tinymce as the textarea editor. The issue arises when trying to submit the form multiple times, as it only works on the initial attempt. This is the form structure <form action="{{action('QuizCont ...

What are some methods for embedding HTML content onto a specific section of a webpage in a Node.js + Express application, without displaying it as the

Objective My goal is to insert a portion of HTML into a web page. Issue The page is not displaying properly with the desired styling and layout. I have a specific page that must be written in plain HTML rather than Jade, although I will still be usin ...

Displaying a div after a successful form submission using Jquery

I created two popup windows. One is used to ask the user whether they want to submit the form, and if they click 'yes', the form is submitted. The issue I encountered is that the other popup window should be shown after the form is successfully s ...

What is the process for a webpage to save modifications made by JavaScript?

I am working on a simple web page with a form that contains checkboxes representing items from a database. When the submit button is clicked, these items may be retrieved. Additionally, there is an option to add a new item at the bottom of the page. My go ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

What is the best way to use checkboxes to highlight table rows in Jquery Mobile?

I have a Jquery Mobile site with a table. Each table row contains checkboxes in the first cell. I am trying to achieve the following: a) Highlight a row when the user clicks on it b) Highlight a row when the user checks the checkbox I have made progr ...

Managing a prolonged press event in a React web application

Hello everyone! I am currently using React along with the Material UI library. I have a requirement to handle click events and long-press events separately. I suspect that the issue might be related to asynchronous state setting, but as of now, I am unsu ...

How can we accurately identify the server that initiated an AJAX call in a secure manner?

Imagine a scenario where Site A embeds a JavaScript file from Server B and then makes a JSONP or AJAX request to a resource on Server B. Is there any foolproof way for Server B to determine that the specific JSONP request originated from a user on Site A, ...

JavaScript - All values stored from the for loop are registering as undefined

Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas fe ...

Combining PHP and Ajax for multiple requests on a single webpage

I currently have code that is only loading one page (load.php?cid=1), but I want to load multiple pages (cid=1, cid=2, cid=3, etc.) into different divs. How can I achieve this? $(document).ready(function() { function loading_show() { ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Using useCallback with an arrow function as a prop argument

I'm having trouble understanding the code snippet below <Signup onClick={() => {}} /> Upon inspecting the Signup component, I noticed the implementation of useCallback as follows const Signup = ({onClick}) => { const handleClick = us ...

Is it no longer necessary to bind functions in React Component Classes?

Recently, I observed that when defining normal class component functions in React, there is no longer a need to bind them inside the class constructor. This means that even without using ES6 public class field syntax, you can simply pass these functions to ...