Show data and messages directly on the screen

I am currently working on ajax, jquery, and javascript, but I am facing some issues.

Although I can use this code to send data to the database, the data is not displayed in the view immediately after sending it; I have to reload the page to see it.

Is there a way to output the data directly in the view without having to reload the page?

Also, how can I display errors and success messages as flash messages (toastr messages)?


I am encountering an error message stating that there are duplicate selectors in the code. How can I rewrite this code to resolve that issue?

    $('#todolist-create-modal').modal('hide');
    $('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
                        return event.keyCode != 13;
});

Here is the corrected code with some enhancements:

   <script type="application/javascript">
    $(document).ready(function () {
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

        $('#add-todo-list').click(function(e) {
            e.preventDefault();
            var _token = $("input[name='_token']").val(); // get csrf field.
            var title = $("input[name='title']").val();
            var description = $("textarea[name='description']").val();
            var privacy = $("select[name='privacy']").val();
            $.ajax({
                url:'{{ route('todolists.store') }}',
                type: 'POST',
                data: {_token:_token, title:title, description:description, privacy:privacy},
                success: function (data) {
                    console.log(data);

                    if (privacy = 0) {

                        //go to the left side

                    } else {

                        //go to the right side

                    }
                },
                error: function(data){
                    console.log(data);
                }
        });
            $('#todolist-create-modal').modal('hide');
            $('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
                return event.keyCode != 13;
            });
        });

    });
</script>

view

<div id="content" class="dashboard padding-10">
   <!-- Your view content here -->

Controller

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|min:5',
        'description' => 'required|min:10',
        'privacy' => 'required|integer'
    ]);

    $attributeNames = array(
        'title' => 'Title',
        'description' => 'Description',
    );
    $validator->setAttributeNames($attributeNames);
    
    if($validator->fails()) {
        return response()->json(['error'=>$validator->errors()->all()]);
    }
    else{
        $todolists = new Todolists();
        $todolists->admin_id = Auth::id();
        $todolists->title = $request->title;
        $todolists->description = $request->description;
        $todolists->privacy = $request->privacy;
        $todolists->save();

        return response()->json(['Your enquiry has been successfully submitted!']);

    }

}

EDIT

After some revisions, I still face two issues:

The flash message is being displayed as 'empty' without any text content. What could be causing this problem?

Additionally, even though the div is reloaded, I can't resend the same request after it loads. Is there something I need to reset or fix?

When checking the console for errors using console.log(data);, I see the following error messages: {error: Array(2)} error : (2) ["The Title ist erforderlich.", "The Description ist erforderlich."]

<script type="application/javascript">
    $(document).ready(function () {
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

        $('#add-todo-list').click(function(e) {
            e.preventDefault();
            $('.todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
                return event.keyCode != 13;
            });

            var _token = $("input[name='_token']").val(); // get csrf field.
            var title = $("input[name='title']").val();
            var description = $("textarea[name='description']").val();
            var privacy = $("select[name='privacy']").val();
            $.ajax({
                url:'{{ route('todolists.store') }}',
                type: 'POST',
                data: {_token:_token, title:title, description:description, privacy:privacy},
                success: function (response) {
                    if (response.error) {
                        _toastr((response),"top-full-width","error",false);
                    }
                    else{
                        $('.todolist-create-modal').modal('hide');
                        $("#content").load(location.href+" #content>*","");
                        _toastr((response),"top-full-width","success",false);
                    }
                }
            });
        });
    });
</script>

Answer №1

Q: Is there a way to display data directly on the view without refreshing the page?

An efficient method using jQuery involves loading partial content, which makes a request to the page to retrieve the contents of the #content div and update the HTML without reloading the entire page:

$("#content").load("/url-of-page > #content > *");

Q: How can I show error and success messages as flash messages (toastr) on the screen?

You can simply write the message inside an HTML element:

success: function(data){
   $(".alert-danger").addClass("hidden");
   $(".alert-success").html(data.msg).removeClass("hidden");
},
error: function(data){
   $(".alert-success").addClass("hidden");
   $(".alert-danger").html(data.error).removeClass("hidden");
}

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

Unable to access Vue component method beyond its scope

Having an issue with my Vue component that I'm trying to call a method from outside its wrapper element #app. Is there a way to register the component so I can easily call it like Component.function(); var viewController = new Vue({ el: "#app", ...

What is the syntax for creating a for loop in JSX within a React component?

I am working on a simple program that involves using a for loop to print numbers from 0 to 10. My goal is to utilize a for loop to print these numbers and pass the props to a child component. Please see my code below: import React, { Component } from &apo ...

IE8 does not recognize jQuery ajaxSubmit

I am currently utilizing the jQuery validation plug-in in conjunction with the jQuery Form Plugin to submit forms through AJAX. Everything functions flawlessly in Firefox and Chrome, however, as expected, Internet Explorer presents some challenges. For som ...

The Datatable plugin is unable to effectively customize tables that are loaded dynamically

Within my single page application, the home page initially loads all static resources and js files. Subsequently, upon a user click event, the table is dynamically loaded. Unfortunately, the datatable customization does not seem to be applied on the newly ...

Why is my return statement in JavaScript Nextjs mapping values twice?

I am running into an issue where my code is displaying the output twice, and I can't seem to figure out why. Any assistance would be greatly appreciated. Here is a link to the current output that I am receiving. I suspect that the problem lies in sett ...

The default value of the input color in HTML/NextJS does not update when changed

Issue: The color input does not change when the default value (#ffffff) is declared. https://i.sstatic.net/BpqUj.png However, it works normally if I don't declare a default value. https://i.sstatic.net/0dBd6.png Note: Using NextJS framework. <i ...

What is the best way to show a selected value in a checkbox within a Google Plus-style popup box?

As I was browsing through a post on Stackoverflow about implementing a Google plus popup box when hovering over thumbnail, I got motivated to try it out on my own website. I successfully integrated the script and managed to add contacts to my database. It ...

Maintain consistent viewing experience across all devices

Is there a way to adjust the activities xml file so that the layout remains consistent regardless of screen size? I want the positioning of buttons and text to remain relatively the same distance apart on all devices. Would using a relative layout achieve ...

Including file format extension in the absence of one

I have created a script that loops through every image source on the page, extracting the extension. If the extension is not recognized or does not exist, I automatically add .jpg to the end. Strangely, the if statement always evaluates to true no matter ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

How to boost the value of a property within a MongoDB document with Mongoose

Recently, I've been dealing with an array of objects named "items". This array includes different objects and I need to search for each object in MongoDB using the "baseId" found in the Base Document. Once I locate the matching object, I aim to update ...

What could be causing html-webpack-inline-source-plugin to prevent the page from refreshing after editing CSS files?

Currently, I am utilizing a plugin that embeds all CSS within the final HTML file. This method prevents the application from refreshing in development mode. Whenever I make edits to the CSS, the build process completes normally, but the styles do not updat ...

Internet Explorer is failing to show the results of an ajax call retrieved from the

Need help with this code block: $(document).ready(function() { dataToLoad = 'showresults=true'; $.ajax({ type: 'post', url: 'submit.php', da ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

Strategies for persisting data in React using local storage to ensure information is retained after page refresh

I am attempting to store searched recipes data in local storage so that when the user refreshes, the data from the last searched recipe will still be available. I have tried saving the recipes data to local storage when a new search request is made and se ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...

Tips on showing an api call response in Reactjs

I am a beginner in Reactjs and currently working with nextjs. I have been trying to integrate a "newsletter" feature into my project. I have created a component for this which is functioning properly. However, I am facing an issue with displaying the "succ ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

Scanner (IE5) impact on page load speeds

I have developed an MVC project which is designed as a single-page application (SPA) utilizing knockoutjs and sammy frameworks. The following script is placed in the head section of the page: <script> var startTime = (new Date()).getTime(); </ ...