why it doesn't display "you had wrong" message? - javascript

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)

Related

why when i reload a page using AJAX the data disappears

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

Blank values stored in database - Ajax Forms

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>

Get responses from php (SweetAlert)

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

AJAX PHP LOGIN Page is not redirecting correctly

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>

Read the value entered in text box in html form and use it by retrieving it in a php page

<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<h2>Train Information from Indian Railways API</h2>
<form id="info">
Please enter train number:<br><br>
<input type="text" id="trainno" name="train">
<br><br>
<input type="submit" value="Submit">
</form>
<script>
$("#info").submit(function(){
$.ajax({
method: 'GET',
url: 'example.php',
success: function(Result){
var myObj = $.parseJSON(Result);
console.log(myObj.result);
},
error: function(data){
alert('ERROR');
}
});
});
</script>
</body>
</html>
example.php
<?php
echo "Value entered is: " .$_GET['train '];
$ch = curl_init("http://api.erail.in/route/?key=3d970b43-550b-4568-9227-492697f47093&trainno=12138");
$fp = fopen("example_homepage.txt", "w");
//$ch is a cURL handle returned by curl_init
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//Execute $ch
$result = curl_exec($ch);
//Read the file contents
$json_data = file_get_contents('example_homepage.txt');
echo $json_data;
curl_close($ch);
fclose($fp);
?>
I am unable to retrieve the user entered value in php and then use it to manipulate the url there, which gets me the data from API server. When I run the HTML page, it just gives me an alert of ERROR. What am I doing wrong? Is it the ajax call? Should it be post method? I tried using ajaxForm from AJAX plugin but no change. Any help will be appreciated. Thank You.
You need to pass the trainno value in the ajax request using "data":
$.ajax({
method: 'GET',
url: 'example.php',
data: { train: $('#trainno').val() },
success: function(Result){
var myObj = $.parseJSON(Result);
console.log(myObj.result);
},
error: function(data){
alert('ERROR');
}
});
});
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<h2>Train Information from Indian Railways API</h2>
<div style="float:left;">Your train name is: <span style="font-weight: bold" id="holder-name"></span></div>
<br><br>
Please enter train number:<br><br>
<form id="myform" name="myform"></form>
<input type="text" name="train" id="trainno">
<br><br>
<input type="submit" name="save" id="save" value="Save">
</form>
<script>
$('#save').on('click', function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "example.php",
data: {train: $('#trainno').val()},
success: function (data) {
//alert(data.result.name);
$('#holder-name').html(data.result.name);
// YOU CAN DO WHATEVER YOU WANT WITH THE DATA
},
error: function (x, e) {
alert("Error");
}
});
});
</script>
</body>
</html>
example.php
<?php
if(isset($_REQUEST['train'])){
$url = 'http://api.erail.in/route/?key=3d970b43-550b-4568-9227-492697f47093&trainno=' . $_REQUEST['train'];
$data = file_get_contents($url);
header('Content-Type: application/json');
echo $data;
} else {
echo json_encode(array("error" => "no data"));
}

Categories

Resources