2

I'm newbie on this webdeveloper matters. I have already made a form where i've used Ajax (JQuery lib) to create a chat box.

Now, i wanna try to do something similar without using Jquery to understand how Ajax works. First i just want to write my messages on log.html using AJAX, so then i can read them later. But i dont understand why i can't send my textarea data into post.php.

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Teste</title>

        <script type="text/javascript">

    function sendXMLDoc(){

         var xmlhttp;

        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari           
            xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5       
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }


        var message=document.getElementById('msg').value;

        xmlhttp.open("POST", "post.php", false);

         xmlhttp.onreadystatechange = function() {//Call a function when the state changes.

            if(xmlhttp.readyState == 0 ) {
                    alert("UNSENT");
            }
            if(xmlhttp.readyState == 1 ) {
                    alert("OPENED");//check if the data was revived successfully.
            }
            if(xmlhttp.readyState == 2 ) {
                    alert("Headers Received");//check if the data was revived successfully.
            }
            if(xmlhttp.readyState == 3 ) {
                    alert("Loading response entity body");//check if the data was revived successfully.
            }

            if(xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {
                    alert("Data transfer completed");//check if the data was revived successfully.

                    }
            }
        }

        xmlhttp.send(message);        
   }

   </script>

xmlhttp.send(data) : Why im not sending my data to post.php?

Post.php is where i write my log.html (but i cant send my messages and i dont understand why):

<?php

    $text = $_POST['message'];  // WHY I CAN'T RECEIVE MY POSTED MESSAGE?
    $fp = fopen("log.html", 'a');
    fwrite($fp, "<div>\n(".date("g:i A").")<br>".$text."<br>\n</div>\n");
    fclose($fp);

?>

And this is my form.html

<body>
    <h1>Insert text on log.html</h1>

    <form method="post" onsubmit="sendXMLDoc();">       
    <textarea name="message" maxlength="196" rows="8" ></textarea>
    <br>
    <input type="submit" value="Send"/> 
    </form>



</body>
1
  • try adding request header like xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") Commented Dec 9, 2016 at 19:30

1 Answer 1

3

have you taken a look at this link ?

It seems to have a complete explanation on how to build an AJAX request with PHP and MySql.

EDIT:

The problem in your code is both on your post.php, which has incorrect syntax (lacking double quotes before the last <br>), and should be something like :

post.php

<?php 
    $text = $_POST['message'];  
    $fp = fopen("log.html", 'a');
    fwrite($fp, "<div>\n(".date("g:i A").")<br>".stripslashes(htmlspecialchars($text))."<br>\n</div>\n");
    fclose($fp);

?>

and with the request header, which should have the content-type set (see code below)

I based this answer on w3.org.

The final html here presented shall help you understand how Ajax requests behave on different browsers. Try it out.

It seems though that for Firefox to load the request, you need to do something when the Status is OPENED (1), and I don't quite understand why.

Try this code on different browsers to see the different approaches to XMLHttpRequest.

<!DOCTYPE html>
<html>

<head>
<script language="javascript" type="text/javascript">



function sendXMLDoc(obj){


        var message=obj["message"].value;
        var data = "message=" + message; 
        var xmlhttp;
        try{
           // Opera 8.0+, Firefox, Safari
           xmlhttp = new XMLHttpRequest();
         }catch (e){
           // Internet Explorer Browsers
           try{
              xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
           }catch (e) {
              try{
                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
              }catch (e){
                 // Something went wrong
                 alert("Your browser broke!");
                 return false;
              }
           }
         }       

        url = "http://localhost/AjaxPhp/post.php"

        xmlhttp.open("POST", url , true);
        xmlhttp.onreadystatechange = display_data;
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  

        xmlhttp.send(data);

        function display_data() {

            if(xmlhttp.readyState == 1 ) {
                    alert("OPENED");//check if the data was revived successfully.
            }
            if(xmlhttp.readyState == 2 ) {
                    alert("Headers Received");//check if the data was revived successfully.
            }
            if(xmlhttp.readyState == 3 ) {
                    alert("Loading response entity body");//check if the data was revived successfully.
            }

            if(xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {
                    alert("Data transfer completed");//check if the data was revived successfully.
                    }
            }
        }
 } 


</script>
</head>

<body>
    <h1>Insert text on log.html</h1>

    <form method="post" onsubmit="sendXMLDoc(this);">       
    <textarea name="message" maxlength="196" rows="8" ></textarea>
    <br>
    <input type="submit"/> 
    </form>


</body>
</html>

I don't truly understand the whys, but according to w3, the order of the requests should, in my understanding, be :

OPENED (after invoking the open method), HEADERS_RECEIVED (after setRequestHeader), LOADING (request body received). DONE (Data transfer completed, after send) .

Chrome handles the post.php but doesn't present any alert box (maybe its my popup settings, maybe not)

IE shows only the OPENED alert message Firefox goes "Headers Received", "Data transfer completed","OPENED", "Data transfer completed".

Hope this helps understanding it a little bit more. Always go check w3.org for the ultimate source on the web. It might not be very user-friendly and intuitive, but provides some tips on the whys and the shoulds.

Sign up to request clarification or add additional context in comments.

7 Comments

No. First of all, thanks for your reply. It is a very intresting site and i believe that will help me in future scripts, i've read similar sites before i post this question but even so i still dont understand what is wrong, because i belive that my script is nearly correct.
I've edited my answer, and with these changes the code should be working on different browsers. Cheers
I've noticed now that my script works with IE, like you refere.. but with firefox and chrome doesn't. I think you find the big question Why this method doesn't work with other browsers.
It does work, if you include if(xmlhttp.readyState == 1 ) { alert("OPENED");//check if the data was revived successfully. } as i mentioned in my final answer. Try it out.
If this answer helped you, please vote it up and/or accept it as the right answer for your question, since your problem is now solved.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.