0

Trying to get PHP to return the value of a button. Not sure what's went wrong but it's returning these errors:

"Notice: Undefined index: data in /storage/ssd4/271/3416271/public_html/ajaxTest.php on line 2 Notice: Undefined index: data in /storage/ssd4/271/3416271/public_html/ajaxTest.php on line 5"

When I print_r($get) it returns an empty array. The HTML code looks fine so I imagine I messed up the AJAX?

(thank you in advance for any help given!)

Here's my HTML, js and PHP for reference:

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="ajaxTest.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>AJAX test</title>
</head>
<body>

<div id="area">
    <h2>Sending Data to the Server</h2>
    <form action="" method="GET">
        <button type="submit" name="data" value="1" onclick="getData('ajaxTest.php', 'moreText')">1</button>
        <button type="submit" name="data" value="2" onclick="getData('ajaxTest.php', 'moreText')">2</button>
    </form>
    <br />
    <p id="moreText">The fetched message should appear here.</p>
</div>    
</body>    
</html>




var XMLHttpRequestObject = false;

if(window.XMLHttpRequest) {

    XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
    XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(dataSource, divID) {

    if(XMLHttpRequestObject){
        var obj = document.getElementById(divID);
        XMLHttpRequestObject.open("GET", dataSource);

        XMLHttpRequestObject.onreadystatechange = function() {
        if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
            obj.innerHTML = XMLHttpRequestObject.responseText;
        }
      }

      XMLHttpRequestObject.send();
    }
}




 <?php
 if ($_GET["data"] == "1") {
 echo 'The server got a value of 1';
 }
 if ($_GET["data"] == "2") {
 echo 'The server got a value of 2';
 }
?>
8
  • Well for starters you have 2 submit buttons in a single form and you're not preventing the default action on form submit. Secondly, you're not doing any proper error handling. Add alerts or console logs to your functions so you can see if they actually trigger and if they contain the data you expect to be in there. It's pretty hard to find a problem if you don't track it down step by step. Commented Oct 28, 2017 at 4:10
  • Anyway, is there any reason why you're not using jQuery for this? It would make it a whole lot easier Commented Oct 28, 2017 at 4:25
  • I did add alerts and messed around with the code earlier but I didn't see the point in posting that in my code on here Commented Oct 28, 2017 at 4:33
  • jQuery would be easier... not my comfort zone though. I'll stick to javascript till I fix my problem, thanks Commented Oct 28, 2017 at 4:34
  • Of course you should add that. Anything you've tried yourself should be included in your question so we dont come up with answers that you've already tried yourself. Saves both us and you time :) Commented Oct 28, 2017 at 4:35

3 Answers 3

1

Alright, after rewriting, this would be the proper way to do it:

<!DOCTYPE HTML>
<html lang='en'>
    <head>
        <meta charset='UTF-8'>

        <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="style.css" />

        <!-- JS -->
        <script type="text/javascript" src="ajaxTest.js"></script>
        <script type="text/javascript">

        function getData(dataSource, divID, data){

            var xhr = new XMLHttpRequest();
                data = encodeURIComponent(data);
                ele = document.getElementById(divID);

            xhr.open('GET', dataSource + '?data=' + data, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    alert('PHP Returned: ' + xhr.responseText);
                    ele.innerHTML = xhr.responseText;
                }
                else if (xhr.status !== 200) {
                    alert('Request failed.  Returned status of ' + xhr.status);
                }
            };
            xhr.send(null);
        }
        </script>

        <title>AJAX test</title>
    </head>
    <body>
        <div id='area'>
            <h2>Sending Data to the Server</h2>

            <button type="button" value="1" onclick="getData('ajaxTest.php', 'moreText', this.value)">1</button>
            <button type="button" value="2" onclick="getData('ajaxTest.php', 'moreText', this.value)">2</button>

            <p id="moreText">The fetched message should appear here.</p>
        </div>
    </body>
</html>

I've removed the form because all you're doing is clicking buttons. You're not submitting a form at all. That way you don't have to prevent the default form action either.

I've also changed your PHP slightly so it returns what it's getting and not just guessing for it:

<?php

if(!empty($_GET['data'])){
    echo 'The server got a value of: '. $_GET['data'];
}

?>

I've tested the code myself and it's working fine of course.

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

1 Comment

Forgot to add the part where the text appears in the <p> element. Fixed it.
1

I understand you are trying to learn to code, so I am not going to critique the sanity of your code.

Here's what you are missing:

You are not including the GET prams in the URL. You are suppose to add the params at the end of the URL like this:

ajaxTest.php?data=1

That's the reason you are getting undefined index.

5 Comments

Sorry, but that on its own won't fix the issue. If he doesn't prevent the default action, his Ajax function will trigger, but his browser will also send him towards the form handler as if the Ajax function was never there.
Agreed, but did not want to complicate matters for him.
Yeah, I'm sorry my code is a terrible mess haha thanks for holding back ;) Thanks so much, yeah that fixed it! EDIT* sorry, false alarm was using testing on the wrong code there
You don't have to be an ass but I think you shouldn't hold back either. Especially those new to coding need to learn how to do it properly straight from the start. Otherwise they keep on doing it wrong and your "kindness" isn't actually helping them :) Just my opinion
Tbh I'm not new to coding a lot of this was just rushed or pasted from somewhere, however I am new to html, php and ajax
0
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="ajaxTest.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>AJAX test</title>
</head>
<body>

<div id="area">
    <h2>Sending Data to the Server</h2>
    <form action="" method="GET">
        <button type="button" name="data" value="1" onclick="getData(this.value,'ajaxTest.php', 'moreText')">1</button>
        <button type="button" name="data" value="2" onclick="getData(this.value,'ajaxTest.php', 'moreText')">2</button>
    </form>
    <br />
    <p id="moreText">The fetched message should appear here.</p>
</div>    
</body>    
</html>


<script>

var XMLHttpRequestObject = false;

if(window.XMLHttpRequest) {

    XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
    XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(value,dataSource, divID) {

    if(XMLHttpRequestObject){
        var obj = document.getElementById(divID);
        XMLHttpRequestObject.open("GET", dataSource+"?data="+value,false);

        XMLHttpRequestObject.onreadystatechange = function() {
        if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
            obj.innerHTML = XMLHttpRequestObject.responseText;
        }
      }

      XMLHttpRequestObject.send();
    }
}
</script>
  1. Change the button type submit to button.
  2. Pass the value to ajax page.

Try this, I think it may works to you.

Comments

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.