I have a site where you type into a text box and it will send what I wrote to my database.
I have been stuck with my page having to reload which is very troubling in my case. i am not familiar with ajax but i have heard it can be used to complete this task. i have 2 files one is called demo.php this sends the information to the server and at this time has a header that redirects me back to that page which i don't want.
I want to be able to keep sending things data to the sever without the page reloading. the other page is the index.php this is were i right into the text box and send the text to my database both files are listed below.
this is the demo.php
<?php
header("Location: http://mywebsite.com");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "working";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
this is the forum on index.php were i enter the information and send it. i need it to stay on that page and not reload in any way.
<form action="demo.php" method="post" />
<p> <input id="textbox" type="text" name="firstname" placeholder="Enter What You Want Your Message To Be" /></p>
<input id="textbox1" type="submit" value="Submit" />
</form>
my second attempt at index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="button" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
});
</script>
</html>
You can have two files/pages for your purpose:
1. Form page
2. Ajax processing page where you request values will be inserted into your database.
Add this to your head tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
Steps to utilize ajax:
1. Include jquery library in form page
2. Include html form
3. Save values from ajax, that means process that ajax
HTML form suppose to be like this:
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
Ajax call:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
ajax_target.php handles formData, its validation and insertion to database.
your html/index form consists
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="demo.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
</script>
</html>
your demo.php includes
<?php
//your db insertion goes here.
echo "inserted successfully";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name ="send" value="send" >
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function(){
var options = {
beforeSend: function () {
if (!confirm('Are you sure to submit ?')) {
return false;
}
},
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
};
}
$('#ajax-form').ajaxForm(options);
});
</script>
</body>
</html>
updated your index.php
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My index.php is:
<head>
<meta charset="UTF-8">
<title>Example Ajax PHP Form</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<form id="my_form_id">
Your Email Address: <input type="text" id="email" /><br>
<button type="submit" id="ddd">button</button>
</form>
<script>
$(document).ready(function(){
$('#my_form_id').submit(function(e){
var email = $('#email').val();
console.log(email);
$.ajax({
type: 'post',
url: 'http://localhost/script.php',
data: {email: email},
success: function(data){
alert(data);
}
});
});
});
</script>
</body>
My goal is to pass an email from my index.php page to another file titled script.php. The script.php code is:
<?php
$emailAddress = '';
if(isset($_POST['email'])){
echo $_POST['email'];
$emailAddress = $_POST['email'];
}
echo 'Received email was: ' .$emailAddress;
?>
When I run my index.php page I am able to enter an email address and the data is successfully displayed in an alert box. However, when I refresh the script.php page it doesn't display the email address. Any help would be greatly appreciated!
<?php
$e = array();
$e['error'] = 'not ok';
if(isset($_POST['email'])){
//echo $_POST['email'];
//$emailAddress = $_POST['email'];
$e['emailAdress'] = $_POST['email'];
$e['text'] = 'Received email was: ';
$e['error'] = 'ok';
}
echo json_encode($e);
?>
Use the json_encode method in your php script
<script>
$(document).ready(function(){
$('#my_form_id').submit(function(e){
var email = $('#email').val();
console.log(email);
$.ajax({
type: 'post',
url: 'http://localhost/script.php',
data: {email: email},
success: function(data){
alert(data.error);
//do stuff
}
},"json");
});
});
</script>
And it is your index.php script that will receive the data.
It is Ajax which and made to work on a single page!
It's not possible to keep the value between page refresh unless you use some storage method: file, database or session.
In case you are using some of this, in index.php the first thing to do is retrieved the stored email and set it as the value of the input.
Simple pseudocode:
If there is email stored
Set email as input value
Show form
Check https://www.php.net/manual/en/reserved.variables.session.php for more info in PHP sessions
---- EDIT with session storage:
at the beggining of index.php add:
<?php
session_start();
$emailAddress = isset($_SESSION['email']) ? $_SESSION['email']:'';
?>
and the input definition now is:
Your Email Address: <input type="text" id="email" value="<?= $emailAddress ?>"/><br>
And script.php have to be like:
<?php
session_start();
$emailAddress = '';
if (isset($_POST['email'])) {
echo $_POST['email'];
$emailAddress = $_POST['email'];
$_SESSION['email'] = $emailAddress;
} else {
unset($_SESSION['email']);
}
echo 'Received email was: ' . $emailAddress;
If you want to display the email in the next page (i.e. script.php), you can use the following codes:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Example</title>
</head>
<body>
<form method="post" action="script.php">
<p>Your Email Address: <input type="email" name="email" required /><br />
<button>Send</button></p>
</form>
</body>
</html>
script.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Example - script.php</title>
</head>
<body>
<p><?php
if(isset($_POST['email'])){
echo 'Received email was: ' . $_POST['email'];
} else {
echo 'No email is received. Something went wrong.';
}
?></p>
</body>
</html>
Alternatively, if you insist using AJAX to pass the data and display on screen, you can do the followings:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Example</title>
<style>
#result { display: none; }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<p>Your Email Address: <input type="email" name="email" id="txt_email" required /><br />
<button type="button" id="btn_send">Send</button></p>
<div id="result"></div>
<script>
$('#btn_send').click(function(){
$.post('script.php', {
email: $('#txt_email').val()
}, function(data) {
if(data.status == 'error') {
console.log('Error occurred');
} else if(data.status == 'success') {
$('#result').html('Email is ' + data.email).show();
}
});
});
</script>
</body>
</html>
script.php
<?php
header('Content-Type: application/json');
if(isset($_POST['email'])) {
$email = trim($_POST['email']); // TODO: validate email via filter_var()
echo json_encode(array('email' => $email, 'status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
?>
I'm trying out a tutorial to learn how to do instant search with PHP/jQuery. I can't seem to find why this code won't work. This search was working before when I had the PHP in the same file as the index, but when I moved it to another file, it stopped working. I keep getting this console error message with each keystroke: ReferenceError: Can't find variable: $_POST. Any help would be deeply appreciated.
index.php file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php file (same location as index.php)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>
Looks like you've used the PHP $_POST in your script..
Try to use:
$.POST
Try this
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});
i am trying to echo the value entered by the user in the input tag using jquery and ajax .
the following is my code
< script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script> <
script type = "text/JavaScript" >
function showMessage() {
var message = document.getElementById("message").value;
$.ajax({
url: 'value_pass.php',
type: 'GET',
data: {
var_PHP_data: message
},
success: function(data) {
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//case error
}
});
} <
/script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
<?php echo "hi".$_GET['var_PHP_data'];?>
</body>
</html>
My php script is:
<?php
echo "hi".$_GET['var_PHP_data'];
?>
the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.
If you are doing this on same page add your php script at the top of the page that handle your ajax request
Like this
<?php if(isset($_GET['var_PHP_data'])){
echo "hi".$_GET['var_PHP_data'];
die;
}?>
<!-- rest of your html code start from here -->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
</body>
</html>
If you using ajax, follow below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
<span id = 'PHP_data'></span>
</body>
</html>
<script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>
<script type = "text/JavaScript" >
function showMessage() {
var message = document.getElementById("message").value;
$.ajax({
url: 'value_pass.php',
type: 'GET',
data: {
var_PHP_data: message
},
success: function(data) {
message1 = "Hi "+message
$('#PHP_data').html(message1);
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//case error
}
});
}
</script>
If you are using form submit use below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method ='GET'>
Enter message: <input type="text" id="message" name = "message">
<input type="submit" value="submit" />
<?php if(isset($_GET['message'])){
echo "hi".$_GET['message'];
die;
} ?>
</form>
</body>
</html>
So I am trying to do something simple. There is a form, it does a self post and I want to get that post information from JQuery and put it into a div.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
JQuery here to catch button click and do a "PHP_self":
<script>
$(document).ready(function(){
$(".gettingpostbutton").click(function(){
$.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", function( data ) {
$("#add_post_information_html_here").append(data+" number from $_POST");
});/**/
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = test_input($_POST["number"]);
}
For SQL Injection:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Basic Form:
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
put a number: <input type="text" number="number">
<br><br>
<input type="button" name="action" class="btn btn-success gettingpostbutton" value="Add Number" />
</form>
Put info to page either through PHP but prefer to do it through JQuery:
<?php
echo "<h2>Your Input:</h2>";
echo $number;
?>
<div id="add_post_information_html_here"></div>
</body>
</html>
Result:
I am new to Angular JS , i want to insert data from form to MySQL database table ( in my case table name is employe ) But when i hit submit it is not inserting . I compiled insert.php file in browser which gives me this error "Trying to get property of non-object" . I am sending data in JSON format and then i have decoded in the index.php file but when i tried to access the decoded data via $data object it gives me the mentioned error .
myApp.js code
var app = angular.module('myApp',[])
.controller("myController",function($scope,$http){
$scope.insertData = function(){
$http.post("insert.php",{'name': $scope.name,'fname': $scope.fname,'dept': $scope.dept})
.success(function(data,status,headers,config){
console.log("Inserted Successfuly!");
});
}
});
insert.php code
<?php
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$fname = $data->fname;
$dept = $data->dept;
$host = 'localhost';
$dbname = 'company';
$dbusername = 'root';
$dbpass = '';
$connection = mysqli_connect($host,$dbusername,$dbpass,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$query = "INSERT INTO employe ('id','ename','fname','dept') VALUES('','$name','$fname','$dept')";
$query_run = mysqli_query($connection,$query);
}
?>
index.html code
<html ng-app="myApp">
<head>
<title> Using Angular with PHP! </title>
<!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>-->
<style type="text/css" src="css/bootstrap.min.css"></style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12" ng-controller="myController">
<form>
Your Name: <input type="text" ng-model="name" /><br><br>
Father Name: <input type="text" ng-model="fname" /><br><br>
Department : <input type="text" ng-model="dept" /><br><br>
<input class="btn btn-success" type="button" value="Submit" ng-click="insertData()" />
</form>
</div>
</div>
</div>
<script type="text/javascript" src="js/angular/angular.min.js"></script>
<script type="text/javascript" src="js/bootstrap/bootstrap.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
You will laugh but just by adding these `` around your table name would do your work fine
$query = "INSERT INTO `employe`(`id`, `ename`, `fname`, `dept`) VALUES('','$name','$fname','$dept')";