0

I've been trying to create a simple grade calculator app with ajax functionality. The ajax seems to be working quite nicely, however the separate PHP file I've created 'response.php' is not GET-ting the data from the form. So it is just echoing out 'Uh oh'.

I'm not sure what I'm doing wrong here and I've been going over my code for a while. Can anyone help?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Grade Calculator</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <script>

            var xhr = new XMLHttpRequest();
            xhr.open("GET","response.php");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    document.getElementById('ajax').innerHTML = xhr.responseText;
                } 
            };
            function sendAjax() {
                xhr.send();
                document.getElementById('gradeForm').style.display = 'none';
            }

    </script>


  </head>

  <body>

    <!-- <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div>
      </div>
    </div> -->

    <div class="container">

      <div class="starter-template">
        <h1>Bootstrap starter template</h1><br>

        <form action="index.php" method="get" id="gradeForm">
            <div class="form-group">
                <label for="currentGrade">What is your current Grade</label>
                <input type="text" name="currentGrade"><br>
            </div>
            <div class="form-group">
                <label for="targetGrade">What is your target Grade</label>
                <input type="text" name="targetGrade"><br>
            </div>
            <div class="form-group">
                <label for="finalWorth">What is your final worth?</label>
                <input type="text" name="finalWorth"><br>
            </div>
            <button type="button" class="btn btn-default" onclick="sendAjax()">Submit</button>
        </form>

        <div id="ajax">

        </div>

      </div>

    </div><!-- /.container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <!-- Latest compiled and minified JavaScript -->
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

  </body>
</html>

response.php

<?php 

        $currentGrade = $_GET['currentGrade'];
        $targetGrade = $_GET['targetGrade'];
        $finalWorth = $_GET['finalWorth'];

        if (isset($currentGrade, $targetGrade, $finalWorth)) {
            echo $currentGrade;
            echo $targetGrade;
            echo $finalWorth;
        } else {
            echo 'Uh oh!';
        }

        // if (empty($currentGrade, $targetGrade, $finalWorth)) {
        //     echo 'Nothing...';
        // } else {

        //     $neededMark = $currentGrade - $targetGrade;
        //     $neededMark = $neededMark / $finalWorth;
        //      $neededMark = $neededMark * 100;
        //      $neededMark = round($neededMark);



?>
chap
  • 1,860
  • 5
  • 24
  • 39
  • Is it an external PHP file? Looks like you are requesting it on the same server. – putvande Jul 08 '14 at 11:16
  • 1
    as I said in the version of this question you posted earlier, you are not sending any parameters in your ajax call and response.php is probably throwing an error because the variables you are trying to read do not exist. If you were to manually assign the url in the ajax query as 'response.php?currentGrade=X&targetGrade=Y&finalWorth=none' you might get an answer from the server. – Professor Abronsius Jul 08 '14 at 11:19

3 Answers3

2

The reason response.php is unable to get the data from the form is that your AJAX isn't sending the data from the form. Unlike a form submit, AJAX won't automatically send the form - you need to set the parameters explicitly.

Prisoner
  • 49,922
  • 7
  • 53
  • 105
2

As far as I am aware you can't retrieve the data because, using the verb (GET) for your call, requires a querystring appended to the target url, this way:

xhr.open("GET","response.php?key1=value1&key2=value2...etc..."); 

However In my opinion would be better to use the POST verb:

xhr.open("POST","response.php", true);

then set a valid request header like:

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

collect the params (your new sendAjax function):

function sendAjax() {

    var values = [];
    var form = document.getElementById("gradeForm");

    for (var i = 0, l = form.length; i < l; i++) 
    {
        if(form[i].type === "text")
        {
            values.push(form[i].name +"="+ form[i].value);
        }
    };

    var params = values.join("&"); 

    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.send(params);

    document.getElementById('gradeForm').style.display = 'none';
}

Now you can retrieve the data in the response.php page, via the superglobal $_POST

ilpaijin
  • 3,645
  • 2
  • 23
  • 26
0

This is how you do ajax request, without jQuery. You can re-purpose this for your own need.

I made this work as single page script:

test.php

<?php

// Handle GET Ajax Request
if (count($_GET))
{
    print_r($_GET);
    exit();
}

?>

<script type="text/javascript">

// helper function - http://stackoverflow.com/a/8567149/2332336
function loadXMLDoc(targetUrl, resultDiv) {
    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");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               document.getElementById(resultDiv).innerHTML = xmlhttp.responseText;
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }
    xmlhttp.open("GET", targetUrl, true);
    xmlhttp.send();
}

// usage
loadXMLDoc('test.php?a=1&b=2', 'result');

</script>

<div id="result"></div>
Latheesan
  • 23,247
  • 32
  • 107
  • 201