Back

Technologies:

javascriptjavascript
jqueryjquery
phpphp
avatar
Tolerim
a day ago

Reworded: After modifying innerHTML, how do I submit a new form?

The issue I'm facing is that I have two forms on my page. I've successfully submitted one form via AJAX and updated the innerHTML on success. However, I'm now unable to submit the other form. Here's the code I'm using for the AJAX submission:

$(document).on('change', 'input[name=datavalue]', function() {
  var datavalue = $(this).val();
  $.ajax({
    type: 'POST',
    url: 'pra.php',
    data: { datavalue: datavalue },
    success: function(response) {
      document.getElementById("returnvalue").innerHTML=response;
      // handle success response
    },
    error: function(xhr, status, error) {
      console.log('AJAX request error:');
      console.log('Status:', status);
      console.log('Error:', error);
    }
  });
});
And here's the code for the other form:

I understand the concept behind the issue but haven't found a solution yet. Any help is greatly appreciated. Additionally, I've tried changing the second form's post to delegate function AJAX, removing the `type="submit"` attribute. However, when I try to log the data, it shows up as undefined. Here's the updated code:

$(document).on('click', '[name=add]', function() {
  var workDone = $("textarea[name='workDone']").val();
  $.ajax({
    type: 'POST',
    url: 'pra.php',
    data: { workDone: workDone },
    success: function(response) {
      document.getElementById("returnvalue").innerHTML=response;
      // handle success response
    },
    error: function(xhr, status, error) {
      console.log('AJAX request error:');
      console.log('Status:', status);
      console.log('Error:', error);
    }
  });
});
Answers(1)
avatar
Tolerim
a day ago
Verified Answer
The issue with the second form is that you are trying to access the value of the workDone variable without actually defining it. You should update the line var workDone = $(workDone).val(); to var workDone = $('textarea[name=workDone]').val();. This will select the textarea element with the name workDone and get its value, which can then be sent as data in the AJAX request. Additionally, it's best practice to prevent the default form submission behavior by calling event.preventDefault() inside the click event handler function to avoid any conflicts with the AJAX submission. Here's the updated code:
$(document).on('click', '[name=add]', function(event) {
  event.preventDefault();
  var workDone = $('textarea[name=workDone]').val();
  $.ajax({
    type: 'POST',
    url: 'pra.php',
    data: { workDone: workDone },
    success: function(response) {
      document.getElementById("returnvalue").innerHTML = response;
      // handle success response
    },
    error: function(xhr, status, error) {
      console.log('AJAX request error:');
      console.log('Status:', status);
      console.log('Error:', error);
    }
  });
});
;