0

I am trying to pass some form data to a php page using JSON as shown below.

 var file = doc.output('blob');
                var fd = new FormData();     // To carry on your data  
                fd.append('mypdf',file);
                fd.append('x','<?php echo $_GET['x']?>');
               // alert('file');

                $.ajax({
                  url: 'week-distribute.php',   //here is also a problem, depends on your 
                  data: fd,           //backend language, it may looks like '/model/send.php'
                  dataType: 'text',
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  success: function (response) {
                    console.log('Success to send request');
                  },
                  error: function (jqXHR) {
                    console.log('Failure to send request');
                  }
                });

The problem I have is that I cannot figure out how to retrive the data from the JSON object. I have tried the following (along with many other attempts) but this does not seem to work. Does anyone know how I can tried both the values x and mypdf please?

$json_data = file_get_contents("php://input");

$data = json_decode($json_data, true);

$x = $data["x"]; //This does not work

$target_file = basename($_FILES["mypdf"]["name"]).uniqid().'.pdf'; //This does not work

This is how the form data is passed across in the headers:

mypdf: (binary) x: eyJ0eXAiOiJKV1QiLCJh

Matt
  • 3
  • 2
  • `$json_data = file_get_contents("php://input");` is incorrect in this case. It's better to use directly `$_POST['x']` – SpinyMan May 13 '20 at 09:27
  • Hi, unfortunately using $_POST['x'] still does not work. An error is displayed saying that the variable is undefined. – Matt May 13 '20 at 09:33
  • OK, then remove two params: `contentType: false` and `processData: false` – SpinyMan May 13 '20 at 09:40
  • Hi, I then get a JQuery error: Uncaught TypeError: Illegal invocation – Matt May 13 '20 at 09:43
  • Just have a look at this answer https://stackoverflow.com/a/10811427/9731538 I think you have a problem with ajax file upload. – SpinyMan May 13 '20 at 09:47
  • When you remove contentType: false only then it does not error but x appears to be blank. – Matt May 13 '20 at 09:50
  • Thanks for the link but I still can't get my head round it :-( – Matt May 13 '20 at 10:32

1 Answers1

0

Try this.

$json = file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo');

$data = json_decode($json,true);

$Geonames = $data['geonames'][0];

echo "<pre>";

print_r($Geonames);

exit;
jguyet
  • 75
  • 8