Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Javasript fetch doesnt work on PHP return when $.ajax works

I need to simply retrive data from server trought POST request. I can only edit front-end code. I found out that that jQuery function $.Ajax works and vanila javasript function fetch() doesn't. I figured it out that its due to PHP code doesn't echo message that i want to read but just returns it like this:

<?php 
    //some php logic
    return array(
        'result' => 'OK',
        'message' => 'data I shall receive',
    );
?>

Ajax request returns {result: 'OK', message: 'data I shall receive'} with following code:

this.sendFileToServer = async (file) =>{
    let data = new FormData()
    data.append('file', file);
    let uploadUrl = this.element.getAttribute('data-uploadurl');
    $.ajax({
        url: uploadUrl,
        body:data,
        success: function (msg){
            console.log(msg);
        }
    })
}

Javascript fetch request returns error 500 with following code:

this.sendFileToServer = async (file) =>{
    let data = new FormData()
    data.append('file', file);
    let uploadUrl = this.element.getAttribute('data-uploadurl');
    const response = await fetch(uploadUrl, {
        method: 'POST',
        body: data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(response => {
        console.log(response.text()); //I tried here return diffrent data like response.json(), but it doesn't work
    });
}

I know i could use Ajax function when it works, but i want my code to be jQuery free. I don't understand why the fetch function doesn't work when it should be the same request. Any help how to make it work or Explanation why i can't work would be nice.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!