Transmit data from a form row to an external PHP script

I'm facing an issue that I need help resolving.

My challenge is to transfer data from a form ROW to a php file.

Below is the initial PHP code (embedded within an echo statement where values are fetched from a MySQLi query):

<form id=\"comedivid\" method=\"post\">
    <input class=\"numer-qua\" type=\"number\" id=\"dadivid\" min=\"0\" max=".$_GET['qua']." autofocus autocomplete=\"off\" name=\"dadivid\" maxlength=\"4\" size=\"5\">
    <input type=\"hidden\" value=\"".$row["id_tes"]."\" name=\"ord\" id=\"ord\">
    <input type=\"hidden\" value=\"".$_GET['codice']."\" name=\"cod\" id=\"cod\">
    <input type=\"hidden\" value=\"".$_GET['qua']."\" name=\"arr\" id=\"arr\">
    <input type=\"hidden\" value=\"".$row['descri']."\" name=\"desc\" id=\"desc\">
    <input type=\"hidden\" value=\"".$row['unimis']."\" name=\"um\" id=\"um\">
    <input type=\"hidden\" value=\"".$row['quanti']."\" name=\"qua\" id=\"qua\">
    <input type=\"hidden\" value=\"".$row['prelis']."\" name=\"pre\" id=\"pre\">
    <input type=\"hidden\" value=\"".$row['sconto']."\" name=\"sco\" id=\"sco\">
    <input type=\"hidden\" value=\"".$row['codvat']."\" name=\"cva\" id=\"cva\">
    <input type=\"hidden\" value=\"".$row['pervat']."\" name=\"iva\" id=\"iva\">
    <input type=\"hidden\" value=\"".$row['codric']."\" name=\"ric\" id=\"ric\">

    <button id=\"dividili\" class=\"btn btn-blue\" type=\"submit\"><i class=\"fa fa-copy\"> Dividi Riga</i></button>
            \n";

The form is nested within a table and the query may yield multiple results.

Here's the AJAX code snippet:

$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
    event.preventDefault();
    var dadivid = $("#dadivid").val();
    var ord = $("#ord").val();
    var cod = $("#cod").val();
    var arr = $("#arr").val();
    var desc = $("#desc").val();
    var um = $("#um").val();
    var qua = $("#qua").val();
    var pre = $("#pre").val();
    var sco = $("#sco").val();
    var cva = $("#cva").val();
    var iva = $("#iva").val();
    var ric = $("#ric").val();


    $.ajax({
        type: "POST",
        url: "../../modules/acquis/dividi.php",
        data: "dadivid=" + dadivid + "&ord=" + ord + "&cod=" + cod + "&arr=" + arr + "&desc=" + desc + "&um=" + um + "&qua=" + qua + "&pre=" + pre + "&sco=" + sco + "&cva=" + cva + "&iva=" + iva + "&ric=" + ric,
        success: function(){alert('success');}
    });
});

});

However, I am encountering issues as no data is being sent to the URL.

Could this be due to the form being in multiple rows? Or could there be an error in my code?

I have also tried using serialize with no luck.

Below is the code snippet:

$("#dividili").click(function(e){ 

    $.ajax( {
      type: "POST",
      url: "../../modules/acquis/dividi.php",
      data: $('#comedivid').serialize(),
      success: function( response ) {}
    });
});

Any assistance on this matter would be highly appreciated. Thank you!

Answer №1

One recommendation I have is to utilize the serialize() function:

$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
    event.preventDefault();

    var form_data = $('form#comedivid').serialize();
    // or
    var form_data = $(this).serialize();

    // Check the output for accuracy
    console.log( form_data );
    // or
    alert( form_data );

    $.ajax({
        type    : "POST",
        url     : "../../modules/acquis/dividi.php",
        data    : form_data,
        success : function(){alert('success');}
    });
});

If you have already tried this and the output seems correct, then there may be an issue with your PHP code. To troubleshoot, you can add this at the beginning of your file to see what was received:

<?php

echo '<pre>';
print_r( $_POST );// or $_REQUEST for both $_POST and $_GET
echo '</pre>';
die;

// Continue with the rest of your PHP code...

If the data is being received properly in PHP, ensure that you are accessing the data correctly like so: $dadivid = $_POST["dadivid"];

Answer №2

When using the jQuery 'serialize' method, data is formatted similarly to a GET query form.

However, it's important to keep in mind that the length of the data may be limited by the Apache configuration.

To work around this limitation, you can try using a custom method like the one below:

(function($) {
    $.fn.serializeObject = function () {
        "use strict";
        var result = {};
        var extend = function (i, element) {
            var node = result[element.name];
            if ('undefined' !== typeof node && node !== null) {
                if ($.isArray(node)) {
                    node.push(element.value);
                } else {
                    result[element.name] = [node, element.value];
                }
            } else {
                result[element.name] = element.value;
            }
        };
        $.each(this.serializeArray(), extend);
        return result;
    };
});

To use this custom method, simply replace the default jQuery 'serialize' method with 'serializeObject'.

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

Uploading large files on Vuejs causes the browser to crash

Whenever I try to upload a file using my browser (Chrome), everything goes smoothly for files with a size of 30mb. However, if I attempt to upload a file that is 150mb in size, the browser crashes. The server's maximum upload size has been configured ...

Add a product to your shopping cart in Opencart with the help of Ajax manually

My goal is to automatically add a product to the cart when a user clicks on a button using a custom function that I created. Here is the code for the button: <input type="button" value="Add to cart" onclick="addItemsToCart(83); " class="button btn-suc ...

Permission not granted on Internet Explorer versions 10 and 11 for ajax requests targeting localhost

I have been facing an issue with making an ajax call from a server on the internet to my localhost. This works perfectly fine on browsers like Firefox and Chrome, but I am encountering problems specifically with Internet Explorer versions 11 and 10. The r ...

What issues could arise from utilizing PHP for generating variables within my CSS file?

One major limitation of CSS is the absence of variables. It would be beneficial to have the ability to use variables for controlling things like the location of imported CSS and color schemes within a design. An alternative solution could involve using a ...

Difficulty in packaging JavaScript resources within Laravel Project

Having trouble setting JS functions as global in my project: In the 'resources\js"', I have: numerosALetras.js: /////////////////////////// function unidades_nal(n){ ... } function decenas_nal(n){ ... } function centenas_nal(n){ ...

I am attempting to establish a connection to a database using PDO within the CodeIgniter framework

$database_config = array( 'hostname' => 'mysql:host=myhostname;dbname=test;', 'username' => 'root', 'password' => '', 'database' => 'test', &apo ...

Is it possible to track down the usage of the var_dump function?

Recently, I started experimenting with Laravel 4 and came across an issue while using the ORM to create a new user account. After executing the code, the following output was displayed on the page: array(1) { [0]=> object(stdClass)#103 (1) { ...

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

I am experiencing an issue where I cannot select a row in datatables to transfer the data to a text field in Laravel 5

I am currently working on a web application using Laravel 5.4. There are certain modules where I have a main form that triggers datatables to appear in a modal dialog window (for example: when I click on a search button, the modal window displays datatable ...

Steps to change the name of the key in a foreach iteration?

Currently, I am working on creating an XML file from a database query. The utility class that I am utilizing is giving me an error message stating Illegal character in tag name. tag: 0 I have identified that this issue stems from the array elements being ...

What is the method to link a progress bar to the value of a text input?

I'm currently working on an application where users need to input the percentage of their skill proficiency, and I want the progress bar to automatically reflect that value. I require assistance with this task, preferably using PHP only, but Java can ...

Transfer image data in JSON format by compressing it into a base64 string from an Android device to a PHP web

I am attempting to upload an image (compressed in base64) as a JSONObject from an Android device to a web service using PHP. I have tried using HttpURLConnection with the POST method. Here is my code in Android: try { JSONObject params = new ...

Create a Flot graph using data from a database

Here is a snippet of jQuery code that I am currently working with: jQuery(document).ready(function () { var formData = "f=27/07/2015&t=01/08/2015"; jQuery.ajax ({ url: 'http://www.yourhealthfoodstore.co.uk/test.p ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...

Eliminate excess space around images in Bootstrap

I have an image tag with a padding applied to it. I am using the Bootstrap CSS framework. Currently, there is a white background behind the image that I want to remove and make it partially transparent instead. The image is in PNG format, so I suspect the ...

"Enhance Your WordPress Website with the Power of jQuery

I have been developing a unique Wordpress plugin that incorporates a grid loading effect using jQuery. The script I have implemented is as follows: <script type="text/javascript"> new GridScrollFx( document.getElementById( 'grid' ), { ...

Streamline retrieval of alphanumeric indexing within json

When accessing json data using jquery, I came across an index structure like this: data.rows[0].student_1 data.rows[0].student_2 data.rows[0].student_3 and so on... Now, I'm looking to automate this process by creating a loop that allows me to acces ...

executing jQuery toggle on freshly generated content

I have a webpage that I designed using jQuery. Within this page, there is a table with rows assigned specific color classnames (e.g., tr class="yellowclass"). Users can filter the rows by clicking checkboxes to show/hide tables of different colors. The i ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

Issue with anchor tag not functioning properly within toggle div

Can you please help me troubleshoot why the anchor tag is not functioning properly within my div elements? When I click on the first div, the second div is displayed but the anchor tag inside the first div does not seem to be working. <script> $(&ap ...