Hey folks, I made a video tutorial on how to submit data from one file to another, and evaluate the returned data. This can be used for checking user logins (with proper encryption), sending/retrieving data to a database or file, and be really helpful with creating a beautiful website with limited page refreshes/loads! :)
I hope this helps some of you understand AJAX/jQuery a little bit better!
Let's go over the code...
index.php (the file sending data from user input)
data.php (the file receiving data & evaluating it)
style.css - make it look nice :)
I hope this helps some of you understand AJAX/jQuery a little bit better!
Let's go over the code...
index.php (the file sending data from user input)
Code
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="box">
<input type="text" name="user-input" id="user-input" class="input-box" /> <br />
<a id="submit-button" class="submit-button" href="#">Submit</a>
</div>
</body>
[b]<!--[/b] https://code.jquery.com -->
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$("#submit-button").on("click", function(e){
e.preventDefault() // don't let href='#' do anything
var value = $("#user-input").val() // get the value from input box
$.ajax({
url: "data.php", // file to send to
method: "GET", // GET or POST
dataType: "text", // expected data type returned from data.php
data: { // data being sent
val:value // send our value as $_GET['val'] or $_POST['val']
}
}).done(function(returneddata){
console.log(returneddata) // show the data echo'd by data.php
if(returneddata == 'success'){ // evaluate data returned
alert('Congratulations!') // i do not use alerts much, i use modals instead -- but for this tutorial we'll alert!
} else {
alert(returneddata); // return an error message
}
})
})
})
</script>
</html>data.php (the file receiving data & evaluating it)
PHP Code
<?php
if(isset($_GET['val'])){
// $val = trim($_POST['val']);
// $desired = 'hello';
if(trim($_GET['val']) == 'hello'){
echo "success";
} else {
echo "The value $val is incorrect and does not match!";
}
} else {
echo "I do not have the neccessary \$_GET value to proceed!";
}
?>style.css - make it look nice :)
Code
.box{
background-color:#f2f2f2;
padding:25px;
max-width:100%;
margin-left:50px;
margin-right:50px;
border-radius:5px;
text-align:center;
}
.input-box{
border-radius:3px;
padding-top:10px;
padding-bottom:10px;
padding-left:5px;
padding-right:5px;
}
.submit-button{
display:inline-block;
position:relative;
margin-top:10px;
border-radius:3px;
background-color:green;
color:white;
border:1px solid black;
text-decoration:none;
padding:10px;
}
.submit-button:hover{
background-color:white;
color:green;
border:1px solid green;
}
