0

I want to send the data ('ABCDEF','23','1234567890','abc@def.com' and the image 'profile.jpg'), into my phpscript, with the help of FETCH api.

My HTML:

<form id="details" class="form">

    Full name: <strong name="name_1">ABCDEF</strong><br><br>
    ID No:<strong name="org_number_1">23</strong><br><br>
    Mobile No:<strong name="ph_number_1">1234567890</strong><br><br>

    E-mail: <strong name="email_1">abc@def.com</strong><br><br>
    ID Card: <img src="profile.jpg" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>

    <button id="go" onclick="submit()"type="button" value="submit">Submit</button>

</form>

My javascript:

function submit(){

    var nme=document.getElementsByName("name_1")[0].innerHTML;
    var id=document.getElementsByName("org_number_1")[0].innerHTML;
    var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
    var email=document.getElementsByName("email_1")[0].innerHTML;
    var img=document.getElementsByName("image")[0].src;
    var dataString = {"name": nme, "email": email, "ID No": id, "Contact no": phone, "image": img};
    
    const dForm = document.getElementById('details');          
    dForm.addEventListener('submit', function(e) {
        e.preventDefault();
        fetch("database_registration.php",{
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(dataString), 
        }).then(function (response){
            return response.text();
        }).then(function (text){
            console.log(text);
        }).catch(function (error){
            console.error(error);
        })
    });
 
}

My php:

<?php
      $post_data = file_get_contents("php://input");
      $data = json_decode($post_data); 
      var_dump($data);         //shows NULL
?>

Why is my $data object NULL? How do I fetch those data?

EDIT: I have also followed this step

  • 1
    I suggest to take a look on CORS. https://enable-cors.org/index.html – I think you are missing the Allow-Origin Header. – m1crdy Jan 12 '21 at 13:40
  • Does it work if you submit the form normally (without AJAX)? – Olivier Jan 12 '21 at 14:07
  • @El_Vanja sorry for that typo. –  Jan 12 '21 at 14:37
  • @Olivier Yea, didn't work that time too. –  Jan 12 '21 at 14:37
  • @m1crdy tried it, doesn't work –  Jan 12 '21 at 14:49
  • You're probably not sending anything, since you're not sending it the correct way. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_your_own_request_object – Anuga Jan 19 '21 at 11:13

3 Answers3

2

Why not getting your post inputs one by one and defining them each in a variable?

$name = $_POST['name']
$id = $_POST['ID No']
$email = $_POST['email']
$phone = $_POST['ContactNo']
$img = $_POST['image']
Evara
  • 84
  • 2
  • 11
0

Apparently you try to contact an API on your localhost at port 5500:

127.0.0.1:5500

By default a lot of things are forbidden, you have to allow it. The server where the API is should have the CORS correctly set. You can either set them on your Apache or Nginx server, or in your app (for example NodeJS app).

djcaesar9114
  • 1,880
  • 1
  • 21
  • 41
0

The data won't be availabe in the super global variables ($_POST in this case) because it's not coming from a multipart-data form or an application/x-www-form-urlencoded. You should be able to see the data reading 'php//input':

<?php
     $post_data = file_get_contents("php://input")
     $data = json_decode($post_data); 
     var_dump($data); //You can't echo an object

MY REFACTOR

<form id="details" class="form">

        Full name: <strong name="name_1">ABCDEF</strong><br><br>
        ID No:<strong name="org_number_1">23</strong><br><br>
        Mobile No:<strong name="ph_number_1">1234567890</strong><br><br>
    
        E-mail: <strong name="email_1">abc@def.com</strong><br><br>
        ID Card: <img src="profile.png" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>
    
        <button id="go" type="submit">Submit</button>
    
    </form>
document.getElementById('details').addEventListener('submit', function(e) {
            e.preventDefault();
            submitData();
        });

function submidData() {
    var nme=document.getElementsByName("name_1")[0].innerHTML;
    var id=document.getElementsByName("org_number_1")[0].innerHTML;
    var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
    var email=document.getElementsByName("email_1")[0].innerHTML;
    var img=document.getElementsByName("image")[0].src;
    var dataString = {"name": nme, "email": email, "IDNo": id, "ContactNo": phone, "image": img};

    fetch("database_registration.php", {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: JSON.stringify(dataString)
        }).then(function (response){
            return response.text();
        }).then(function (text){
            console.log(text);
        }).catch(function (error){
            console.error(error);
        });
}

MY OUTPUT

object(stdClass)[1]
  public 'name' => string 'ABCDEF' (length=6)
  public 'email' => string 'abc@def.com' (length=11)
  public 'IDNo' => string '23' (length=2)
  public 'ContactNo' => string '1234567890' (length=10)
  public 'image' => string 'http://localhost/so-test/profile.png' (length=36)
Periplo
  • 424
  • 4
  • 10
  • it prints **NULL** –  Jan 15 '21 at 04:23
  • I was able to reproduce your code and test it after refactoring the HTML and JS part too, so I'm gonna share with you what I did to make it work. – Periplo Jan 15 '21 at 12:27
  • I keep getting `Failed to load resource: the server responded with a status of 405 (Method Not Allowed)`. How do I fix this? Please help me. –  Jan 15 '21 at 13:56
  • Well, that's brand new information. Sounds like your server doesn't allow he POST method, wich is pretty strange since it's really common. Please, share information about the server you're using and its configurations. – Periplo Jan 15 '21 at 14:42
  • Well, as far as I know, I do have `XAMPP` and `php 8.0.0` installed. And my code editor is **Visual Studio Code**. That's all I know of. –  Jan 15 '21 at 15:19
  • Try this headers: `headers: {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}` – Periplo Jan 15 '21 at 16:17