Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass data to PHP via AJAX POST

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php

$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);

var_dump($dados);

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading