Jump to content

AJAX : Why did not my xhr object send string variable to php page as $_POST variable?


eaglehopes
Go to solution Solved by eaglehopes,

Recommended Posts

I am trying to learn AJAX and I found page  https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send where, it says that I can send string variable by using POST method of xmlhttprequest object.

I used this code by using AJAX xmlhttprequest(xhr) object to get a content into the "div" element whose id is "contentDiv" by using onclick event of a button ;

<button type="button" id="buttonT1" onclick="getContent()">Get content</button>
<div id="contentDiv" ></div>
<script>
async function loadPage(url,elementIdToInsert,postVariables) {
    var xhttp = new XMLHttpRequest();
  	xhttp.onreadystatechange = function() {
    switch(this.readyState ) {
      case 4 :
      if(this.status == 200) {
        document.getElementById(elementIdToInsert).innerHTML = this.responseText; // this here refers to xhttp object
        console.log("ok");
      } else { console.log("not ok! : "+this.status ); }
      break;
    } 
  };  // end of onreadystatechange 
  xhttp.open("POST", url, true); // open the file
  // DEBUG console.log( postVariables );
  xhttp.send( postVariables );  
}

function getContent() {
	loadPage("./path/to/phpfile/scripts.php","contentDiv","foo=bar");
}
</script>

And in my scripts.php file I checked it :

<?php 
  echo "sended foo variable has value of ".$_POST['foo'];
?>

However, I got this output :

sended is

so it is blank! I checked it with isset() and !empty() functions of php and result is that ; it is set, not empty but no data in it? 

Why did not work my "POST" method code? Thanks.

Link to comment
Share on other sites

  • Solution
45 minutes ago, requinix said:

First thing you need to do is stop using XMLHttpRequest and switch to fetch.

Thanks requinix for suggestion, but I read lots of comparisons between fetch vs. XMLHttpRequest pages, such as  https://blog.openreplay.com/ajax-battle-xmlhttprequest-vs-the-fetch-api. Implementing "timeout" and "readyState " and some other features that are "not easy" in fecth.  XMLHttpRequest suits better for my purposes and easier(while loading... etc.) to handle.

 found another page after your link requinix, about POST data using form data : https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects in my search.

 Then, I added fastly a hidden form into my html code and send formdata object and worked. My code to solve problem was : 

<form name="hiddenForm"></form>
<button type="button" id="buttonT1" onclick="getContent()">Get content</button>
<div id="contentDiv" ></div>
<script>
async function loadPage(url,elementIdToInsert,postVarName, postVarValue) {
    var xhttp = new XMLHttpRequest();
  	xhttp.onreadystatechange = function() {
    switch(this.readyState ) {
      case 4 :
      if(this.status == 200) {
        document.getElementById(elementIdToInsert).innerHTML = this.responseText; // this here refers to xhttp object
        console.log("ok");
      } else { console.log("not ok! : "+this.status ); }
      break;
    } 
  };  // end of onreadystatechange 
  xhttp.open("POST", url, true); // open the file
  let formData = new FormData(document.forms.hiddenForm);
  formData.append(postVarName,postVarValue);
  xhttp.send( formData );  
}

function getContent() {
	loadPage("./path/to/phpfile/scripts.php","contentDiv","foo","bar");
}
</script>

and send data correctly to php script and I got it from $_POST['foo'].

Thanks.

 

Link to comment
Share on other sites

5 minutes ago, eaglehopes said:

Thanks requinix for suggestion, but I read lots of comparisons between fetch vs. XMLHttpRequest pages, such as  https://blog.openreplay.com/ajax-battle-xmlhttprequest-vs-the-fetch-api. Implementing "timeout" and "readyState " and some other features that are "not easy" in fecth.  XMLHttpRequest suits better for my purposes and easier(while loading... etc.) to handle.

 found another page after your link requinix, about POST data using form data : https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects in my search.

 Then, I added fastly a hidden form into my html code and send formdata object and worked. My code to solve problem was : 

<form name="hiddenForm"></form>
<button type="button" id="buttonT1" onclick="getContent()">Get content</button>
<div id="contentDiv" ></div>
<script>
async function loadPage(url,elementIdToInsert,postVarName, postVarValue) {
    var xhttp = new XMLHttpRequest();
  	xhttp.onreadystatechange = function() {
    switch(this.readyState ) {
      case 4 :
      if(this.status == 200) {
        document.getElementById(elementIdToInsert).innerHTML = this.responseText; // this here refers to xhttp object
        console.log("ok");
      } else { console.log("not ok! : "+this.status ); }
      break;
    } 
  };  // end of onreadystatechange 
  xhttp.open("POST", url, true); // open the file
  let formData = new FormData(document.forms.hiddenForm);
  formData.append(postVarName,postVarValue);
  xhttp.send( formData );  
}

function getContent() {
	loadPage("./path/to/phpfile/scripts.php","contentDiv","foo","bar");
}
</script>

and send data correctly to php script and I got it from $_POST['foo'].

Thanks.

 

Totally disagree as FETCH is very easy to implement and is very elegant in my opinion - However, every coder has a different style. 😉

    /* Handle General Errors in Fetch */
    const handleErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };

/* Success function utilizing FETCH */
    const quizUISuccess = (parsedData) => {
        console.log('trivia data', parsedData);
        mainGame.style.display = 'grid';
        d.getElementById('content').scrollIntoView();

        //gameData = parsedData;


        gameData = parsedData.sort(() => Math.random() - .5); // randomize questions:
        totalQuestions = parseInt(gameData.length);
        createQuiz(gameData[gameIndex]);

    };

    /* If Database Table fails to load then answer a few hard coded Q&A */
    const quizUIError = (error) => {
        /*
         * If game database table fails to load then give a few questions
         * and answers, so that the game will still work properly.
         */
        failed = true;
        mainGame.style.display = 'grid';
        d.getElementById('content').scrollIntoView();
        console.log("Database Table did not load", error);
        gameData = [{
            "id": 1,
            "user_id": 1,
            "hidden": "no",
            "question": "[Blank] is the length of time when the film or digital sensor inside the camera is exposed to light, also when a camera's shutter is open when taking a photograph. The amount of light that reaches the film or image sensor is proportional to the [Blank].",
            "category": "photography",
            "answers": [
                "Shutter Speed or Exposure Time",
                "ISO",
                "",
                ""
            ]
        },
            {
                "id": 2,
                "user_id": 1,
                "hidden": "no",
                "question": "[Blank] was one of the earliest photographers in American history, best known for his scenes of the Civil War. He studied under inventor Samuel F. B. Morse, who pioneered the daguerreotype technique in America. [Blank] opened his own studio in New York in 1844, and photographed Andrew Jackson, John Quincy Adams, and Abraham Lincoln, among other public figures.",
                "category": "photography",
                "answers": [
                    "Robert Capa",
                    "Steve McCurry",
                    "Ansel Adams",
                    "Matthew Brady"
                ]
            }
        ]
        totalQuestions = gameData.length;
        //console.log(gameData[gameIndex]);
        createQuiz(gameData[gameIndex]);
    };

    /* create FETCH request */
    const createRequest = (url, succeed, fail) => {
        fetch(url)
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

 

Link to comment
Share on other sites

5 hours ago, Strider64 said:

Totally disagree as FETCH is very easy to implement and is very elegant in my opinion - However, every coder has a different style. 😉

My statement was : " Implementing "timeout" and "readyState " and some other features that are "not easy" in fecth." because they are missing. So, "some implementations" are not easy(not just according to me, but according to others, please see the link I have sent above) due to they are missing and need extra time to add and prone to errors for beginners like me. :)

Therefore, I think, I am misunderstood; since "totally" word catches my attention which is not so correct ! By the way your code is highly elegant , thanks for sharing with us :D.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.