Home > OS >  How to send jquery object data through AJAX to php?
How to send jquery object data through AJAX to php?

Time:11-24

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?

CodePudding user response:

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.

  • Related