Prevent refreshing the page when submitting information

Whenever I try to post data to PHP, the page ends up reloading. I have attempted to address this issue by following suggestions from similar questions but none of them seem to work as expected. Any assistance is greatly appreciated.

<!--HTML-->
<form method="post" action="index.php" onclick="sendForm(event);">            
   <input type="text" class="form-control" id="code" name="rand5_code">
    <input type="submit" href=""  name="rand5_btn" class="btn btn-success" value="Enter">
</form>

 //Javascript
<script type="text/javascript"> 
            function sendForm(e){
                e.preventDefault();
            }

        </script>

I was also suggested another approach using AJAX:

<form id="form">
    <input style="width:200;margin-top:5px" type="text" class="form-control" id="code" name="installer2_code" placeholder="Enter Code">
     <input type="submit" href="#" style="margin-top:5px" name="installer2_btn" class="btn btn-success" id="form" onclick="sendForm(event);" value="Enter">
   </form>

<script>
    $('#form').on('click', function(e){
       e.preventDefault();
           var name = $(#code).val(),
        $.ajax({
          type: 'post',
          url: 'header_php.php',
        });
    });


    </script>

Answer №1

Consider placing onclick = "sendForm(event);" on the button rather than the form

Answer №2

It is recommended to switch onsubmit instead of using onclick in the form.

function sendForm(e) {
  e.preventDefault();
}
<form method="post" action="index.php" onsubmit="sendForm(event);"><!--changes-->
  <input type="text" class="form-control" id="code" name="rand5_code">
  <input type="submit" href="" name="rand5_btn" class="btn btn-success" value="Enter">
</form>

Answer №3

Modify the button by changing type="submit" to Type="button" and utilizing jQuery ajax

$("#btnid").click(function(){
    $.ajax({
        method: "POST",
        url: "some.php",
        data: { name: $('#code').val()}
    })
    .done(function( msg ) {
        alert( "Data Saved: " + msg );
    });
})

Additionally, delete the action attribute from the form

Answer №4

To avoid page reload, include onsubmit="return false;" in your form element. Remember, the e function in your JavaScript code should refer to a click event, not a submit event which triggers a page reload.

<!--HTML-->
    <form method="post" action="index.php" onsubmit="return false;" onclick="sendForm(event);">            
       <input type="text" class="form-control" id="code" name="rand5_code">
        <input type="submit" href=""  name="rand5_btn" class="btn btn-success" value="Enter">
    </form>

     //Javascript
    <script type="text/javascript"> 
        function sendForm(e){
            e.preventDefault();
        }

    </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

Pagination and asynchronous deletion with will_paginate

Currently, I have a list of resources that are displayed on a paginated list using the will_paginate gem. I haven't made any customizations yet, here is how my view looks: <ul> <%= render :partial => "item_li", :collection => @items%& ...

Accessing the window variable within a Jquery selector in Javascript

I'm encountering some issues while attempting to optimize code. The following lines execute without errors: Array.prototype.forEach.call( $('ZA1 .stat'), function( td ) {//ExcuteCode} Array.prototype.forEach.call( $('ZA2 .stat'), ...

Using Linux variables in the .env file of your Vue.js project can provide a convenient way to

Using .env in a *.js file allowed me to set the BANK variable as either A_BANK or B_BANK like so: BANK=A_BANK or BANK=B_BANK However, when passing the argument as A_BANK or B_BANK like: --bank A_BANK in a shell script loop for var in $@ do if [ ${var} ...

How can I generate 200 divs that are identical but each displaying a unique file (page0.svg, page1.svg..., page200.svg)?

<div class="mySlides"> <img src="1173/page0.svg" style="width:50%"> </div> <div class="mySlides"> <img src="1173/page1.svg" style="width:50%"> </div> My task involves generating approximately 200 similar div codes ...

Create a new object by extracting JSON data using JavaScript

I am attempting to extract various data elements from a JSON file and place them into an object. My ultimate goal is to then convert this object back to JSON format, containing only the desired data. I believe that structuring the object like this might w ...

Position a moveable item in the middle of two designated drop zones

I have been experimenting with creating a drag-and-drop feature that allows the draggable object to be placed between two droppable targets. The goal is for both droppable targets to receive and acknowledge the draggable object simultaneously, updating the ...

Displaying icons that correspond to the file's extension

I need help creating a table of uploaded files in PHP connected to an MS SQL Server. Each file needs to display an icon based on its extension, but I'm not sure of the best way to achieve this. There are three options I've considered: The best ...

What is the best way to update office-js dependencies in a React Outlook web add-in while ensuring safety?

I have a react outlook addin and I'm trying to figure out how to update it to the latest office-js-dependencies. The documentation seems confusing to me. It looks like I need to update the versions in my package.json file, but there isn't any cl ...

Transform text hue using regular expressions in TypeScript/React

Why isn't my class being used in my regex function? I'm quite confused about what's going on. Regex let headingTitle: Element | null = document.querySelectorAll("h2") headingTitle.innerHTML = headingTitle.textContent?.repla ...

What is the most effective way to import a substantial static array in React for utilization in a select field?

The scenario is quite straightforward. I currently have a single array containing over 2500 strings of company names, saved locally in the project as a JSON file within a subdirectory under src. To access this data in my component, I am importing the JSON ...

Encountering a SyntaxError while implementing lightweight-charts in NextJS

I'm encountering an issue while trying to integrate the lightweight-charts package into my nextjs project. When attempting to utilize the createChart function, I am receiving a syntax error in my Node.js console. ...\lightweight-charts\dist& ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

What is the best way to style HTML content with MathJax following its retrieval with jQuery.load?

I recently encountered an issue while using jQuery.load to load a new page. The content on the original page is being treated strangely in some way. Specifically, I have code on the original page that formats LaTeX commands with MathJax: <script type=" ...

What is the best way to combine values passed from PHP to AJAX?

I need to combine the contents of showFname, showMname, and showLname and display the result in showName. However, I am facing an issue where the combined names are not appearing in showName. HTML <input type="text" id="showFname" name="showFname" /& ...

CSS animation is designed to work with a single element

For my school project, I've been experimenting with creating a functional phone using HTML. To achieve this, I incorporated a JavaScript class as shown below: document.querySelector(".app-content").classList.add("app-on"); The class .app-on alters th ...

How can one utilize Codemirror code folding while avoiding the use of "[ ]"?

I am looking forward to implementing Codemirror codefolding for folding only braces { and }, as well as comments. However, I am facing an issue where it also folds square brackets [ and ]. Since square brackets are usually part of one-line statements, I do ...

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

Node.js applications on Openshift frequently encounter 503 errors

I am currently in the process of setting up my initial Node.js + express web application utilizing Openshift's complimentary service. After installing node + npm and Openshift tools on my computer, I attempted to run my application. It functions perf ...

Trouble encountered while attempting to utilize @click="checkedInput" for displaying checkbox label in Vue.js?

const app = new Vue({ el: '#app', data: { checkedNames: [], checkedName: true, close: false }, methods: { uncheck(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); }, ...

What is the best approach to incorporating two distinct grid layouts within a single section?

I am attempting to replicate the header-graphic navigation found on this website: It appears that they are not using a grid for the header-graphic area, but rather keeping them separated as 2 divs within their Hero block container. I am interested in recr ...