I have this html code that's supposed to retrieve a local json file and have it parse and stringify to the local storage. I wanted to test the code, but when I fill out the form and run it, it says ReferenceError: insertRecord is not defined in Firefox console.
Any help would be very much appreciated.
Thank you.
<!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>
<title>Register</title>
<link href="css/navigation.css" rel="stylesheet" type="text/css">
<link href="css/body.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<script src="store.js" type="text/javascript"></script>
<script type="text/javascript">
var i;
var user;
var txt;
$(document).ready(function () {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: getUser,
error: function() {alert("retrieval error"); }
});
});
function getUser(data) {
if (localStorage) {
if (!localStorage.getItem('user')) {
user = JSON.parse(data.User);
localStorage.setItem('user', user);
}
else {
String item = localStorage.getItem('user');
user = JSON.parse(item);
}
}
else
alert("Local Storage not supported");
}
function insertRecord() {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: insertUser,
error: function(){ alert("retrieval error"); }
});
function insertUser() {
txt = { firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
userName: document.getElementById("userName").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value
};
localStorage.setItem('user', user + JSON.stringify(txt));
}
}
</script>
</head>
<body>
<img src="images/Dance etc logo LARGE.jpg" width="263" height="150" alt="Dance Etc Logo" />
<hr />
<div data-role="header">
<h1>Dance Etc.</h1>
</div>
<div data-role="content" >
<h1>Register</h1>
<form method="post" action="" id="register" name="form">
<label>First Name: </label>
<input type="text" id="firstName" /><br />
<label>Last Name: </label>
<input type="text" id="lastName" /><br />
<label>Username: </label>
<input type="text" id="userName" /><br />
<label>Email: </label>
<input type="text" id="email" /><br />
<label>Password: </label>
<input type="password" id="password" /><br />
<input type="submit" value="Register" onClick="insertRecord()" />
</form>
</div>
<div data-role="footer">
Contact Us
Policy
History
</div>
In your code you have the following line:
String item = localStorage.getItem('user');
This isn't valid JavaScript and is therefore throwing a SyntaxError: Unexpected identifier, preventing the rest of your JavaScript code from being evaluated.
However, as you try to attach insertRecord inline in the HTML, it tries to run when triggered, but can't invoke code that didn't get evaluated.
You should consider attaching event listeners using element.addEventListener.
Additionally, indenting your code may help you debug, too.
var i, user, txt;
$(document).ready(function () {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: getUser,
error: function () {
alert("retrieval error");
}
});
});
function getUser(data) {
if (localStorage) {
if (!localStorage.getItem('user')) {
user = JSON.parse(data.User);
localStorage.setItem('user', user);
} else {
item = localStorage.getItem('user');
user = JSON.parse(item);
}
} else
alert("Local Storage not supported");
}
function insertRecord() {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: insertUser,
error: function () {
alert("retrieval error");
}
});
function insertUser() {
txt = {
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
userName: document.getElementById("userName").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value
};
localStorage.setItem('user', user + JSON.stringify(txt));
}
}
Related
I am trying to add records into the database table without reloading the page, I am using ajax in my case eventually got a response(201) from the server(alert("Error occurred !")). I just messed up with this code from the last couple of hours but didn't find the hit where I am getting wrong.
records.html
<!DOCTYPE html>
<html>
<head>
<title>Insert data in MySQL database using Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 60%;">
<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
×
</div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name">
</div>
<div class="form-group">
<label for="pwd">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
</div>
<div class="form-group">
<label for="pwd">Phone:</label>
<input type="text" class="form-control" id="phone" placeholder="Phone" name="phone">
</div>
<div class="form-group" >
<label for="pwd">City:</label>
<select name="city" id="city" class="form-control">
<option value="">Select</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
</select>
</div>
<input type="button" name="save" class="btn btn-primary" value="Save to database" id="butsave">
</form>
</div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
if(name!="" && email!="" && phone!="" && city!=""){
$.ajax({
url: "input.php",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
</body>
</html>
input.php
<?php
include "mysqli_connect.php";
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$sql = "INSERT INTO `bulk`( `name`, `email`, `phone`, `city`)
VALUES ('$name','$email','$phone','$city')";
if (mysqli_query($con, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($con);
?>
Table structure:
Try adding datatype:"JSON" in your ajax call
$.ajax({
url: "input.php",
datatype: "JSON",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
alert(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
In input.php, check whether the data is coming or not:
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['city']))
{
/// your insert code
}
data: {
'name': name,
'email': email,
'phone': phone,
'city': city
}
Try this and if it doesn't work do a print_r of the $name variables to see if they are filled incorrectly.
I want to send OTP with Laravel and ajax but when i'm calling ajax it shows error page not found...
HTML:
`
<div id="first_step">
<div class="col-md-4">
<input value="+91" type="text" placeholder="+1" id="country_code" name="country_code" />
</div>
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
`
script:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
var host = "{{URL::to('/')}}";
alert(host);
$.ajax({
type: "POST",
url: host+"/send_otp",
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
}); });
Route in web.php:
Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function');
//Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function'); also try this
Controllers:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response);
}
Welcome to SO. As far as I understand and according to jQuery.ajax documentation you have forgotten to set datatype='json' in your ajax request. Your request should be:
$.ajax({
type: "POST",
url: host + "/send_otp",
datatype: 'json',
data: {
name: phone_number
},
success: function(msg) {
alert(msg);
},
error: function(request, status, error) {
alert(request.responseText);
}
});
I see a few things that could be throwing the error.
You are prepending the ajax url to post to with the variable host. It's not needed, you should try it this way:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
As per Laravel documentation (https://laravel.com/docs/5.8/responses), you can return json responses like the below:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
You should be sending the csrf token with your post:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {
_token: {{ csrf_token() }}, //csrf token
name:phone_number
},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
HTML :
<!DOCTYPE html>
<html>
<head>
<title>Ajax Dynamic Dependent Dropdown in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
.box{
width:600px;
margin:0 auto;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="first_step">
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" id="phone_number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
{{ csrf_field() }}
</body>
</html>
<script>
$(document).ready(function(){
$('#send_otp_button').on('click', function(e) {
var select = $('#phone_number').val();
alert(select);
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, _token:_token},
success:function(result)
{
alert(result);
}
})
});
});
</script>
Web.php(Route File)
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/dynamic_dependent', 'DynamicDependent#index');
Route::post('dynamic_dependent/fetch', 'DynamicDependent#fetch')->name('dynamicdependent.fetch');
?>
//DynamicDepdendent.php (Controller)
<?php
//DynamicDepdendent.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$response = $request->get('select');
echo $response;
}
}
?>
i got something weird in my code. honestly, i got this from someone and i try to adapt it for my needs. So the problem is when i click fetch button, the data is not display. can any body here tell me what is wrong with the code?
Any related answer will be appreciated. Thanks in advance.
and here are my code
<script type="text/javascript">
$(document).ready(function() {
function myrequest(e) {
var name = $('.username').val();
$.ajax({
method: "GET",
url: "http://localhost/spdb/debug/autofill.php", /* online, change this to your real url */
data: {
username: name
},
success: function( responseObject ) {
alert('success');
$('#posts').val(responseObject.level);
$('#joindate').val(responseObject.last_login);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
<form method="POST" action="?act=proc">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</fieldset>
</form>
</body>
</html>
and this is the PHP code :
$return = mysqli_query($konek, "SELECT * FROM tb_auth WHERE username ='admin' LIMIT 1");
$rows = mysqli_fetch_array($return);
$formattedData = json_encode($rows);
print $formattedData;`
here are the result from PHP Code :
{
"0":"1",
"id_auth":"1",
"1":"TRC-US001",
"auth_code":"TRC-US001",
"2":"admin",
"username":"admin",
"3":"5f4dcc3b5aa765d61d8327deb882cf99",
"password":"5f4dcc3b5aa765d61d8327deb882cf99",
"4":"1",
"level":"1",
"5":"2018-07-05 13:55:19.200878",
"last_login":"2018-07-05 13:55:19.200878",
"6":"1",
"status":"1"
}
this is the picture :
result
Hope this can help you
first we need to do some modification on html, and php code :
<!-- doctype is mandatory -->
<!DOCTYPE html>
<!-- language en -->
<html lang="en">
<head>
<!-- title also is mandatory -->
<title>tilte of your project</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form method="POST" action="?act=proc">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</fieldset>
</form>
<!-- put all your javascript before the end of the body -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
function myrequest(e) {
// use $('#username') to select by id instead of $('.username') used to select by class
var name = $('#username').val();
$.ajax({
method: "GET",
url: "http://localhost/spdb/debug/autofill.php", /* online, change this to your real url */
data: {
username: name
},
dataType: 'json', /* this is not mandatory */
success: function( responseObject ) {
console.log('success');
$('#posts').val(responseObject.level);
$('#joindate').val(responseObject.last_login);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
</body>
</html>
php code :
// this line is very important, by using this line
// the browser can recognize that the data sent from
// the server as a json object.
header("Content-type: application/json");
$formattedData = [];
if (isset($_GET['username'])) {
$username = trim($_GET['username']);
// to be sure that the username is not empty
if(empty($username)) {
print json_encode($formattedData);
exit;
}
$konek = mysqli_connect($sql_db_host, $sql_db_user, $sql_db_pass, $sql_db_name, 3306);
$return = mysqli_query($konek, "SELECT * FROM tb_auth WHERE username = '" . $username . "' LIMIT 1");
// use mysqli_fetch_assoc instead of mysqli_fetch_array
// $rows = mysqli_fetch_array($return);
$rows = mysqli_fetch_assoc($return);
$formattedData = json_encode($rows);
// very important every connection created need to be closed
mysqli_close($konek);
}
print $formattedData;
In your html code, there is an input with an id username. In Javascript, search for this line of code var name = $('.username').val();. Change . to #. It should be var name = $('#username').val();.
.username is for any tag that have a class username.
#username will search for a tag that have an id username.
try to parse responseObject to json using
responseObject=JSON.parse(responseObject);
in you success function
I'm working on an Angularjs + Moodle + WebService APP
I have done a little Login page and have a question.
I'm getting the Token of my user via $.ajax and I can see it in my chrome console.
The thing is, I want to save that token for using it in WS moodle fuctions and I'm usin JSON.strungify to get the token, but I have not successed.
I just get -> {readystate: 1} as an alert, instead get a token. but in my console.info(response); I got the token as show the next image :
Thi is my code:
controller.js
var app = angular.module('mainApp', ['ngRoute', 'toaster', 'ngAnimate']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html'
})
.when('/dashboard', {
resolve: {
"check": function($location, $rootScope) {
if(!$rootScope.loggedIn){
$location.path('/');
}
}
},
templateUrl: 'dashboard.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('loginCtrl',
function($scope, $location, $rootScope) {
$scope.submit = function() {
/*if($scope.username == 'admin' && $scope.password == 'admin') {
$rootScope.loggedIn = true;
$location.path('/dashboard');
} else {
alert('Wrong Stuff');
}*/
$rootScope.loggedIn = true;
var username = $scope.username;
var password = $scope.password;
postCredentials(username, password/*, createSession*/);
};
function postCredentials(username, password, callback) {
if (username!==null || password!==null) {
var serverurl = 'https://comunidaddeaprendizaje.cl/ac-cap/login/token.php';
var data = {
username: username,
password: password,
service: 'moodle_mobile_app' // your webservice name
}
var response = $.ajax(
{ type: 'POST',
data: data,
url: serverurl,
dataType: 'JSON'
}
);
console.info(response);
dataString = JSON.stringify(response);
alert(dataString);
if (dataString.indexOf('error') > 0) {
alert('Invalid user credentials, please try again');
};
} else {
alert('Something Wrong');
}
}
}
);
login.html
div class="breadcrumbs" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
Home
</li>
<li class="active">Login</li>
</ul>
</div>
<div class="page-content">
<div class="row">
<div class="space-6"></div>
<div class="col-sm-10 col-sm-offset-1">
<div id="login-box" class="login-box visible widget-box no-border">
<div class="widget-body">
<div class="widget-main">
<h4>Login ACCAP</h4>
<div ng-controller="loginCtrl">
<form action="/" class="form-horizontal" id="myLogin">
<div class="form-group">
UserName:
<input type="text" class="form-control" id="username" ng-model="username" required focus><br>
Password:
<input type="password" class="form-control" id="password" ng-model="password" required>
</br>
<button type="button" class="width-35 pull-right btn btn-sm btn-primary" ng-click="submit()">
<div class="col-sm-7">
<i class="ace-icon fa fa-key"></i>
Login
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login APP</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/1.1.0/toaster.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.7/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.js"></script>
<script src="https://code.angularjs.org/1.2.0/angular-animate.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/1.1.0/toaster.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-view></div>
</body>
</html>
Thanks for your help!
The response variable is an object which contains a lot of information about the response. It is not the same as your response text.
Your second mistake is that your AJAX call is asynchronous, so you cannot obtain your response immediately after AJAX call. You need to wait for the response. Instead of
var response = $.ajax({
type: 'POST',
data: data,
url: serverurl,
dataType: 'JSON'
});
console.info(response);
dataString = JSON.stringify(response);
alert(dataString);
if(dataString.indexOf('error') > 0) {
alert('Invalid user credentials, please try again');
};
you should write
var response = $.ajax({
type: 'POST',
data: data,
url: serverurl,
dataType: 'JSON',
success: function(response) {
console.info(response);
dataString = JSON.stringify(response);
alert(dataString);
if(dataString.indexOf('error') > 0) {
alert('Invalid user credentials, please try again');
};
}
});
Once a form is submitted my javascript hides one div and shows another:
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
The bottom line is where I'm trying to add some text to the div that is dynamically displayed. However, nothing is displayed in the div. I'd also like to show the variable from another function in the same file.
it's the var e = $("#username").val(); from the code below which I would like to add to the div eventually.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin() {
var e = $("#username").val();
var p = $("#password").val();
if(e != "" && p != "") {
$.ajax({
type: 'POST',
url: 'http://localhost/php/log.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
if (response.success) {
$.mobile.changePage("#loginTest");
}
else {
alert("Your login failed");
}
},
error: function(error){
alert('Could not connect to the database' + error);
}
});
}
else {
alert("You must enter username and password");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
HTML Code:
<body>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="button" value="Login" id="submitButton" onclick="handleLogin()">
<div data-role="footer">
</div>
</div>
<div id="loginTest" data-role="page">
<div id="name">
</div>
</div>
</body>
try this on element id loginTest (#loginTest)
document.getElementById('loginTest').innerHTML= your variable here; //or any string
if you are using jquery
$( '#loginTest' ).text( your variable ); //or any string
Wouldn't you be better to restrict the post back:
<input type="button" value="Login" id="submitButton" onClientClick="handleLogin()">
and then return false from the function.