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

Result of jQuery Ajax responseText: "An issue occurred while processing your request."

I encountered an issue with the UAT environment where I received the error message "There was an error processing the request". Interestingly, the code works fine in my local environment. The line Utility.WriteLogEvent("TestService", strMessage); is respo ...

ajax-triggered forms

Is there a way to ensure that a form functions correctly when it is included in the HTML loaded via AJAX? I am utilizing jQuery for this task. Any suggestions or advice would be appreciated. ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

How can I combine an ordinary image and a CSS2D image in THREE.js CSS2DRenderer and save them together as a single .jpg file?

After implementing the following code... (1) I successfully saved regular rendered THREE.js scenes as .jpg files; (2) Additionally, I managed to utilize CSS2DRenderer to display CSS2D labels on top of the canvas; (3) Now, my goal is to save the image wi ...

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

The dot notation in JSON syntax allows for easy access

Recently, I've been struggling with referencing a variable in JSON dot notation within my meteor application. It seems that when trying to access respJson.userlower.name, userlower is not being recognized as a valid variable. Is there a workaround for ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Rearrange element's placement using Jquery Drag & Drop

I am experiencing difficulties in positioning my elements after a drop event. Within my "list" of divs... In order to keep the divs together and update the list, I utilize jQuery's append function to move the element from the list to its designated ...

Is there a way to verify the selection of all mandatory fields prior to concealing a div?

var count = 2; $('.next').click(function() { var requiredField = true; $(this).siblings('table').find('tbody tr:nth-child(' + count + ') td').each(function() { var element = $(this).find('center').f ...

Display data fetched from concurrent Ajax calls in a React Component

I am currently in the process of converting my original project to Reactjs. Since I am new to this and it's my first application, I could use some guidance on how to effectively implement this in a React-friendly way and enhance both my skills and the ...

Button with a Jquery icon design

Hello, I am currently working on implementing an icon button that can collapse and expand text. Although I have successfully implemented the logic for collapsing/expanding, I am facing difficulties in creating the actual icon button. The theme I am require ...

Choosing various files from separate directories within an HTML input type="file" element

Is there a way to select multiple files from various directories using the HTML input type="file" element? I have been searching for resources on how to do this without any luck. Are there any npm packages that can assist with achieving this functionalit ...

A method for calculating the product of two selected numbers and then adding them together

I am currently working on a form that includes two select options; one for logo design and another for letterhead design. Users should be able to choose the quantity of each design, or both if they wish. For example, a user could select 2 logo designs and ...

TimePicker Component for ASP.Net MVC with Razor Syntax

I'm currently working on implementing a TimePicker using Razor and JQueryUI in my bootstrap website. While I have successfully created a DatePicker, I am facing difficulties in creating a separate TimePicker using two different TextBoxes instead of se ...

Keeping state between navigations in Ionic and AngularJS: A guide

In the process of developing my very first hybrid mobile application using Ionic and AngularJS, I have encountered a challenge that I am currently trying to resolve. The issue at hand involves maintaining the state of the graphical user interface between n ...

Browser Fails to Recognize AJAX Links as Visited

It appears that the styles for a:visited do not apply to links that are loaded via JavaScript. When a user clicks on a standard link, it shows as visited right away and even after refreshing the page. I'm uncertain if this issue is specific to jQuery ...

Spider login page

My attempt to automate a log in form using Scrapy's formrequest method is running into some issues. The website I am working with does not have a simple HTML form "fieldset" containing separate "divs" for the username and password fields. I need to id ...

The AnchorEL component becomes unusable once a function has been executed for the first time

I am facing a challenge with anchorRef and struggling to understand how it works as I am new to React and have never used it before. After the onClickAway method is called, Material-UI shows an error stating that the anchorRef is set to null, but this warn ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

Is there a way for me to utilize a single set of checkboxes for submitting multiple times in order to generate multiple selections simultaneously?

I'm exploring the idea of using checkboxes that can be dynamically updated and posted to a PHP page multiple times. The goal is to send different sets of selections from the same checkboxes to the PHP page, with each set being treated as data for furt ...