When dynamically adding input data, the serialized array may not successfully pass through Ajax

function SubmitData(){
    var postData = $("#xForm").serializeArray();
    $.ajax({
    type: "POST",
    url: "mail.php",
    data: postData,
    success:function(data){
        console.log(data);
    },
    error: function(jqXHR, textStatus, errorThrown) 
    {
    console.log("Failure sending data");
    }
    });
}

$('#sub-comfirm').on('submit',  function (e){
    e.preventDefault();
    SubmitData();
});

function CreateImagePost(imgValue){
    var pImg = $("#mydata");

    var inputBlock = "";
    inputBlock += '<input type="hidden" id="canvasData" name="canvasData">';
    pImg.html(inputBlock);

    var element = document.getElementById("canvasData");
    element.value = imgValue;
}

My goal is to use serializeArray to get all my input data through PHP. The problem arises when adding the input "canvasData" using the function CreateImagePost; my PHP does not receive the data at all.

However, if I directly add the input "canvasData" to the HTML field, the data successfully passes through to my PHP. Why can't I pass my data when adding the input using a function?

Answer №1

After setting it up below, I found that everything you provided is functioning correctly. It's important to review your HTML code and compare it with mine to identify any differences.

If you have a form within another form, this is invalid HTML and will lead to issues. Also, if mydata is placed incorrectly, the serialize function may not be able to locate it.

function SendData() {
  PostImgCreate("XYZ");
  var postData = $("#xForm").serializeArray();
  console.log(postData);
}

$('#sub-comfirm').on('submit', function(e) {
  e.preventDefault();
  SendData();
});

function PostImgCreate(imgValue) {
  var pImg = $("#mydata");

  if(!pImg.find("#canvasData").length) {
      var inputblock = "";
      inputblock += '<input type="hidden" id="canvasData" name="canvasData">';
      pImg.html(inputblock);
  }

  var elem = document.getElementById("canvasData");
  elem.value = imgValue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <form id="xForm">
        <input name="xxx" type "text" value="testtest" />
        <span id="mydata"></span>
    </form>

<form id="sub-comfirm">
    <button type="submit">Submit</button>
</form>

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

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

WordPress display issue: AMCharts chart won't appear

I recently crafted an XY 2 series chart using the Amcharts library and have successfully integrated it into my WordPress website with the necessary plugin. This particular chart showcases load span values for construction spreader beams, and it was built ...

multiple simultaneous ajax calls being triggered

I am currently working on creating 4 cascading dropdowns, where the options in each dropdown repopulate based on the selection made in the previous one. To achieve this functionality, I decided to implement an Ajax call. The call takes the parameters, det ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Yii2 paired with Ajax: The output does not consist of the SQL query outcomes

I am facing an issue with executing an AJAX query using jQuery as the response is not as expected. On the client side: $.ajax({ url: "/family?idperson=1234", dataType: 'json', success: function(res) { console.log(JSON.string ...

Utilizing Jquery for seamless page transitions in Rails with the help of Ajax calls

I am currently working on a project that involves creating two pages. The first page will display a selection of items that I want to showcase on the second page. On the initial page, I have already picked out the specific items that I plan to show on the ...

Selecting an element using jQuery with the `:eq(i)` selector

I'm attempting to set the height of 10 hi div classes to different values. I am aware of the method to do so. $(".hi:eq(0)").css("height",n[0]); $(".hi:eq(1)").css("height",n[1]); $(".hi:eq(2)").css("height",n[2]); .......... $(".hi:eq(9)").css(" ...

How can one retrieve a Python object from a prior HTTP request?

I find myself in a bit of a dilemma when it comes to designing the asynchronous aspect of my web application. The situation is quite straightforward; a visitor uploads a file, extensive computation is performed on the file, and then the results are returne ...

What is the best way to ensure my buttons hide or display correctly when clicked?

I have been working on setting up an edit button that toggles the visibility of save and cancel buttons. However, I encountered a problem where all the buttons disappear when I click on the edit button. This issue did not occur with my other buttons, and t ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

The hover effect in CSS brings life to list items when filled with content

I am attempting to create an animation for an <li> element that gives the illusion of a fill effect moving from left to right when hovered over. This is my current progress: ul { list-style-type: none; } .hoverTest { float: left; margin-right: 1 ...

Tips for combining several JSON objects in a Node.js/Jade merge operation

Given the code below which sets up various configurations for a company: default.js (utilized by config.js to load base configurations) { "templateData": { "corp": { "corpName": "Company", "DepartmentOne": { "name": "Dep ...

Authenticate users using JavaScript usernames

Below is my registration link that opens a modal: <a href="#registermodal" data-toggle="modal">Register Here</a> Here is the code for the modal dialog: <div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;"> ...

Tips for dynamically updating the div class based on the model's value

How can I dynamically change the CSS class of a bootstrap element based on a value? I would like to display a div in green if the value is "OK" and red otherwise. If status = "OK", it should look like this: <div class="small-box bg-green">, else < ...

Show a picture without specifying its file location

Looking for Suggestions on a New Title I am interested in using a script as the source attribute for an image, like this : <img src="img.js"/> Note: I am open to using any programming language, whether it be javascript or php. Here is what my fol ...

How can I easily activate a C# class from an asp.net webpage?

I have three labels in my asp.net page: One with a default name for filtering Another filled with a list of names to click on for new filter A third one with a list of items to be filtered The content of the second and third labels is loaded by C# code ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Problems with select tag change events

I encountered an issue with select tag onChange events. When I select a value from the select tag, it should display in a textbox that is declared in the script. It works perfectly when I remove the class "input" from the select tag, but I prefer not to re ...

Issue encountered when trying to add data into MySQL database

Having trouble inserting data into my MySQL database, even though I believe I'm doing it correctly. Does anyone know how to troubleshoot this issue or if I may have overlooked something? Everything seems to be working fine, but for some reason, it&apo ...

Upon receiving the ajax request, the entire code page is called back

I'm having trouble saving data using a button in Laravel. When I use console.log, the entire code appears in the console and I don't understand why this is happening. Here is my input field and button: <form action="{{ url('sendcom& ...