Home > Software design >  How to pass data to PHP via AJAX POST
How to pass data to PHP via AJAX POST

Time:01-18

I'm trying to pass data via AJAX to a PHP file, but it's returning NULL.

Here's the AJAX code (with all 'val()' getting a value correctly [I've tested it]):

 $.ajax({
                            url: '../utilities/atualizar_ferias.php',
                            method: 'POST',
                            cache: false,
                            contentType: false,
                            processData: false,
                            data: {
                                data_inicio: inicio_target.val(),
                                data_fim: fim_target.val()
                            },
                            success: function(resultado){
                            console.log(resultado);
                            }
                        })

Here is the PHP code to receive the data:

<?php

$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);

var_dump($dados);

Does anyone have any idea why I'm getting NULL?

CodePudding user response:

Your PHP script isn't returning any sort of valid JSON. It's just doing a var_dump of the result of filter_input_array. According to the docs on that function, the return value is as follows:

Return Values

An array containing the values of the requested variables on success. If the input array designated by type is not populated, the function returns null if the FILTER_NULL_ON_FAILURE flag is not given, or false otherwise. For other failures, false is returned.

An array value will be false if the filter fails, or null if the variable is not set. Or if the flag FILTER_NULL_ON_FAILURE is used, it returns false if the variable is not set and null if the filter fails. If the add_empty parameter is false, no array element will be added for unset variables.

I suggest you inspect in your browser what is being returned as the response to your POST operation to the server. You should see that it is the output of the PHP var_dump function which is not valid JSON, so your JS won't parse it.

You may also need to set options on your AJAX request to specify what sort of result you expect: text, json, etc.

  • Related