im trying to reload a table whenever the user hits the save button. but the problem is that the whole page is being reloaded.plz someone help.here is my javascript code:
$(document).ready(function(){
//save button listener
$("#save").click(function(){
//receiving data entered by user from design.php
var name = $('#name').val();
var email = $('#email').val();
var telephone = $('#telephone').val();
var username = $('#username').val();
var password=$('#password').val();
$.ajax({
type:'POST',
url: 'contactData.php',
data:{"name":name,"telephone":telephone,"email":email, "username":username, "password":password},
// dataType:'json',
success: function(data) {
var result = JSON.parse(data);
$("#validate").html(result.msg);
if (result.msg="Your info has been sent")
{
$("#table").load("design.php");
return false;
}
}//end of success
});//end of ajax
});//end of listener
});//end of javascript
and this is the div that i want to reload which is in the design.php page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact Info</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery1.js'></script>
<script src='jqueryTest.js'></script>
</head>
<body>
<h2>Contact Information</h2>
<p><span class="error">* required field</span></p>
Name: <input type="text" id="name" >
<span class="error">* </span>
<br><br>
Email: <input type="text" id="email" >
<span class="error">* </span>
<br><br>
Telephone: <input type="text" id="telephone" >
<span class="error">* </span>
<br><br>
UserName: <input type="text" id="username">
<span class="error">*</span>
<br><br>
Password: <input type="password" id="password">
<span class="error">*</span>
<br><br>
<input type="button" id="save" value="save" >
<div id="validate"></div>
<div id="table">
<?php
$username = "root";
$password = "";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
$selected = mysql_select_db("mysql", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM users ");
?>
<table border="2" style= "background-color: #99ffcc; color: #761a9b; margin: 0 auto;">
<thead>
<tr>
<th>Name</th>
<th>Telephone</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<tbody class="container">
<?php
while( $row = mysql_fetch_assoc( $result ) )
{
echo "<tr>
<td>{$row['name']}</td>
<td>{$row['telephone']}</td>
<td>{$row['email']}</td>
<td>{$row['username']}</td>
<td>{$row['password']}</td>
</tr>\n";
}
?>
</tbody>
</tr>
</thead>
</table>
</div>
when hitting the save button the whole page is being reloaded.what is the solution for div table only to be reloaded
Have only <div id="table"> in design.php file, in your original file have the <div id="show-table"> and in the success function of ajax store the whole page as Object and append to the div dynamically like this
var Obj = load('design.php');
$('#show-table').html(Obj);
Remember the design.php file has to separate file from the file where you have written the script
Related
index html:
<!DOCTYPE html>
<html>
<head>
</head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<body>
<form method="post" action="/cms/common/sendEmail" enctype="multipart/form-data" class="valida tc" id="thisForm">
<input type="hidden" name="lang" value="tch" />
<tr>
<td>
<div class="g-recaptcha" id="recaptcha" data-sitekey="sitekey"></div>
</td>
</tr>
<tr>
<td class="submitBtnWrap"><input type="submit" value="送出" class="roundBtn" /><span class="at-error"></span></td>
</tr>
</table>
</form>
</body>
</html>
recaptcha.php:
<?php
$public_key = "6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ";
$private_key = "6Lc9oGIaAAAAAEthTaDOcm3VJ9Uldizbl6ZDKQ2_";
$url = "https://www.google.com/recaptcha/api/siteverify";
$q
=$_GET["q"];
echo $q;
if(array_key_exists('submit_form',$_POST)){
// echo "<pre>";print_r($_POST);echo"</pre>";
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
$response = json_decode($response);
// echo "<pre>";print_r($response);echo "</pre";
if($response->success == 1)
{
echo "Your information was valid...";
}else{
echo "You are a robot and we don't like robts.";
}
}
?>
Hello, I try to add the recaptcha 2 in my web. The site side and server side are done.
But how can I send the token to google server side verification using php file as the form action cannot be edited to action="recaptcha.php".
Or is any solution like using ajax, javascript to finish server side verification?
Please help me. Thank you all.
If you can't change action="recaptcha.php", you need to use AJAX to verify the responses.
So, Your index.html should be like
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="/cms/common/sendEmail" enctype="multipart/form-data" class="valida tc" id="thisForm">
<input type="hidden" name="lang" value="tch" />
<tr>
<td>
<div id="recaptcha" ></div>
</td>
</tr>
<tr>
<td class="submitBtnWrap"><input type="submit" value="送出" class="roundBtn" /><span class="at-error"></span></td>
</tr>
</table>
</form>
<!-- Add jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Add recaptcha explicitly -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<!-- render and verify by ajax -->
<script>
var onloadCallback = function() {
grecaptcha.render('recaptcha', {
'sitekey' : '6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ',
'callback' : verifyCallback,
});
}
var verifyCallback = function(response) {
$.post('recaptcha.php', {'g-recaptcha-response' : response}, function(data){
alert(data);
});
};
</script>
</body>
</html>
your recaptcha.php:
<?php
$public_key = "6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ";
$private_key = "6Lc9oGIaAAAAAEthTaDOcm3VJ9Uldizbl6ZDKQ2_";
$url = "https://www.google.com/recaptcha/api/siteverify";
if(isset($_POST['g-recaptcha-response'])){
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
$response = json_decode($response);
if($response->success == 1)
{
echo "Your information was valid...";
}else{
echo "You are a robot and we don't like robts.";
}
}
?>
So like the title says, $_SESSION['login_user'] returns undefined yet the login form still works.
I use $_SESSION['login_user'] after login to store the persons username to use for headings ect.
Here is the code below.
index.php
<?php
include('login.php'); // Includes Login Script
if (isset($_SESSION['login_user'])) {
header("location: profile.php"); // Redirecting To Profile Page
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="login">
<h2>Login Form</h2>
<form action="login.php" method="post">
UserName : <input id="name" name="username" placeholder="username" type="text">
Password : <input id="password" name="password" placeholder="**********" type="password"><br><br>
<input name="submit" type="submit" value="Login">
<span><?php echo $error; ?></span>
</form>
</div>
</body>
</html>
login.php
<?php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "sports world");
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT Username, Password from login where Username=? AND Password=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row {
$_SESSION['login_user'] = $username; // Initializing Session
header("location: profile.php"); // Redirecting To Profile Page
}
mysqli_close($conn); // Closing Connection
}
session.php
<?php
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "sports world");
session_start();// Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Information Of User
$query = "SELECT Username from login where Username = '$user_check'";
$ses_sql = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['Username'];
profile.php
<?php
include('session.php');
if(!isset($_SESSION['login_user'])){
header("location: index.php"); // Redirecting To Home Page
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link href="Main.css" rel="stylesheet" type="text/css">
<link href="Shop.css" rel="stylesheet" type="text/css">
<script src="Main.js" type="text/javascript"></script>
<script>
sessionStorage.setItem('status','loggedIn');
sessionStorage.setItem('username','<?php echo $_SESSION['login_user']; ?>');
sessionStorage.setItem('Fname', 't');
</script>
</head>
<body onload="myFunctionH(); bttn();">
<section id="header">
<div class="header">
<h1>Sports World</h1>
</div>
<div class="MainMenu">
<a href="Home.php" >Home</a>
<a href="Shop.php" >Shop</a>
Contact Us
Cart
<input class="active button button3" id="b1" onclick="dest();" type=button>
</div>
</section>
<!--
<div id="">
<b id="">Welcome : <i><?php /*echo $_SESSION['login_user']; */?></i></b>
<b id="">Log Out</b>
</div>
-->
<section id="row" >
<div class="column2">
<div class="column4">
<div class="card3">
<h1>Your Profile</h1>
<h4 id="name" style="margin: 0; padding: 0;" class=""> Name: Thomas Shields </h4>
<h4 id="user" style="margin-bottom: 7%; margin-top: 0; padding: 0;" ></h4>
<button onclick="myFunctionH()" class="p.dashed">Dashboard</button>
<button onclick="myFunctionH()" class="p.dashed">Orders</button>
<button onclick="myFunctionH()" class="p.dashed">Addresses</button>
<button onclick="myFunctionS()" style=" border-style: solid none solid none;" class="p.dashed">Account Details</button>
<div id="myDIV">
<div class="column6">
<div class="">
<input type="submit" name="change_details" style="margin-top:0;" class="btn btn-success" value="Change Details"/>
</div>
</div>
</div>
</div>
</div>
<div class="column3">
<div class="card3">
</div>
</div>
</section>
<section id="row">
</section>
</body>
</html>
main.js
function bttn() {
let elem = document.getElementById("b1");
if (sessionStorage.getItem('status') === null) {
elem.value = "Login"
}
if (sessionStorage.getItem('status') !== null) {
elem.value = "View Account";
}
}
if (sessionStorage.getItem('status') === "loggedIn") {
let us = sessionStorage.getItem('username');
document.getElementById("user").innerHTML = "Username: " + us;
}
function dest() {
if (sessionStorage.getItem('status') === null) {
window.location.href='index.php'
} else if (sessionStorage.getItem('status') !== null){
window.location.href='profile.php'
}
}
window.onbeforeunload = function(){
sessionStorage.setItem('status',' ');
};
function myFunctionH() {
let x = document.getElementById("myDIV");
x.style.display = "none";
}
function myFunctionS() {
let x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
}
}
I've being trying different things for ages but i just can't get it to work.
Note: it did work in a previous version and when comparing the versions nothing seems different...
Cheers
So, i simply changed $_SESSION['login_user'] to $_SESSION['login_user2'] for all of them and it fixed the problem ¯_(ツ)_/¯. No idea what was causing it.
Alerting Numbers or Characters only input values in text box? How in AngularJS?
I want to add functionality that when someone put a numbers in the countryname text box. The program will alert "Input country name not numbers". In contrast with the zip code "Input zip code not name"
Here is my code...
<!DOCTYPE html>
<html>
<head>
<title>Country Listings</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/angular.min.js"></script>
</head>
<body>
<div class="container" style="width:500px;">
<h1 align="center">Countries</h1>
<div ng-app="myapp" ng-controller="countrycontroller" ng-init="displayData()">
<label>Search: </label>
<input type="text" ng-model="searchBox" class="form-control">
<br />
<label>Country Name</label>
<input type="text" name="country_name" ng-model="countryname" class="form-control" value="{{countryname}}" required="" />
<br />
<label>Zip Code</label>
<input type="text" name="zip_code" ng-model="zipcode" class="form-control" required="" />
<br />
<input type="hidden" ng-model="id" />
<input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="{{btnName}}"/>
<br /><br />
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Country Name</th>
<th>Zip Code</th>
<th colspan="2">Actions</th>
</tr>
<tr ng-repeat="x in names | filter:searchBox">
<td class="tbl">{{x.id}}</td>
<td class="tbl">{{x.country_name}}</td>
<td class="tbl">{{x.zip_code}}</td>
<td class="tbl"><button ng-click="updateData(x.id, x.country_name, x.zip_code)" class="btn btn-info btn-xs">Edit</button></td>
<td class="tbl"><button ng-click="deleteData(x.id )" class="btn btn-danger btn-xs">Delete</button></td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
<script>
var app = angular.module("myapp",[]);
app.controller("countrycontroller", function($scope, $http){
$scope.btnName = "Submit";
$scope.insertData = function(){
if($scope.countryname == null)
{
alert("Country Name is required");
}
else if($scope.zipcode == null)
{
alert("Zip Code is required");
}
else
{
$http.post(
"insert.php",
{'countryname':$scope.countryname, 'zipcode':$scope.zipcode, 'btnName':$scope.btnName, 'id':$scope.id}
).success(function(data){
alert(data);
$scope.countryname = null;
$scope.zipcode = null;
$scope.btnName = "Submit";
$scope.displayData();
});
}
}
$scope.displayData = function(){
$http.get("select.php")
.success(function(data){
$scope.names = data;
});
}
$scope.updateData = function(id, first_name, last_name){
$scope.id = id;
$scope.countryname = first_name;
$scope.zipcode = last_name;
$scope.btnName = "Edit";
}
$scope.deleteData = function(id){
if(confirm("Are you sure you want to delete this data?"))
{
$http.post("delete.php", {'id':id})
.success(function(data){
alert(data);
$scope.displayData();
});
}
else
{
return false;
}
}
});
</script>
I've tried adding another else if ($scope.countryname = [0-9]), bubt it didn't work. Please help... I also tried editing my insert.php but no lack.
index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$data = json_decode(file_get_contents("php://input"));
if(count($data) > 0)
{
$country_name = mysqli_real_escape_string($connect, $data->countryname);
$zip_code = mysqli_real_escape_string($connect, $data->zipcode);
$btn_name = $data->btnName;
if($btn_name == "Submit")
{
$query = "INSERT INTO tbl_user(country_name, zip_code) VALUES ('$country_name', '$zip_code')";
if(mysqli_query($connect, $query))
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
}
if($btn_name == 'Edit')
{
$id = $data->id;
$query = "UPDATE tbl_user SET country_name = '$country_name', zip_code = '$zip_code' WHERE id = '$id'";
if(mysqli_query($connect, $query))
{
echo 'Data Updated...';
}
else
{
echo 'Error';
}
}
}
?>
Use ng-pattern
For only numbers:
ng-pattern="/^[0-9]*$/"
For only characters:
ng-pattern="/^[a-zA-Z]*$/"
Reference
**This is my php index.php file. I want to type first name and last name type and auto it has to be save the database. I wrote the code using ajax. but, this is not working properly. Please can any one help me. **
index.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script type="text/javascript">
$(document).on('keyup','firstName','lastName',function(){
var rel = $(this).attr('rel');
var flatvalue = $(this).val();
$("#firstName"+rel).val(flatvalue);
});
</script>
</head>
<body>
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
</body>
</html>
onKeyPress event not proper because it call many times as per user hit.
Use onBlur event instead of onKeyPress for submit the form and save it to MySql users table.
Try below example,
PHP
<?php
$connection = mysql_connect("localhost", "jaydeep_mor", "jaydeep_mor");
$db = mysql_select_db("jaydeep_mor", $connection);
if(isset($_POST['firstName']) && isset($_POST['lastName'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName != '' || $lastName != ''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
header("Location: test.php?msg=Data Inserted successfully...!!");
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
HTML / JAVASCRIPT
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta><title>Home Page</title>
<script type="text/javascript">
function saveData(){
document.forms["userDataForm"].submit();
}
</script>
</head>
<body>
<?php if(isset($_GET['msg']) && trim($_GET['msg'])!=""){ ?>
<br /><div><?php echo $_GET['msg']; ?></div><br />
<?php } ?>
<form action="test.php" method="post" name="userDataForm">
<label for="firstName">First Name</label>
<input type="text" name="firstName" value="<?php echo isset($_POST['firstName'])?$_POST['firstName']:''; ?>" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" value="<?php echo isset($_POST['lastName'])?$_POST['lastName']:''; ?>" onblur="return saveData();" ><br><br>
<!--input type="submit" id="Submit" name="Submit" value="submit"/-->
</form>
</body>
</html>
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_REQUEST['firstName'])){
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
die();
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
die();
}
}
//mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){ alert('d');
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url:'',
data:{'firstname':firstname,'lastname':lastname, },
type: 'POST',
success: function(data){
alert("Data Save: " + data);
}
});
});
});
</script>
</head>
<body>
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName"><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName"><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</body>
</html>
may be this can help you,
if you want to do it via form submit then just you need to give the url of your controller function in the action method of the form
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
if you want to do it via ajax then you can add id attribute for first_name and last_name input and can do it in following way,
$('#submit').on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$.ajax({
url: url of your controler, //url of your controller function
type: "POST",
data: {'first_name' : first_name,'last_name':last_name},
success: function (data) {
//whatever you want to do on success
} else {
//in case of no data
}
}
});
});
in the same way you can give a class attribute to the input box and on keyup event can save the data via class
have you try doing it this way
$('body').delegate('input[type="text"]', 'keypress keydown keyup change propertychange paste', function(event) {
event.stopImmediatePropagation();
if (event.type === 'keydown' || event.type === 'keypress') {
return;
}
//insert what you want to do here
//perform some ajax
/*
$.ajax({
url: 'index.php',
method: 'POST',
data: {
'firstName' : $('input[name=firstName]).val(),
'lastName' : $('input[name=lastName]).val()
},
success: function(mResponse) {
alert(mResponse);
}
});
*/
});
I have to insert data through jQuery and ajax method. But data is not inserting in database. Pleas help me is this method is wrong?
Here is my code,
form.html
<!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- <script src="jquery-3.1.0.js" type="text/javascript"></script>-->
<script type="text/javascript">
function submitData()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
var contact = document.getElementById('contact')
$.ajax({
type: 'POST',
url: 'data_ins.php',
data:{
uname:name,
uage:age,
ucontact:contact
},
success: function(response){
$('#success_para').html("Data inserted");
}
});
return false;
}
</script>
</head>
<body>
<form method="POST" onsubmit="return submitData();">
name : <input type="text" name="name" id="name"> <br>
age : <input type="text" name="age" id="age"> <br>
contact : <input type="text" name="contact" id="contact"> <br>
<input type="submit" name="submit" >
</form>
<p id="success_para"></p>
</body> </html>
and, data_ins.php
<?php
$conn = mysqli_connect("localhost","root","","test_db");
$name = $_POST['uname']; $age = $_POST['uage']; $contact = $_POST['ucontact'];
if(!$conn) {
echo"<script>alert('Database Connection Failed or invalid connection');</script>"; }
else {
$sql = "insert into records (name, age, contact) values ('$name', '$age', '$contact')"; mysqli_query($conn, $sql);
mysqli_error($conn); }
?>
Please let me know what's wrong in my code. Thanks, in advance.
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
Your "submit" button causes page reloading, so you'll not be able to see the result of a query in your onSuccess.
<input type="button" name="submit" onclick="submitData();" >
Have you checked your response? You can also view it in browser's inspector.
success: function(response){
$('#success_para').html(response);
}