Creating a form using Ajax in PHP to submit messages without having to refresh the page

I am trying to submit a form using an ajax call without having to refresh the page.

Below is the HTML markup:

<form id="form">
<input type="radio" name="radio" value="radio1">
<input type="radio" name="radio" value="radio1">

<input type="checkbox" name="box" value="box1">
<input type="checkbox" name="box" value="box2">

<input type="text" name="text" value="box2">

<input type="submit" id="submit" name="submit" class="embtn btn-1" value="Send" onclick="submitform()">

</form>

Here is the associated JavaScript code:

function submitform(e) {
    e.preventDefault();
    $.ajax({
        url : 'assets/php/brief-wiz.php', 
        type: 'post', 
        data: $('form').serialize() 
    }).done(function(html) {
        $( ".form-message" ).append( html );
    });
};

This is the PHP script being used:

<?php

$errors = [];

if (empty($_POST["radio"])) {
    $errors[] = "Please select a radio option";
} else { 
    $radio = implode($_POST['radio']);
}

if (empty($_POST["box"])) {
    $errors[] = "Please complete all checkboxes ";
} else { 
    $box = implode($_POST['box']);
}

$text = ($_POST['text']);   

// Additional PHP code for sending email...

?>

The issue faced is that the messages disappear quickly and the page reloads. How can I prevent this from happening?

Answer №1

Implementing Javascript Event Handling:

HTML Code

<form id="form" action="assets/php/brief-wiz.php">
    <input type="radio" name="radio" value="radio1">
    <input type="radio" name="radio" value="radio1">

    <input type="checkbox" name="box" value="box1">
    <input type="checkbox" name="box" value="box2">

    <input type="text" name="text" value="box2">

    <input type="submit" id="submit" name="submit" class="embtn btn-1" value="Send">
</form>

JAVASCRIPT Code

$('form').on('submit',function(event){
  event.preventDefault();
  var form = event.currentTarget;
  $.ajax(
    {
        url : $(form).attr('action'), 
        type: 'post', 
        data: $(form).serialize() 
    }
  ).done(
    function(html) {
        $( ".form-message" ).append( html );
    }
  );
});

Answer №2

Consider updating the type of your submit input to a button for better functionality.

Answer №3

The reason your button isn't working is because it has a type of submit! I recommend using this code instead:

<button id="submit" class="embtn btn-1" onclick="submitform()">Send</button>

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

Detecting race conditions in React functional components promises

There's an INPUT NUMBER box that triggers a promise. The result of the promise is displayed in a nearby DIV. Users can rapidly click to increase or decrease the number, potentially causing race conditions with promises resolving at different times. T ...

Positioning Problems with Popups

I have been facing an issue with the positioning of a popup in my trivia game. Despite trying multiple solutions, I have not been able to achieve consistency. Here is a snippet of the HTML code: <div class="logo"> <img src="css/rio-40.png"/& ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

Reduce the number of redundant fields in MongoDB collections

I'm facing an issue with my model structure. Here is the schema: var accountSchema = new mongoose.Schema({ 'seeker': { 'fullName': String, 'ageGroup': String, 'education': String, ...

Animation not properly synced with Bootstrap 4 Dropdown hide event

Could you please check out my codepen for clarification: http://codepen.io/anon/pen/oLZOyp Essentially, I have integrated two animations using animate.css into Bootstrap 4 show.bs.dropdown and hide.bs.dropdown events. The animations work on the first show. ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

The header location functionality is not functioning properly on the live server

I have a single registration and payment page where the program flow goes from registration to confirmation and then to payment. Upon validation and calculation on the registration page, it should redirect to the confirmation page. This is my code: < ...

Refresh the PartialView only after clicking submit

I am struggling with updating only the contents of my partial view after clicking an input type="submit button. My goal is to refresh just the partial view and update it with the updated model from the controller code, without refreshing the entire page. S ...

React DnD now enables dragging an entire list of cards instead of just a single card

Implementing react DnD in my react Project has been challenging. In the render method, I have defined a variable called Populate that generates a list of cards as shown below: render() { var isDragging = this.props.isDragging; var connect ...

Trouble arises with kids when trying to adjust the display to block mode

I need to set all the div elements inside the div with id "editor" to display as block. However, when I change the display property of the div with id "editor", only that specific div's display is affected, while everything else inside the div becomes ...

What is the process for creating custom event bindings in AngularJS?

There is a custom event called core-transitionend (specifically triggered by Polymer), and I am able to specify an event handler using document.addEventListener(). However, what would be the most recommended approach for achieving this in AngularJS? Alter ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...

Include the referrer header when using the chrome.downloads API

I have been working on developing an extension that replicates the Ctrl+Click to save image functionality from Opera 12. In my extension, I am utilizing chrome.downloads.download() in the background script to trigger downloads, while a content script is re ...

Guide on exporting a submodule within a TypeScript package

My aspiration is to develop a Typescript library that emulates the structure of popular libraries like RxJS and Angular Material, which are divided into submodules. RxJS and Angular exhibit a way to import features using syntax like this: // RxJS import ...

Don't waste time creating multiple popups for changing content - streamline your process

Challenge I've successfully extracted information from an array and displayed it dynamically in a tooltip/popup window above each photo on the page. However, with 56 different individuals at various locations, arranging them neatly in a grid poses a ...

I am seeking to perform these operations solely using pure WebGL, without relying on the Three.js library

if( keyboard.pressed("up")) pobjects[movementControls.translate].translateX(1); if( keyboard.pressed("down")) pobjects[movementControls.translate].translateX(-1); if( keyboard.pressed("left")) pobjects[mo ...

Extra Pathway

Having trouble adding a second route to the /privacy page. The error "Cannot GET /privacy.html" keeps popping up. Any suggestions? This code seems to be failing to display the privacy.html content app.get('/privacy', function(req, res) { res.s ...

Having difficulty understanding and parsing JSON using JQuery

I have a jQuery function that is returning data in the following format: {"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166", ...

How can I use AJAX to read a CSV file uploaded by a client in C#?

My current project involves the scenario where a user needs to choose a CSV file from their local system. It is then necessary for me to read the contents of this file and display them on a JQGrid. The catch? This all needs to work smoothly in Internet E ...

Passing data out of the withTransaction helper using Mongoose

Hi there! Greetings, I'm currently working on extracting data from the mongoose withTransaction callback. The code snippet below shows my current approach using callbacks: const transactionSession = await mongoose.startSession() await transactionSe ...