MKUltra
MKUltra

Reputation: 374

Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn!

I'm using AJAX in javascript to send a JSON string to PHP.

I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.

I have a html file with a username field, password field, and login button.

Then I have a javascript file that takes the username pass and sends it to a php file.

I know the php file is being accessed because I am seeing the test echo in console.

I just cant figure out how to access the data I'm sending to the php.

script.

function attemptLogin(){

var inputUserName = JSON.stringify(document.getElementById("userName").value);


var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){

    var DONE = 4;
    var OK = 200;

    if (ajaxData.readyState === DONE) {
        if (ajaxData.status === OK) {
            console.log(ajaxData.responseText);
        }else{
            console.log("ERROR : " + ajaxData.status);
        }
    }
};
ajaxData.send(inputUserName);
}

ajax.php

<?php
    echo"TestInPHP";
?>

For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.


Here is an edit for the working code thanks to SuperKevin in the comments below. This code will take the string in the username and password fields in HTML by the JS, send it to PHP and then sent back to the JS to output to the browser console window.

index.html

<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>

script.js

function attemptLogin(){

var inputUserName = 
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);

var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;


var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){

    var DONE = 4;
    var OK = 200;

    if (ajaxData.readyState === DONE) {
        if (ajaxData.status === OK) {
            console.log(ajaxData.responseText);
        }else{
            console.log("ERROR : " + ajaxData.status);
        }
    }
};
ajaxData.send();
}

ajax.php

<?php
  echo $_GET['fname']; 
  echo $_GET['pass'];
?>

Upvotes: 3

Views: 175

Answers (3)

blackandorangecat
blackandorangecat

Reputation: 1344

If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.

With jQuery you can do something like this:

First Page:

$.ajax({
      url: 'sportsComparison.php',
      type: 'post',
      dataType: 'html',
      data: {
         BaseballNumber = 42,
         SoccerNumber = 10
      },
      success: function(data) {
        console.log(data);
      });

which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.

sportsComparison.php:

<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue =  $_POST["SoccerNumber"];

$TotalValue = $BaseballValue * $SoccerValue;

print "<span class='TotalValue'>".$TotalValue."</span>";

?>

This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.

Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.

Upvotes: 0

Kevin Pimentel
Kevin Pimentel

Reputation: 1916

Here's a simple example of how you would make a vanilla call.

This is our main file, call it index.php.

<script>

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "delete.php", true);
    xhttp.send();

</script>

Here's our server script. delete.php

<?php

echo "HELLO THERE"; 

Now, if you wanted to pass data to your script you can do the following:

xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();

To access this data you can use the global $_GET array in php. Which would look like this:

$fname = $_GET['fname']; 
$lname = $_GET['lname'];

Obviously, you have to sanitize the data, but that's the gist of it.

For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.

Upvotes: 2

Nico_
Nico_

Reputation: 1386

You can see all the data sent to your php with :

<?php
   print_r($_GET); //if it's send via the method GET
   print_r($_POST); //if it's send via the method POST
?>

So, in your case it will be something like :

<?php
  echo $_GET['username'];
?>

Upvotes: 0

Related Questions