How To Send and Receive JSON With XAMPP PHP - javascript

I have a XAMPP 7.1.10-0 server running with this index.php
<?php
if(isset($_POST["username"])) {
echo $_POST;
header("Location:getbooks.php");
exit;
} else {
echo file_get_contents("login.html");
}
?>
This initially works and displays the login.html file. Then I want to make a ajax call to this file again to switch to another html file. So login.js does this.
window.onload = function() {
var button = document.getElementById("submit");
button.onclick = function() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var data = {"username": user, "password": pass};
data = $(this).serialize() + "&" + $.param(data);
$.post('index.php', data, function(response) {
console.log(response);
});
}
}
As you can imagine there is a button that is clicked and when it clicks the Ajax call is made. When I click the button it does not change the header and therefore does not change the page. Would anybody know what I am doing wrong?

If you want to redirect, you can do it in AJAX success method.
login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<div class="form">
Username: <input id="username" type="text"></input> <br>
Password: <input id="password" type="password"></input> <br>
<button id="submit">Submit</button>
</div>
<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
var button = document.getElementById("submit");
button.onclick = function() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
$.ajax({
url: 'index.php',
data: {
"username" : user,
"password" : pass
},
type: 'POST',
success: function(response) {
window.location = response;
},
error: function(error) {
}
});
}
})
</script>
</body>
</html>
index.php:
<?php
if(isset($_POST["username"])) {
//process the array
echo "getbooks.php";
} else {
echo file_get_contents("login.html");
}
?>
Aside this, you can also handle the response from PHP in AJAX to update the view of the page without redirection.

Related

Passing variables to a page with AJAX and returning those variables in PHP

I'm trying to do something I would think would be really simple: Pass form data to a PHP page with AJAX, and get the result of the PHP back.
Edited to Add: As written right now, it only returns successfully sporadically, rather than every time it's run, for some reason.
Edited to Add (05/30/2020):
I was able to get it working such as it is by changing the ajax like this:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
$.ajax({
type: "GET",
url:'showme.php' + dataTosend,
data:dataTosend,
async: false,
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = data;
},
error: function(data){
document.getElementById('txtresponse').innerHTML = "failure.";
}
});
});
});
</script>
Now I have to work on serializing the form, because it's actually multiple rows I have to pass. I don't know if I need that as a second question, though.
This is my main page:
<html>
<head>
<script src="Scripts/jquery.min.js"></script>
<script src="Scripts/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.plugin.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.datepick.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("Manager_Review").val();
var dataTosend='DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
$.ajax({
type: "POST",
url:'showme.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = "Successful.";
},
error: function(data){
console.log(data);
document.getElementById('txtresponse').innerHTML = "failure.";
console.log(data);
}
});
});
});
</script>
</head>
<body>
<form id="dddform" method="post">
<input type="text" id="DDD_Number" name="DDD_Number"><br>
<input type="text" id="Manager_Review" name="Manager_Review"><br>
<button id="button" name="Submit">Click Me</button>
</form>
<div id="txtresponse"></div>
<div id="thisworks"><?php if(!isset($_POST['Submit'])){echo $Manager_Review;} ?></div>
</div>
</body>
</html>
This is showme.php:
<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
?>
<script language = 'Javascript'>
document.getElementById('thisworks').innerHTML = '<?php echo $Manager_Review_Date; ?>';
</script>
The call is made successfully. (The "Success"and "Successful" messages appear), but I can't get the value of $Manager_Review_Date to appear in the "thisworks" DIV.
Any pointers? I'm fairly new to AJAX (if you couldn't tell from my code).
Your php should be:
<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
// NO javascript here
And the output of this script is in data variable of success callback:
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = data;
},

Ajax value with redirect and echo to page

I have developed the website using jquery & PHP, I have created a page using HTML, / PHP so what I want is if I click on submit, item ajax should send value to PHP variable and then execute index.php and get that value to another page.
Please help me to resolve the issues.
So far, I have tried the following:
index.php
my Javascript Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = $("#number").val();
$.ajax ({
type: "POST",
url: "ajax.php",
data: { val : val },
dataType:'text',
success: function( result ) {
// window.location.href = 'ajax.php';
// alert(result);
}
});
});
});
</script>
my HTML Code
<form name="numbers" id="numbers">
<input type="text" name="number" id="number" >
<button type="button" id="btn">Submit</button>
</form>
ajax.php
<?php
session_start();
$_SESSION['val'] = $_POST['val'];
print_r($_SESSION);
?>
You can store the value in session and redirect the user to other page and get data from session at other pages.
<?php
session_start();
$_SESSION['data'] = $_GET['val'];
?>
Your HTML code must be like that
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<button type="button" id="btn">Submit</button>
</form>
For redirect to other page you can use like
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
window.location.href = 'url';
}
});
});
});
</script>
in this if you click button its refresh the page because you using input type="submit" on button , so just change it to input type="button"
<input type="button" id="btn" value="submit">
and if you want to keep input type="submit" as you already did then just add prevent default to jquery
$(document).ready(function(){
$("#btn").click(function(event) {
event.preventDefault();
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
}
});
});
});
you can use session
in ajax.php you have to add:
<?php
session_start();
echo $_GET['val'];
$_SESSION['val'] = $_GET['val'];
?>
and use variable $_SESSION['val'] to any page

How to fix Ajax fetch nothing from database?

I have a hard time finding my mistake in this code. I have a search bar and I'd use ajax so that the data will fetch automatically.
This is my html file.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="bootstrap4/jquery/jquery.js"></script>
<script>
function loadproducts()
{
var name = document.getElementById("search");
if(name)
{
$.ajax({
type: 'post',
contentType:false,
cache: false,
processData:false,
data: {
products:name,
},
url: 'loadproducts.php',
success: function (response){
$('#product_area').html(response);
}
});
}
else
{
$('#product_area').html("No Product found!");
}
}
</script>
</head>
<body>
<input type="text" name="search" id="search" onkeyup="loadproducts();">
<div id="product_area">
</div>
</body>
</html>
----------
This is my loadproducts.php file
<?php
include('server/connection.php');
if (isset($_POST['products'])){
$name = mysqli_real_escape_string($db,$_POST['products']);
$show = "SELECT product_name,sell_price FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['product_name']."</p>";
echo "<p>".$row['sell_price']."</p>";
}
}
}
Ill tried putting alert("called"); function on the ajax success and the alert is activated but still no output show. I also edit the var name = document.getElementById("search"); to var name = document.getElementById("#search"); but it pass straight to the else statement.Can someone site the problem of this code?
Currently, you're accessing the actual HTML element. You want the value, so use .value:
var name = document.getElementById("search").value;
Or if you prefer, you can simplify this down with jQuery:
var name = $("#search").val();

How to send textbox value to server using ajax?

I have an HTML form which contains a username textbox and a submit button.
When a user inputs a name in the username textbox, I want to take that value and send it over to the server so I can check whether the username has already been taken by another user or not.
Here is my code for creating the form:
<!DOCTYPE html>
<html>
<head>
<script src="JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial- scale=1">
<script>
function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
}
</script>
</head>
<body>
<div id="Registeration_Div" class="Registeration_Div">
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
placeholder="" name="UserName" maxlength="30" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="Submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
</div>
</body>
</html>
You could use the $.ajax method in jQuery:
function postUsernameToServer() {
var username = $("#Registeration_Username_box").val();
$.ajax({
url: "http://YourServerUrl",
type: "POST",
data: { username: username },
success: function() {
alert('Successfully connected to the server');
},
error: function() {
alert('Something went wrong');
}
});
}
To invoke this using a button click (From my comment) you could do the following:
<button id="checkUsername">Check username</button>
$("#checkUsername").on("click", function() {
postUsernameToServer();
});
Ensure that you have the jQuery library imported to use the function.
If you did not want to use the jQuery and rather native JavaScript you can use the XMLHttpRequest.
Try this it will work :
Use jQuery.ajax()
Code :
function submitFormData() {
var name = document.getElementById("Registeration_Username_box").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username=' + name;
if (username == '') {
alert("Please Enter the Username");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "checkUsername.php",
data: dataString,
cache: false,
success: function(data) {
alert(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
I am giving example in php for checking the username. You can use any language accordingly.
checkUsername.php :
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("dbname", $connection); // Selecting Database
//Fetching Values from URL
$username=$_POST['username'];
//Select query
$query = 'select * from user_table WHERE name = "'.$username.'";
$query_result = mysql_query($query);
$res = mysql_fetch_assoc($query_result);
do
{
echo json_encode($res);
}while($res = mysql_fetch_assoc($query_result));
}
mysql_close($connection); // Connection Closed
?>

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

Categories

Resources