Unsuccessful retrieval of hidden property's value following ajax request

While using my web app, I encountered an issue with my ajax script that submits form data to a different div based on an input tag within the submitting form. Everything works smoothly until the moment the ajax script needs to read the returned ajax data.

Here's the script in question:


<script type="text/javascript">
$(document).ready(function() {
 $("form").submit(function() {
 // Getting the form ID
 var  formID = $(this).attr('id');

var hv = $('input[name=target]').val(); 
alert(hv);

//alert( $("#form2 input[name=target]").val() ); //works
alert ("formID at start is " + formID);
if (formID =="form1") {
    var hv = "div2";
    alert ("form id at 1st if is " + formID);
}
if (formID =="form2") {
    var hv = "response";
}
if (formID =="contact3") {
    var hv = "div1";
}

var formDetails = $('#'+formID);
$.ajax({
 type: "POST",
 url: 'file.php',
 data: formDetails.serialize(),
 success: function (data) { 
 $('#'+hv).html(data);
 },
 error: function(jqXHR, text, error){
 $('#'+hv).html(error);           
 }
 });
 return false;
 });
});
</script>

And here is the corresponding HTML code:

<div id="div1" style="background-color:lightblue">
    <form  name="contact1" action="contact.php" method="POST" id="form1">    
 <div>Name: <input type="text" name="name" id="name"   required /></div> 
 <div>Email: <input type="email" name="email" id="email"  required /></div>
 <input type="hidden" name="target" value="form2">
 <div><input type="submit" name="submit" value="Submit" /></div> 
</form>

    <p>This is Div FORM1</p>
</div>

<hr>


<div id="div2" style="background-color:yellow">
<form name="contact2" action="contact.php" method="POST" id="form2">    
 <div>Name: <input type="text" name="name"  required /></div> 
 <div>Message: <input type="text" name="message"  required /></div>
 <input type="hidden" name="target" value="response">
  <div><input type="submit" name="submit" value="Submit" /></div> 
</form>
    <p>This is DIV form 2</p>
</div> 




<div id="response" style="background-color:brown"><p>This is DIV Response. </p><p>This is DIV Response. </p><p>This is DIV Response. </p><p>This is DIV Response. </p><p>This is DIV Response. </p><p>This is DIV Response. </p></div>


Moreover, there is a file called file.php which contains:

<?php

if(isset($_POST['email'])){
 echo "Contact Form 1 Submitted Successfully";
}
elseif (isset($_POST['message'])){
 echo "Contact Form 2 Submitted Successfully";
}
elseif (isset($_POST['message'])){
 echo "Contact Form 3 in RESPONSE Submitted Successfully";
}
?>

<form name="contact3" action="contact.php" method="POST" id="contact3">    
 <div>new content: <input type="text" name="contact3"  required /></div> 
 <div>New content <input type="text" name="message3"  required /></div>
 <input type="hidden" name="target" value="form1">
 <div><input type="submit" name="submit" value="Submit" /></div> 
</form>

The problem arises when clicking the submit button for form2 as it updates the response div correctly. However, when trying to interact with the loaded contents from file.php, the jQuery script fails to work, causing the browser to post the entire screen to file.php instead of executing the intended ajax posting!

An intriguing mystery indeed!

Answer №1

The issue with the PHP file's new form lies in its dynamic addition, requiring a modification to your code as demonstrated below.

Replace

$("form").submit(function() {

With

$(document).on('submit', 'form', function() {

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

Steps to load data using ajax-php with specific parameters

I have a situation where I need to trigger a JavaScript function when a link is clicked. <input type='hidden' id='name'> <a href='#' onclick='getUsers(1)'>Click here</a> function getUsers(id){ $( ...

What is the best way to effectively test jQuery's .ajax() promises using Jasmine and/or Sinon?

There is a simple function that returns a jQuery .ajax() promise: CLAW.controls.validateLocation = function(val, $inputEl) { return $.ajax({ url: locationServiceUrl + 'ValidateLocation/', data: { 'locationNam ...

Manipulate classes based on scrolling (Wordpress)

Trying to manipulate a widget by adding and removing classes based on user scroll behavior has proven to be quite challenging. Specifically, I aim to add one class when the user scrolls down by 50px and remove it when they scroll back up. Website: Check o ...

Obtain POST information through AJAX and jQuery

post.js $.post( "/scripts/update.php", {id: testId, age: testAge}, function(data) { $(".testDiv").html(data.testId); $(".testDiv2").html(data.testAge); } ); update.php $userId = $_POST["id"]; $userAge = $_POST["age]; // contact database ...

An always-visible navigation menu

After exploring various resources related to the same topic, such as sticky navigation bars and others, I noticed that all the solutions provided involved the use of this link http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js. However, inc ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

Navigating through the img src using JavaScript

Currently, I am working on a task that involves the following code snippet: <input type="file" id="uploadImage" name="image" /> <input type="submit" id="ImageName" name="submit" value="Submit"> My goal is to have the path of the selected imag ...

Discover the ultimate guide to creating an interactive website using solely JavaScript, without relying on any server-side

I'm facing a challenge: I have a desire to create a website that is mainly static but also includes some dynamic components, such as a small news blog. Unfortunately, my web server only supports static files and operates as a public dropbox directory. ...

The integration between curl_exec and Mailchimp fails to function properly when implemented with AJAX

I have successfully set up a form within my Wordpress site to send data to Mailchimp using their API. When I use a standard form that redirects to a designated page, everything works smoothly and all the data gets imported as expected. However, I am now t ...

Revamping the values attribute of a table embedded in a JSP page post an AJAX invocation

I am encountering an issue with displaying the content of a table. The table's data is retrieved via an AJAX request when clicking on a row in another table on the same page. Here is my code for the JSP page: <table id="previousList" class="table" ...

Leveraging AJAX for fetching files on the identical server

Just starting out with HTML and AJAX programming, so let's give it a shot: I've developed a website that populates a table with content from an external txt file (content.txt). The text file is hosted on a Windows 2003 webserver in the C:\I ...

Can a PHP script be executed through an Ajax event?

Is it feasible to execute the script of a PHP file when an AJAX event is triggered? Consider this scenario: on the AJAX error, could we send the data to the error.php file, record the error, notify the admin via email, and perform any other desired action ...

Invoke a Google Apps Script through AJAX that necessitates authentication

I am looking to access a Google Apps Script via AJAX that requires user authorization to send an email from their Gmail account. The challenge lies in the fact that I need to send the email from within the Google Apps Script. The call originates from my w ...

The function $.getJSON() seems to be non-responsive

I've been struggling to solve this issue for quite some time now. The users.json file that I am using can be found in the "JSON" folder alongside the other files. The alert("Before") is functioning properly, but I'm facing difficulty with getting ...

The URL overwrites the Ajax transfer type

When making an ajax call using a generated URL from a paginator script, I encountered an issue. The URL was dynamically created as shown below: "http://192.168.1.23:8000/pricing/0/999/null/?page=9" A similar link is generated on the server: "https://xxx ...

Issues with Recursive Ajax Functionality in Internet Explorer 11

Trying to perform consecutive ajax GET calls using the $.ajax jQuery method in order to handle a large JSON data size of around 2MB. The process runs smoothly in Chrome, but encounters issues in IE11. In IE11, it consistently falls into the fail method dur ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

PHP - Implementing a Submit Button and Modal Pop-up AJAX across multiple browsers in PHP

As a newbie in PHP AJAX coding, I'm facing a challenge with having two browsers. My goal is to click the submit button on one browser and have a modal popup on the other browser simultaneously. Essentially creating a chat system where only a button an ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

Send data with AJAX and PHP without refreshing the page

I have implemented the "add to favorite" feature on my WordPress project using a <form> submission. Each time I click on the add to fav button, it works fine, but the page always reloads which is quite annoying. To tackle this issue, I decided to imp ...