0

I am using Repeater JS and it uses repeaterVal() function to fetch all input field values from nested repeater form and provides an object like this:

enter image description here

So, I created a variable var formData = jQuery('.repeater').repeaterVal() and passed that formData to the data of AJAX like this:


<?php $dir = plugin_dir_url( __FILE__ ) . "formdata.php"; ?>

<script>
var form = "<?php echo $dir ?>";

$.ajax({
    method: "POST",
    url: form,
    data: formData,
    success: function (data) {
        console.log("Form is submitted");
    },
    error: function (jqXHR, exception) {
        console.log(jqXHR);
    }
});
</script>

And then in the formdata.php file, I tried to echo those object values like this:

<?php 
$a = $_GET;
if(!$a){
    echo "Array is empty";
}
else{
    print_r(array_keys($a));
}
?>

And the AJAX data always send an empty object, I don't know why and where am I doing it wrong. But in a PHP file, when I try to echo object data, it shows me it's an empty array. I tried to add dataType as JSON in the AJAX but then the AJAX always returned the error message instead of success.

My goal is to send the form data in object form and then in PHP file, I wanted to fetch all those object data and then insert them into the MySQL database.

So, let me know how is that possible?

Farhan Ali
  • 13
  • 4

1 Answers1

0

You forgot to initialize the formData variable. Since you want to pass an object use JSON.stringify().

Do this

<?php $dir = plugin_dir_url( __FILE__ ) . "formdata.php"; ?>

<script>
var form = "<?php echo $dir ?>";
var formData1 = $('.repeater').repeaterVal();
var formData = new FormData();

formData.append('data',JSON.stringig(formData1));

$.ajax({
    method: "POST",
    url: form,
    data: formData,
    processData: false,
    contentType: false,
    success: function (data) {
        console.log(data);
        console.log("Form is submitted");
    },
    error: function (jqXHR, exception) {
        console.log(jqXHR);
    }
});
</script>

Setting processData to false will prevent jQuery from automatically converting the data into query string. Also don't forget to set the contentType to false.

Nelson Katale
  • 1,309
  • 15
  • 21
  • Glad it helped. :) – Nelson Katale Nov 23 '21 at 16:54
  • A quick question: Though the above solution works but it's sending all the data from Jquery to PHP in array form. But I wanted to send it as an object so that I can target all the data one by one and store them in the MySQL database. Or if you know a way to convert that received array in PHP to object? – Farhan Ali Nov 23 '21 at 19:34
  • Use `foreach` to loop through the array and save each item to the MySQL db. – Nelson Katale Nov 25 '21 at 08:00