0

im trying to pass javascript arrays in a jquery .post, but it's not showing on the page. What am i doing wrong? i see that my arrays are filled, but the data is not showing on the page post. The console log shows the p element also i dont know why it's doing that.

jquery code:

 $("#submitboeking").click(function(event) {

        event.preventDefault();


        //Cursisten
        var voornamen = [];
        var achternamen = [];
        var geslachten = [];
        var geboortedata = [];

        $("[id^='txtCursistVoornaam']").each(function() {
            voornamen.push($(this).val());
        });
        $("[id^='txtCursistAchternaam']").each(function() {
            achternamen.push($(this).val());
        });
        $("[id^='radCursistGeslacht']:checked").each(function() {
            geslachten.push($(this).val());
        });
        $("[id^='txtCursistGeboortedatum']").each(function() {
            geboortedata.push($(this).val());
        });

        // console.log(voornamen);
        // console.log(achternamen);
        // console.log(geslachten);
        // console.log(geboortedata);

        $.post('/wp-content/themes/tweb/processboeking.php',
         {


            voornamen: voornamen,
            geslachten: geslachten,
            voornamen: voornamen,
            achternamen: achternamen,
            geboortedata: geboortedata,
            })
            .done(function(data)
             {
                console.log(data)
                $('#overzichtboeking').html(data);

            }).fail(function(data) {
                alert(response.responseText);
            });

        var li_count = $('.nav-tabs li').length;
        var current_active = $('.nav-tabs li.active').index();
        if (current_active < li_count) {
            $('.nav-tabs li.active').next('li').find('a').attr('data-toggle', 'tab').tab('show');
            var txt = $(".oplselect option:selected").text();
            var val = $(".oplselect option:selected").val();
            $('.showoplnaam').html('Uw selectie: ' + txt);
        }

    });

console.log data:

Array
(
    [voornamen] => Array
        (
            [0] => G.F.
        )

    [geslachten] => Array
        (
            [0] => Dhr.
        )

    [achternamen] => Array
        (
            [0] => martens
        )

    [geboortedata] => Array
        (
            [0] => 25-10-1993
        )

)
<p id="overzichtboeking"></p>  

processboeking.php

<?php
include '/home/vhosts/tweb.nl/httpdocs/wp-content/themes/tweb/db/dbcon.php';

print_r($_POST);

?>
<p id="overzichtboeking"></p>  
  • _"The console log shows the p element also"_ - The result of the ajax request will contain _all_ output from the requested page. Since you're outputting `

    ` in the end of the requested file, it will be a part of the response.
    – M. Eriksson Apr 30 '19 at 08:10
  • You also shouldn't need to manually add `[]` to the end of the key names on the request data. Since those variables already are arrays, jQuery should handle it for you. – M. Eriksson Apr 30 '19 at 08:14
  • @MagnusEriksson check my edit, i changed the [], but still no response on my print_r post. – nielsmartens Apr 30 '19 at 08:33
  • What do you mean by _"still no response on my print_r post"_? So where does the "console.log data" in your question come from? That looks like the output of print_r(), if you ask me? – M. Eriksson Apr 30 '19 at 08:34
  • @MagnusEriksson im trying to catch the post on the page processboeking.php, so my print r_post needs to show the data on the page processboeking. The console.log is showing the data in the console. You see that i am also doing a $('#overzichtboeking').html(data); that means that the data is put in the id of overzichtboeking and that it needs to show on the page, but it doesnt. the data is only in the console and not on the page. – nielsmartens Apr 30 '19 at 08:41
  • Convert the javascript array to a json string and pass that through to the PHP server side script. before using it in the script, json_decode it back to any array. – Jim Grant Apr 30 '19 at 08:47
  • @JimGrant do you got an example ? i'm new to this. – nielsmartens Apr 30 '19 at 08:51

1 Answers1

0

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});

Taken from this stackoverflow post: How to send a JSON object using html form data

To go from JSON input on the server side, take a look at this article for converting back to a PHP array: https://www.dyn-web.com/tutorials/php-js/json/decode.php

Jim Grant
  • 1,128
  • 2
  • 13
  • 31
  • it's not form data. – nielsmartens Apr 30 '19 at 09:45
  • Okay but the principle still applies. Instead of having `var formData = JSON.stringify($("#myForm").serializeArray());` you will have for each array `var array1 = JSON.stringify(voornamen);`. Then in your POST Ajax call, you will send through the `arrayX` variables. On the server side, you'll call the JSON_DECODE function on each of the `$_POST['arrayX']` variables. – Jim Grant Apr 30 '19 at 10:38
  • There's no reason for manually using `JSON.stringify()`. If you want to post a complete form, just do: `data: $('#your-form').serialize()`. And if you want to post some custom data, just pass a json object: `data: {someArray: ['foo', 'bar', ...], someKey: 'hello world'}`. – M. Eriksson Apr 30 '19 at 12:02
  • It also seems a bit unnecessary to encode the data (using JSON.stringify) before you send it, just to decode it again in the back end when PHP receives it. Just send it as normal post-parameters – M. Eriksson Apr 30 '19 at 12:08
  • The user has stated that this isn't form data, hence why I suggested about replacing the `serializeArray()` on the form to looking at individual elements. The `JSON.stringify` creates the JSON object from a JavaScript array and permits it to be transmitted via HTTP(S). If @nielsmartens was simply sending through alphanumerical text, then you are right, encoding and decoding, is pointless. – Jim Grant Apr 30 '19 at 12:56