Hey guys & gals, I made a pretty cool video tutorial showing you how to use jQuery's $.ajax method to send & receive data from one file to another. This can be used to retrieve info, refresh live chats, or pretty much anything where you want to update information on one page (or database) without forcing the user to go to another page or reload the current page!
I hope you all like it 🙂
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 you all like it 🙂
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:
<?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;
}







