Create a form action dynamically with JavaScript

html code :

<section class="main">
<form class="form-4" name="form4" id="form4" method="POST">
    <p class="submit">
        <button type="submit" name="submit" onclick="show()"><i class="icon-thumbs-up icon-large"></i></button>                     
    </p>
</form>
</section>

js code :

function show(){

      $.ajax({        
      type: "POST",
      url: "check_login_points.php",
      data: {test : JSON.stringify(arr)},
      success: function(data) {

                if(data == 0)
                {

                  alert("       SORRY :( \n misplaced cue points.");
                }
                else if(data == 1)
                {
                  document.getElementById("form4").action = "http://localhost/profile_book/login_key.php";
                  //alert("WELCOME !!!");
                  //$("#form4").attr('action', 'http://localhost/profile_book/login_key.php');
                }
                else if(data == 2)
                {

                  alert("enter cue-points");
                } 
            }
        }); 
}

I am attempting to set the form action in JavaScript after a successful ajax call, but unfortunately, it doesn't seem to be working as expected. Any suggestions or solutions would be greatly appreciated. Thank you in advance!

Answer №1

In order to achieve your desired outcome, you may encounter some challenges due to the asynchronous nature of the process. It will be necessary to divide the task into multiple parts for successful execution.

To begin with, consider renaming the button to avoid potential conflicts:

<button type="submit" name="btnSubmit" />

Next, establish a form submission binding using jQuery instead of inline events:

$("#form4").on("submit", function(event) {
    // Prevent default submission behavior
    event.preventDefault();
    // Call the required functions
    show();
});

Finally, ensure that the submit action is manually triggered after setting the appropriate action:

function show (){
      $.ajax({        
      type: "POST",
      url: "check_login_points.php",
      data: {test : JSON.stringify(arr)},
      success: function(data) {

                if(data == 0) {
                  alert("SORRY :( \n misplaced cue points.");
                } else if(data == 1) {
                  $("#form4").attr("action", "http://localhost/profile_book/login_key.php")[0].submit();
                } else if(data == 2) {    
                  alert("enter cue-points");
                } 
            }
        }); 
}

Answer №2

Allow me to take a guess. It seems like you are inquiring about why the form is not submitting. If that's the case, it could be due to the absence of the form-submit function:

var submission = document.getElementById("form4");
submission.action = "http://localhost/profile_book/login_key.php";
submission.submit()

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

Ensuring model accuracy in Asp.Net Core prior to initiating an Ajax request via JavaScript

Here is a snippet of code that I am currently using, which is triggered on a button click event. The question I have is regarding the validation of my viewmodel object before sending an ajax call. I can see model errors in JavaScript, but I'm unsure o ...

Controlling Material-UI using a custom .css stylesheet

Are there alternative methods for customizing Material-UI components using CSS stylesheets? I'm aware of the {makeStyles} method and JSS overrides, but I find it messy in the code and confusing when trying to modularize it in other files. Is there a ...

Ways to conceal and reveal image and text elements based on array loop output

I am currently working on setting up a questionnaire. The questions and answer options are being pulled from a database using an API. Some of the options include images, with the image link stored in the database. I am trying to find a solution where text ...

Using jQuery, identify when any of the elements within every function are missing

In my JavaScript file, I have the following code snippet: var aryYears= []; $(".year").each(function(){ aryYears.push($(this).val()); }) This allows me to pass an array of years as a parameter in the saveChanges function. I want to make ...

Retrieve information about the clicked item using the Backbone framework

I have a unique webpage that showcases an impressive collection of books. Each book listed on the page comes with essential information such as the title, price, and description. This data is imported from a JSON file. Excitingly, when users click on any ...

Hiding content in HTML with the Display:none property

After exploring various posts on this topic, I am still unable to find a solution that fits my specific scenario. Despite the challenges, I thought it would be worth asking for recommendations. Currently, I have a PowerShell script generating a report in ...

Is it possible for nextAll() to exclude a specific parent element and search only for children inside that parent?

Below is the structure of my html ajax form: <form name="vafForm" id="vafForm" method="GET" action="urlfor ajax"> <input type="hidden" value="0" id="vafProduct"> <select class="catSelect {prevLevelsIncluding: 'cat'} c ...

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Exploring the process of traversing a function for each ng-repeat element

Hey everyone, I'm currently facing an issue where I need to pass each date through a function in order to get the desired result. Let's take a closer look at the code snippet: <md-list> <md-divider ></md-divider> ...

Ajax request fetching distinct data from database

My regular ajax function successfully posts to a php page and retrieves data from a table. However, I encountered an issue when attempting to set the user's FB image. The error message I received was: "error": { "message": "Unsupported get reques ...

Looking for assistance with navigating through this URL using Python (requests, beautifulsoup, or selenium) or Javascript (node js, puppeteer)?

While attempting to gather data, I encountered an interesting pagination challenge on the following URL: My expertise in Web Scraping was put to the test as this website implemented a unique JavaScript-driven pagination. For the initial 5 pages, it simply ...

A numeric input area that only accepts decimal numbers, with the ability to delete and use the back

I have successfully implemented a code for decimal numbers with only two digits after the decimal point. Now, I am looking to enhance the code in the following ways: Allow users to use backspace and delete keys. Create a dynamic code that does not rely o ...

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...

Variations in jQuery's append method when dealing with a string, a reference to a jQuery object

Here are multiple ways to add a div element to the body of an HTML document. But what distinctions exist between them and in what scenarios should each be utilized for optimal performance? var newDiv = '<div id="divid"></div>'; $(&ap ...

Starting your React application with the `npm start` command

After creating my react app using the create-react-app command, I named it react-app. These were the steps I followed: Navigate to the directory by typing cd react-app/ Run the command npm start Encountered an error message that reads; npm ERR! Missing ...

Encounter issue when attempting to insert multiple items into MongoDB

// Import User and Item Models const User = require('../../models/User'); const Item = require('../../models/Item'); router .post('/login/:id', passport.authenticate('jwt', {session: false}), (req, res) => { ...

The functionality of the AJAX Script is failing to load properly on mobile devices

Currently, I am undertaking a project that involves ESP32 Arduino programming to create a webpage where users can interact with buttons to activate relays. Additionally, I have implemented a slider using a short script. This project is inspired by the ESP3 ...

Can a library be developed that works with both Java and JavaScript/TypeScript?

I specialize in Angular development. Our front- and backend both contain specialized calculation methods that work like magic. Although the classes are the same, any bugs found in the calculations have to be fixed separately in two different projects. Is ...

"Encountering an issue with ASP.NET MVC and Angular when making an AJAX call with multiple parameters, the HttpPostedFileBase

When sending an object and a file from my Angular service, the following code snippet is executed: $scope.addProject = function () { { var project = {}; project["Id"] = $scope.Id; project["ProjectCode"] = $scop ...

What is the best way to automatically log out a user once their session cookie has expired during an online exam?

While developing an MVC ExpressJS Test app, I encountered an issue with auto-logout functionality for users who stop answering test questions. The error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" keeps app ...