0

So I have a form, I took the contents of its inputs, threw them into an array, had it made into a JSON and then sent it to PHP so it can in turn decode and enter it into a database. I know it'd be easier to just use a <form method="POST" action="phpfile.php"> but I can't have this redirecting to another page, especially since my PHP is not embedded into HTML, instead it handles things offsite. Otherwise it'd be simpler to just use $_POST["name"] to get what I need. Nonetheless, this page in particular is supposed to create the user, receive a server response, that the user has been entered into the database and then is given an alert with a button to be redirected to the main page.

So anyway here are the relevant sections of this whole process.

JavaScript:

window.onload = function findSubmitButton() {
    var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);
}

    function serverInteraction() {
      var xmlhttp;
      var inputArray;
      var finalArray = [];
      var JSONArray;
      if (window.XMLHttpRequest){
          xmlhttp = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } else {
          throw new Error("Your browser is not compatible with XMLHTTP");
          return false;
      }
      inputArray = document.querySelectorAll("input[type=text]");
      for(var i = 0; i < inputArray.length; i++){
          finalArray[i] = inputArray[i].value;
      }
        console.log(finalArray);
        JSONArray = JSON.stringify({finalArray: finalArray}); 
        console.log(JSONArray);
        xmlhttp.open("POST","phpFiles/sendUserInfo.php", true);
        xmlhttp.setRequestHeader("Content-type","application/json");
        xmlhttp.send(JSONArray);

    }

PHP:

<?php
    $finalArray = json_decode($_POST['finalArray']);
    var_dump($finalArray);
?>

That var_dump simply returns a null and using echo gives me nothing, except a warning that my array variable isn't initialized through XDebug. I'm not quite sure what I'm doing wrong here, I've been following this just like the tutorials tell you to do it, and isn't generating the array. I've also tried $_POST['JSONArray']without any luck in case that was how it was supposed to go. Also tried file_get_contents('php://input') which sends an empty string as well.

Argus
  • 911
  • 3
  • 9
  • 20
  • If I were you I would start by checking what is being sent through the entire POST array. `var_dump($_POST);`, see what's there. Also you're missing a ; after inputArray = document.querySelectorAll("input[type=text]") – Digits Mar 30 '15 at 00:23
  • possible duplicate of [Javascript : Send JSON Object with Ajax?](http://stackoverflow.com/questions/6418220/javascript-send-json-object-with-ajax) – Ken Y-N Mar 30 '15 at 00:25
  • Yeah, I did that, and nothing, all I get is an empty array. – Argus Mar 30 '15 at 00:51

2 Answers2

0

You are bypassing $_POST by sending the the data as "Content-type","application/json" .

The data will instead be set in the body of request and can be retrieved using file_get_contents("php://input")

For further discussion see file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

Generally there is no need to send your data as json to php

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • So if I don't send it through JSON what do I do, just send the array as is? Will it get there unharmed? I just used it because I thought passing it from one place to another would cause trouble. – Argus Mar 30 '15 at 00:48
0

You can't get your data from $_POST if you put JSON in your post body. see this question Receive JSON POST with PHP. php can't handle application/json properly.

For your var_dump is empty, try this

var_dump(file_get_contents('php://input'));
var_dump(json_decode(file_get_contents('php://input'), true));

you will see your data.

And if you send your data without change it to JSON, you will get wrong data.

eg: your finalArray is ['a','b','c'] and you send it directly.

var_dump(file_get_contents('php://input'));

you will see php got string a,b,c instead of ['a','b','c']

So if you want to use $_POST to receive data, you need to use application/x-www-form-urlencoded. you can use jquery to do it. see http://api.jquery.com/jquery.ajax/

 $.ajax({
    method: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" }
   })
   .done(function( msg ) {
      alert( "Data Saved: " + msg );
   });

it will serialize your js object into x-www-form-urlencoded and php will handle it properly.

use chrome's dev tools, switch to network and see the request payload and response would be helpful for you.

Community
  • 1
  • 1
at15
  • 139
  • 6
  • Thanks for the answer, but I already found out what was going on, since this is asynchronous its of no use to open up the PHP page manually and expect the information to get there out of the blue. I know that using JQuery shortens and simplifies things, but I can't use it, I just began with JavaScript, and using the simple method at first doesn't feel like a good idea to me. Regardless, this seems like the solution to my problem so I will mark this. – Argus Mar 31 '15 at 06:05