0

I have used JavaScript to turn data from a file into an array. I now want to use the input from a form to search through this array using PHP and display the results in a table. I have read through many posts that have solutions to something similar but I am unsure how to proceed.

I have updated my code using the suggestion posted by @Kevin_Kinsey

I am using ajax with POST to pass the array to PHP like this

function sendPhp(reports) {
$.ajax({
    type: 'POST',
    url: 'reports.php',
    data: JSON.stringify(reports),
    contentType: 'application/json',
    dataType: 'json'        
});
}

Then I am using this to receive it in PHP

<?php
$json = filter_input(INPUT_POST, "data", FILTER_SANITIZE_EMAIL);
//replace FILTER_DEFAULT with appropriate filter flags, as tight as possible

$dataObject = json_decode($json);
$dataArray = json_decode($json, true);
var_dump($json);
?>

my page is now displaying NULL in the browser and viewing the get request in the console shows no data being received.

Can someone point out my mistake please? I do not understand why the data is not being passed.

This image shows the console log my POST which shows my array

ajax post

This image shows the console log of the GET on my PHP page which is empty.

get on php

pedaars
  • 151
  • 1
  • 12

1 Answers1

0
<?php
    # get the data from POST, not stdin
    $json = filter_input(INPUT_POST, "data", FILTER_DEFAULT);
    //replace FILTER_DEFAULT with appropriate filter flags, as tight as possible

    $dataObject = json_decode($json);
    $dataArray = json_decode($json, true);

Note that there is NO security in place here, apart from whatever FILTER_FLAGS you can set to attempt to sanitize the input. You need token-based verification for protection against XSS, and should thoroughly test for unexpected input inside the JSON before acting upon it with the remainder of your PHP script/handler, and probably a lot more paranoia about security in general.

Kevin_Kinsey
  • 2,285
  • 1
  • 22
  • 23
  • I have tried this but i am still not receiving it on the php page – pedaars May 03 '17 at 09:46
  • What's the name of the variable? Show this in PHP with "print_r($_POST);" ... it appears to me that you're calling it "data" in the AJAX call and expecting it to be called "json" when it's POSTed to PHP. Follow the transaction in your debugger (whatever "Inspect Element" gives you in a browser) and see what's really happening. – Kevin_Kinsey May 03 '17 at 13:39
  • if i use "print_r($_POST);" the php page will display Array ( ) does this mean it is receiving an empty array as if i do {var_dump($_POST); it displays array(0) { } ? – pedaars May 03 '17 at 17:29
  • Yes, empty POST array. Check your debugger, especially the console and network tabs. – Kevin_Kinsey May 03 '17 at 20:26
  • Well I don't have a clue why it isn't working I know it will end up being something small out of place it always is – pedaars May 04 '17 at 09:53