0

I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content. The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()! If I put manually a number in $ore it works fine, so the problem is not the query.

Thank you.

Here's the code:

JQuery

$('form').submit(function(e) {

                e.preventDefault();

                var formId = $(this).attr('id');
                var data = area_get_row_date(formId);

                var parametriPost = $(this).serialize() + '&data_r=' + data;


                $.ajax({                                      
                    url: 'insert_db.php',                  
                    method: 'POST',
                    async: false,
                    data: parametriPost,
                    success: function() {

                         // Success code
                    },
                    error: function(xhr, status, error) {
                        alert("Errore!");
                    }
                });
            });

PHP (insert_db.php)

$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];

    $sql = "INSERT INTO ore_lav
            VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";


    $results = api_store_result(api_mysql_query($sql));

This is what parametriPost contains:

lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
javabrett
  • 7,020
  • 4
  • 51
  • 73
user123456
  • 241
  • 1
  • 3
  • 10
  • 1
    basic debugging: `var_dump($_POST, $_SERVER['REQUEST_METHOD'])`. confirm that php actually received that data, and that a POSt was actually performed. And you are vulnerable to [sql injection attacks](http://bobby-tables.com) – Marc B Jul 29 '15 at 14:20
  • Maybe this helps: http://stackoverflow.com/questions/6627936/jquery-post-with-serialize-and-extra-data – NiMeDia Jul 29 '15 at 14:22
  • 1
    `data_r=')); DROP TABLE ore_lav;` :( Anyway, it works for me - `$_POST` contains all the fields as expected. – riv Jul 29 '15 at 14:23
  • Umm you have `orelavorateore_3_07_2015=` (empty string) in your parameters. What exactly are you expecting to get? Also if you're using double quoted strings in PHP, you don't need to use append syntax, you can just put variables inside the string, like `"INSERT INTO ... STR_TO_DATE($data) ... "`. – riv Jul 29 '15 at 14:29
  • @MarcB How can I see the result of var_dump? riv look better, orelavorateore_3_07_2015=25! It's the fourth parameter! – user123456 Jul 29 '15 at 14:37
  • 1
    It is also the last parameter, so you have it in there twice, with the second occurence overwriting the first one... The `var_dump` will be returned as the result of your ajax query, as an argument of the `success` function, so you can simply `console.log` it. Or you can make the php script log it to file. – riv Jul 29 '15 at 14:50
  • Can you check if it's the same issue as here: http://stackoverflow.com/questions/31513934/php-not-receiving-data-from-xmlhttprequest/31514017#31514017 ? If it is the same, the answer is phenomenally simple. – nealio82 Jul 29 '15 at 14:53
  • @Nealio: don't think so, he needs the post data as an associative array, not as a raw string. – riv Jul 29 '15 at 14:57
  • @riv: i thought the issue was that the data wasn't available / visible in PHP, which using file_get_contents('php://input') would solve. You can unserialise to get your object/array in php once you can see it :) – nealio82 Jul 29 '15 at 15:56
  • @riv That was the issue! When I created the form I duplicated the textbox orelavorateore_3_07_2015 and I forgot to change its name, so in $_POST there was two same index! This is so embarassing! ;) Thank you so much! – user123456 Jul 30 '15 at 07:11

1 Answers1

0

You can use this snippet to convert your form data into JSON format :

$.fn.serializeObject = function()
    {
       var o = {};
       var a = this.serializeArray();
       $.each(a, function() {
           if (o[this.name]) {
               if (!o[this.name].push) {
                   o[this.name] = [o[this.name]];
               }
               o[this.name].push(this.value || '');
           } else {
               o[this.name] = this.value || '';
           }
       });
       return o;
    };

    $("form").submit(function( event ) {

        event.preventDefault();

        //convert form data to JSON
        var params = $(this).serializeObject();
        //add a 'data_r' field with some data to our JSON
        params.data_r = 'sample data';

        $.ajax({
            url: 'app.php',
            type: 'POST',
            data: JSON.stringify(params),
        })
        .done(function(data) {
            console.log(data);
        });
    });

and on the PHP side :

<?php 

    $data = json_decode(file_get_contents('php://input'), false);

    print_r($data->data_r);


 ?>

Now $data is an object and you can access to a specific field :

$data->data_r
Paul Boutes
  • 3,285
  • 2
  • 19
  • 22