Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty($_POST) === false) {}, whereas the other pages use

if (isset($_POST['save-settings'])) {}
. I'm at a loss on what to do next. Below is the code snippet I am using:

Here's the HTML BUTTON section:

<input id="save-settings" class="submit" type="submit" name="save-settings" value="Save" onclick="return false;" />

And here's the JS SCRIPT:

$(document).ready(function() {
        $("#save-settings").click(function() {
            var name        = $("#webname").val();
            var charset     = $("#webchar").val();
            var meta        = $("#webmeta").val();
            var description = $("#webdesc").val();
            var startsite   = $("#webstartsite").val();
            var starturl    = $("#webstartsiteurl").val();
            var footer      = $("#webfooter").val();

            $.post("../lib/action.php", {
                name: name,
                charset: charset,
                meta: meta,
                description: description,
                startsite: startsite,
                starturl: starturl,
                footer: footer
            }, function(data) {
                $("#gy-main-notification-bar").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
                setTimeout(function() { $("#gy-main-notification-bar").slideUp(500) }, 2500);
            });
        });
    });

Lastly, the PHP SCRIPT section:

if(isset($_POST['save-settings'])) {
    $updatesettings = "UPDATE `settings` SET
    `name`='".escape($_POST['webname'])."',
    `charset`='".escape($_POST['webchar'])."',
    `meta`='".escape($_POST['webmeta'])."',
    `description`='".escape($_POST['webdesc'])."',
    `startsite`='".escape($_POST['webstartsite'])."',
    `starturl`='".escape($_POST['webstartsiteurl'])."',
    `footer`='".escape($_POST['webfooter'])."'
     WHERE `id`= 1";

     if ($update_settings = $db_connect->query($updatesettings)) {}
     echo 'Success!';
 }

I prefer not to switch from isset to empty in the script as all my "onclick" scripts are located in one action.php file. Interestingly, when I remove onclick="return:false;" from the input field, the code works fine. Any assistance would be highly appreciated!

Answer №1

Event handler functions for clicks can include an event argument. By accessing this argument, you can utilize the preventDefault() method. Using this method will stop the default action of a click event, preventing the page from refreshing.

Modify

$("#save-settings").click(function() {
        var name        = $("#webname").val();

to

$("#save-settings").click(function(ev) {
        ev.preventDefault();
        var name        = $("#webname").val();

Answer №2

Do not forget to add the post save-settings. It should have been included in the ajax post like so:

$.post("../lib/action.php", {
            'name': name,
            'charset': charset,
            'meta': meta,
            'save-settings': true,
            'description': description,
            'startsite': startsite,
            'starturl': starturl,
            'footer': footer
        },

Make sure to update this in your sql statement for the correct posts

 `name`='".escape($_POST['name'])."',
`charset`='".escape($_POST['charset'])."',
`meta`='".escape($_POST['meta'])."',
`description`='".escape($_POST['description'])."',
`startsite`='".escape($_POST['startsite'])."',
`starturl`='".escape($_POST['starturl'])."',
`footer`='".escape($_POST['footer'])."'
 WHERE `id`= 1";

Answer №3

By including the code onclick="return false" in an HTML document, you effectively prevent the execution of any associated JavaScript code. Instead of using this method, it is advised to remove the onclick="..." attribute entirely and replace it with preventDefault() in order to successfully avoid form submission.

$("#save-settings").click(function(e) {
   e.preventDefault();
   .....

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

Deactivate the button while you wait for the Google Maps directionService

When utilizing the Google Maps service to plot a route with multiple waypoints and under slow 3G conditions, I need to deactivate an HTML button until the new route is traced. calculateRoad(departure: any, arrival: any) { const request = { origin: ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

Submitting a form via email without the need for PHP

Currently, I am focusing on a project that is small and emphasizes presentation more than security. The main objective is to create a form where users can input data, then click submit for all the information gathered to be sent to a specified 'mailt ...

Leveraging Grid and Proxy to access and store information using a single URL in ExtJS 4

I'm a bit confused about how proxies work in ExtJS. Is it possible to use basic functions with them to both retrieve and store data using just one URL? For instance, can I call users.read() to fetch data and users.save() to save new or edited grid fie ...

Tips on keeping a div element in a fixed position until triggered by jQuery

I've managed to create a navigation bar within a header that sticks to the top of the screen once you scroll down past 100px. The functionality works well, but I'm looking to make the navigation bar stay fixed on the right until it snaps, essenti ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

Is there a method to instruct crawlers to overlook specific sections of a document?

I understand that there are various methods to control the access of crawlers/spiders to documents such as robots.txt, meta tags, link attributes, etc. However, in my particular case, I am looking to exclude only a specific portion of a document. This por ...

Alter the class generated by ng-repeat with a click

I currently have a dynamically generated menu displayed on my website, and I am looking to apply a specific class to the active menu item based on the URL (using ngRoutes). The menu items are generated from a $scope.menu object, so my initial thought was t ...

I am facing difficulty in retrieving a unique dynamic div id using the useRef ReactJS hook, as it keeps returning the same id repeatedly

When using the useRef Reactjs hook, I encountered an issue where it returned the same id repeatedly instead of generating a dynamic div id. I need this functionality to map buttons and div ids in order to create a flexible accordion. The goal is to displ ...

Custom scrollbar designed for optimal viewing on various devices

I'm currently using perfect-scrollbar to customize the scrollbar in my application. However, I've encountered a situation where I need to set the height of the scrollable section in terms of a percentage. When I tried to do this by setting the he ...

Is there a way to ensure that a "catch all other" route in the Vue Router will also capture the URL if a portion of it matches a predefined route?

After following the suggestion to implement a catch all route from this article, I realized that it does not capture URLs that partially match a defined route. routes: [ { path: "/album/:album", name: "album", component: Album, } ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

Can Three.js be used to create a compact canvas?

I've successfully implemented a three.js scene on my website where users can drag to rotate an object. However, I don't want the scene to take up the entire webpage. I tried adjusting the field parameters with the following code: renderer.setSiz ...

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

Mastering the Art of Restricting an IP Address Range with FILTER_VALIDATE_IP

In order to restrict access to certain resources, I need to implement a system that filters IP addresses. To validate the IP address, I currently use FILTER_VALIDATE_IP and filter_var. However, I am facing an issue where the starting and ending IP address ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Email confirmation section

I'm in the process of setting up a subscription newsletter page, and everything seems to be working correctly except for the part where I need users to enter their email address twice. The second email field is meant for confirmation purposes, but I&a ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...