I am building forms using AJAX and encountering a problem:
Whenever I submit the form, the values stored in the database go blank ... (FYI, of course the page doesn't refresh.. that's the whole point.)
Here is my file index.php:
<!doctype html>
<html>
<head>
<title>Form Practice</title>
</head>
<body>
<div id="myForm">
Name: <input name="username" type="radio" value="Sagar">Sagar</input>
<input name="username" type="radio" value="Saransh">Saransh</input><br /><br />
Profession: <input name="profession" type="radio" value="Coder">Coder</input>
<input name="profession" type="radio" value="Entrepreneur">Entrepreneur</input>
<input name="profession" type="radio" value="Blogger">Blogger</input><br /><br />
<input type="submit" id="submit" value="Submit"></input>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$.ajax({
url: "data.php",
type: "POST",
async: false,
data:{
"username":$('input[name=username]:checked', '#myForm').val(),
"profession": $('input[name=profession]:checked', '#myForm').val()
}
});
</script>
</body>
</html>
And my Data.php:
<?php
require 'connect.php';
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('cant use'. DB_NAME . ':'. mysql_error());
}
$username = $_POST['username'];
$profession = $_POST['profession'];
$sql = mysql_query("INSERT INTO info (Name, Profession) VALUES('{$username}', '{$profession}')");
if(!mysql_query($sql)){
die('Some Error '. mysql_error());
}
mysql_close();
?>
<!doctype html>
<html>
<head>
<title>Data</title>
</head>
<body>
</body>
</html>
try this
<script>
$(document).ready(function(){
$('#submit').on('click', function(){
$.ajax({
type: 'POST',
async: false,
url: 'data.php',
data:{
"username":$('input[name=username]:checked', '#myForm').val(),
"profession": $('input[name=profession]:checked', '#myForm').val()
},
success: function(response)
{
}
}).error(function(request, status, error){
console.log(e);
});
});
});
</script>
Edit with this
<script>
$(document).ready(function(){
$('#submit').on('click', function(){
var username=$('input[name="username"]:checked').val();
var profession=$('input[name="profession"]:checked').val();
$.ajax({
type: 'POST',
async: false,
url: 'data.php',
data:"username=" + username+ "&profession="+ profession,
success: function(response)
{
}
}).error(function(request, status, error){
console.log(e);
});
});
});
</script>
Related
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>
Often i use ajax by jquery but according to the below code why it doesn't display "you had wrong" message when "IF"is true? and just display "faile" message?
file Login.php
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<title>just for test</title>
</head>
<div id="Response" ></div>
<h3>login</h3>
<form id="Login" class="form-login">
<input type="text" class="form-control" name="yourname" id="yourname" placeholder="yourname">
<button type="submit" class="btn btn-bricky pull-left"> ورود <i class="fa fa-arrow-circle-right"></i> </button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function (e){
$("#Login").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "include/php/check_login.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
if(data=='faile'){
$("#Response").html('you had wrong...');
}else{
$("#Response").html(data);
}
return false;
}
});
}));
});
</script>
</body><!-- end: BODY -->
</html>
file:check_login.php
<?php
if (isset($_POST['yourname']) && !empty($_POST['yourname']))
{
$yourname=$_POST['yourname'];
echo $yourname;
}
else echo "faile";
?>
Here is method for receiving json based data
<!DOCTYPE html>
<html lang="en" class="no-js"> <head> <title>just for test</title> </head>
<body>
<div id="Response" ></div>
<h3>login</h3>
<form id="Login" class="form-login">
<input type="text" class="form-control" name="yourname" id="yourname" placeholder="yourname">
<button type="submit" class="btn btn-bricky pull-left"> ورود <i class="fa fa-arrow-circle-right"></i> </button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$(function (e) {
$("#Login").submit(function(e){
e.preventDefault();
$.ajax({
url: "check_login.php",
data: new FormData(this),
type: "POST",
contentType: false,
cache: false,
processData:false,
// data type should be set to json to get the response data as json value
dataType: 'json',
success: function(json) {
if( json.data == 'faile') {
$("#Response").html('you had wrong...');
} else {
$("#Response").html(json.data);
}
return false;
}
});
});
});
</script>
</body>
</html>
check_login.php
<?php
session_start();
if (isset($_POST['yourname']) && !empty($_POST['yourname']))
{
$response = array( "data" => $_POST['yourname']);
} else {$response = array( "data" => "faile");}
echo json_encode($response);
?>
Using json, there should be no error regarding \n :: the new line after echo
Place
var yourname=$('#yourname').val();
between <script> and $(document).ready(function (e){
and change from
data: new FormData(this),
to
data: "yourname="+yourname;
add die(); after else echo "faile";
Look for newline that is returned after the ?>, as it returns something like "faile\n".
You can use one of:
remove the closing ?> tag
add die after echo
check for "faile\n"(not recommended)
I want to make form html look like this :
<script>
function name()
{
var name = $('#name').val();
var url_send = 'send.php';
$.ajax({
url : url_send,
data : 'name='+name,
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
}
</script>
<script src="assets/bootstrap-sweetalert.js"></script>
<script src="assets/sweetalert.js"></script>
<link rel="stylesheet" href="assets/sweet-alert.css">
<form action="#" method="post">
<label>Name</label>
<input type="text" name="name"><br>
<input type="submit" onclick="name();">
<div id="result"></div>
and this is send.php
<?php
$name = $_POST['name'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
And the problem is,how i show SweatAlert modal,when result of php is Success Sweatalert will show Success Modal.And when failed it will show Failed Modal ?
Now what must i edit to my script?
I hope you are expecting code with jquery ajax;
See the code below;
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<link rel="stylesheet" type="text/css" href="sweetalert-master/dist/sweetalert.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="sweetalert-master/dist/sweetalert.min.js"></script>
<script>
$(document).ready(function () {
$("#submit").on("click", function(e){
e.preventDefault();
var name_val = $("#name").val();
$.post( "send.php", {name_send:name_val}, function(data){
if (data == 'success'){
swal("Good job!", "Nice work!", "success");
return false;
}else{
swal("Here's a message!", "Please type a name");
}
});
});
});
</script>
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="name" id="name"><br>
<input type="submit" id="submit">
</form>
</body>
</html>
send.php
<?php
$name = $_POST['name_send'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
$.ajax({
url : url_send,
data : {name: name},
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
in your ajax code you placed data : 'name='+name, , please have a look at what i did , maybe that helps
Jquery ajax accepts object in data parameter data: {key:value}. In the question we are using string as a parameter to data of jquery ajax
Source code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Content-Type: application/json');
echo json_encode($_POST);
exit(0);
}
?>
<html>
<head>
<title>Web Test</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script type="text/javascript">
$.ajaxSetup({
data: {role: 'admin'} //(I)
});
//Ajax to current page
$.ajax('test', {
method: 'post',
data: $('#formTest').serialize() //(II)
,success: function(res){
console.log(res);
}
});
</script>
</body>
</html>
I want to send the form data by jQuery AJAX, and append default data (role=admin) to every AJAX request, but it doesn't work as I want.
I take some option like below:
data: {role: 'admin'} //(I) (for default data)
data: $('#formTest').serialize() //(II) (for form data)
(This is exactly as the source code above)
=> RESULT from console: {username: "admin", password: "admin_pass"}
So, this approach seem does not work
data: 'role=admin' //(I)
data: $('#formTest').serialize() //(II)
(Same URLencoded format)
=> Same as above
data: [{name: 'role', value: 'admin'}] //(I)
data: $('#formTest').serializeArray() //(II)
(Same serializeArray format)
=> Same as above
data: {role: 'admin'} //(I)
data: {username: 'admin', password: 'admin_pass'} //(II)
=> This approach works! But there is no built-in jQuery method to convert form data to object like that. I must use a "thirt-party" solution use $('#formTest').serializeObject() (from here).
So, is there any way to solve this problem with jQuery only?
JQuery offer ajaxSetup and serialize/serializeArray method but they seem not play well with each other.
Why just not append a variable with the desirable data?
<html>
<head>
<title>Web Test</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script>
var theRole = '&role=admin';
//Ajax to current page
$.ajax('test.php', {
method: 'post',
data: $('#formTest').serialize() + theRole,
success: function(res) {
console.log(res);
}
});
</script>
</body>
</html>
EDIT
Another approach, using ajaxSetup()
<html>
<head>
<title>Web Test</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script>
$.ajaxSetup({ data: {role: 'admin'} });
//Ajax to current page
$.ajax('test.php?' + $('#formTest').serialize(), {
method: 'post',
success: function(res) {
console.log(res);
}
});
</script>
</body>
</html>
Must then use json_encode( $_REQUEST ) instead.
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
header( 'Content-Type: application/json' );
echo json_encode( $_REQUEST );
}
?>
Basically I've got a AJAX Login page that is working and everything but when I successfully login I want it to redirect to a page without it reloading I'm not sure how its done as I am very new to langauge. Many thanks
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<title>Popup Login</title>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='1')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){
?>
<a href='logout.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<div class="err" id="add_err"></div>
<form action="login.php">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
$mysqli=mysqli_connect('');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo '1';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
When I successfully login I want it to redirect to a page without it reloading
As long as the page to be redirected to is on the same domain, or you can set CORS headers properly, and you can deal with relative links, then in your success callback you can replace the entire page's HTML with that of the new page.
You can start another ajax call for your new page, and use document.write() to obliterate the existing HTML like so:
...
success: function(html){
if(html=='1') {
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut(400, function(){
// Completely replace the page's HTML
$.ajax({
type: 'GET',
url: 'http://example.com/logged-in',
async: false, // You want this synchronous
success: function(data) {
// This code block replaces your current page seamlessly
document.open();
document.write(data);
document.close();
},
error: function(e){
alert(e.message);
}
});
});
}
...
Here is a demo:
$("#bye").fadeOut(1400, function(){
$.ajax({
type: 'GET',
url: 'http://enable-cors.org/',
async: false,
success: function(data) {
// This is a quick-n-dirty hack
// to get the relative links working for the demo
var base_href = '<base href="http://enable-cors.org/">';
document.open();
document.write(base_href + data);
document.close();
},
error: function(e){
alert(e.message);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="bye"><h1>Logged in Successfully</h1></div>