简体   繁体   中英

When I send a POST request from a JavaScript file to a PHP file in the same application, the PHP script always reads it as a GET request. Why?

I have a dynamic form on one of my web pages. The form stores data in the script file and updates it as the user adds more data from the form. This is the object that I create in JS:

const survey = {
   title: '',
   createdBy: '',
   description: '',
   openingMsg: '',
   thankyouMsg: '',
   questions: [],
}

The questions array holds Question objects. Here is the class:

class Question {
   constructor(id) {
      this.id = id
   }
   questionText = ''
   type = ''
   choices = new Map()
}

I add an event listener to the submit button like this:

const saveSurveyBtn = document.getElementById('saveSurvey')
surveyForm.addEventListener('submit', saveSurvey)

and the saveSurvey function looks like this:

function saveSurvey(e) {
    e.preventDefault()

    fetch('../../actions/save-survey.php', {
        method: 'POST',
        body: JSON.stringify(survey),
        headers: {
            "Content-type": "application/json;charset=UTF-8"
        }
    })
}

As you can see I'm trying to send the data to a local php script from JS. All is well until I get to the php script. The problem is this; regardless of the fact that in my fetch call I use method: POST , it always gets sent as a GET request. Why? How can I fix this?

OK, I can't tell you why my form data wasn't being posted and I have confirmed that it was being sent as a GET request. But this is how I solved this problem.

I added a hidden field in the form and changed the button of type "submit" to type "button". I then grabbed that button via JS and set a click listener on it. When the user presses the button I first assign my JSON serialized survey object to the hidden field. Then I manually submitted the form and it was sent via POST to the PHP script. The form's method was always "post" but that didn't seem to matter initially. I don't know why but here is my input in the form:

<input name="survey" id="survey" type="hidden" value="">

then I grab the button which looks like this:

<button type="button" class="btn btn-success" id="saveSurvey">Save Survey</button>

notice it's no longer of type "submit". I then add a click event listener to it and call this function when clicked:

function saveSurvey(e) {
    document.getElementById('survey').value = JSON.stringify(survey)
    surveyForm.submit()
}

This worked. I don't know if I fully answered my own question so if someone else comes along with a better answer I will adjust this post. Thank you everyone for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM