Login Process with jQuery Ajax and PHP - javascript

Hey guys I need some help.
My problem is the error div is not displaying the content that I want it to appear in the success function of my AJAX request. I tried alerting the response and it returns true if user-name and password is correct and returns false if incorrect.
I don't know why its not working.
so this is my code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container" name="main-div">
<div id="error">
AA
</div>
<center>
<div name="login-div">
<h2>LOGIN PAGE</h2>
<form method="post" class="login_form">
Username: <input type="text" name="username"></br></br>
Password: <input type="password" name="password"></br></br>
<button type="submit" name="button_login" id="button_login">LOGIN</button>
</form>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(document).ready(function(){
$("#button_login").click(function(){
var data = $(".login_form").serialize();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: data,
beforeSend: function(){
alert(data);
},
success : function(response){
//alert(response);
if(response=="true"){
$("#error").html("CORRECT USERNAME AND PASSWORD")
//window.location="home.php";
}else{
$("#error").html('<a>WRONG</a>');
});
}
}
});
});
});
</script>
</body>
</html>
Thanks in advance

There is an extra closing bracket in the script what you wrote. Try to open the page in the chrome and open the developers console to see the syntax error.
Login.html:44 Uncaught SyntaxError: Unexpected token )
I corrected the syntax as below
$(document).ready(function(){
$("#button_login").click(function(e){
e.preventDefault();
var data = $(".login_form").serialize();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: data,
beforeSend: function(){
alert(data);
},
success : function(response){
//alert(response);
if(response=="true"){
$("#error").html("CORRECT USERNAME AND PASSWORD")
//window.location="home.php";
}else{
$("#error").html('<a>WRONG</a>');
}
},
error : function(response) {
$("#error").html('error'+ error);
}
});
});
});

Related

AJAX callback does not see jQuery plugin's method

I'm receiving a data from AJAX response and I'm trying to update a jQuery plugin with that value in the success callback:
$.ajax({
url: '/some/url',
type: 'GET',
dataType: 'json',
success: (data) => {
$(".my-rating").starRating('setRating', data.rating);
}
});
I'm using the star-rating-svg plugin to show ratigns (http://nashio.github.io/star-rating-svg/demo/). The problem is that I'm having an error:
Uncaught TypeError: $(...).starRating is not a function
However, this function works perfectly when is called outside AJAX callback. Do you know how to deal with this?
EDIT:
Larger piece of my code:
show.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/star-svg/src/jquery.star-rating-svg.js"></script>
<link rel="stylesheet" type="text/css" href="/star-svg/src/css/star-rating-svg.css">
</head>
<body>
<div class="my-rating mb-1"></div>
<script>
function getUserRating() {
$.ajax({
url: '/some/url/rating',
type: 'GET',
dataType: 'json',
success: () => {
$(".my-rating").starRating('setRating', data.rating);
}
});
}
function webpageReady() {
if($(".my-rating").is(':visible')) {
$(".my-rating").starRating({
starSize: 20,
disableAfterRate: false,
callback: function(currentRating, $el){
$.ajax({
url: '/some/url/setRating',
type: 'POST',
data: {'rating' : currentRating}
});
}
});
getUserRating();
}
}
</script>
<script type="text/javascript">webpageReady();</script>
</body>
</html>
rating.js
router.get("/some/url/rating", function (req, res) {
Rating.findOne({'author.id': req.user._id}).populate("ratings").exec(function(err, rating){
if(err){
console.log(err);
}
else{
res.send({userRating : rating});
}
});
});
I had the same question, and I figured it out like this - I use jQuery StarRatingSvg v1.2.0:
callback: function(rating, $el){
$.post(
URL,
{ rating: rating, _token : "csrf_token" }
).done(function (resp) {
$el.starRating('setRating', parseFloat(resp.rating), false);
});
}
The callback function has two parameters: rating - the value set by a user when they click the stars, and $el - the rating element.
I hope it helps someone.
Here is simple demo for this plugin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/jquery.star-rating-svg.js"></script>
</head>
<body>
<div class="my-rating"></div>
<script>
$(document).ready(function(){
$(".my-rating").starRating({
starSize: 25,
callback: function(currentRating, $el){
// make a server call here
}
});
});
</script>
</body>
</html>
Problem solved: In a footer there was another link to a jquery.

Hitting token error exception unexpectedly?

I am getting unexpected token error from below code and not sure which part have gone wrong
<script>
function delete(n){
alert("This is Called");
if (confirm("Are you sure?")) {
$.ajax({
url: 'functions/delete.php',
type: 'POST',
data: {id: n},
success: function(response) {
console.log(response);
alert('This Works');
}
});
} else {
}
}
</script>
Re-name your function and get rid of the <script> tag if the code is in an external script. Check out below for example:
function deleteFn() {
alert("This is Called");
if (confirm("Are you sure?")) {
alert('This Works');
//Make AJAX call here
}
}
deleteFn();
delete is reserved word in JavaScript, you need to rename "delete" function.
And I would split the code on small peaces and test them separately.
Here is a working example (https://next.plnkr.co/edit/BwG70k3cNQf9sy3A) and the same code below. It does the same as you wanted but without alerts and confirm popups, and I put different URL, it returns response:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button onclick="remove('7')">Run POST Request</button>
<div id="result"></div>
<pre id="data"></pre>
<script>
function remove(n){
$.ajax({
url: 'https://httpbin.org/post',
type: 'POST',
data: {id: n},
success: function(response) {
//console.log(response);
$('#result').html('POST request was successfull:');
$('#data').html(JSON.stringify(response, null, '\t'));
}
});
};
</script>
</body>
</html>

AJAX call display response from php script in html

I have a html file where users can input a value.
I wrote a script in PHP that checks if this value is present in the databse. If it's present it returns
{"active":true}
Now my goals is that when the user inputs their value and submit they will be redirected to a certain page if this active is true. If it's false they should see an error message.
So here's what I've tried with my AJAX call:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
data: data,
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
Here is my HTML:
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="#" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue" />
</form>
For some reason I get an error:
Uncaught ReferenceError: data is not defined
I am new to AJAX and I am not sure if what I am trying is correct.
Any help would be greatly appreciated!
Thanks in advance.
Can you try:
$(".aanmeldenmodal").submit(function(e){
e.preventDefault();
I am updating my answer in whole
<html>
<body>
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="txt1" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue checkform" />
</form>
</body>
</html>
jQuery part is like
$("document").ready(function () {
$("body").on("click", ".checkform", function (e) {
e.preventDefault();
var request = $("#txt1").value;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {request: 'request'},
dataType: 'json',
success: function (data) {
if(data.active==true){
alert("success");
}else{
alert("failure");
}
}
});
});
});
ajax.php should be like this
if(isset($_GET['request'])){
//check for the text
echo json_encode($arr);
}
In api/check.php
You can pass data in json format
$json = json_encode($data);
retrun $json;
You can also not share any data so You can remove data from jQuery.
data:data
Your Jquery look like this:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});

jquery POST response successful BUT data empty

im using jquery to send a post to a session endpoint of my api to get a login token. the request returns success, however the data is empty. if i do the same request in cURL it returns json.
Im new to jquery. does anyone have any suggestions as to what the problem might be?
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE> login </TITLE>
</HEAD>
<LINK rel="stylesheet" type="text/css" href="login.css" />
<BODY>
<DIV id="container">
<DIV id="header">
<IMG src="image.bmp" alt="logo" style="width:64px;height:64px;"/>
<H1> my service </H1>
</DIV>
<DIV id="content">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("button").click(function()
{
$.post("www.mydomain.com/api/session",
{
username: "batman",
password: "123"
},
function(data,status)
{
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
<DIV id="loginform">
<form method="POST">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<button> welcome! </button>
</form>
</DIV>
<DIV id="description">
<P>mydomain description</P>
<P>Join now to see what people are doing near you!</P>
</DIV>
<DIV id="register">
<P>Dont have an account with us? </P>
<P>Register here now !!</P>
</DIV>
</DIV>
<DIV id="nav">
</DIV>
</DIV>
</DIV>
</BODY>
</HTML>
WOW! i found the problem, it was so simple. i just needed to use http:// in front of my url.
Thanks for every ones time and help!.
Moreover Punit's answer, I advice to use $.on() method which is better than .click() function.
$(function() {
// equals to $(document).ready(function(){ but faster to wright
$("#loginform").on('click', 'button', function() {
//Punit's Code (that is good !!)
$.ajax({ url: 'your_url_here',
data: {username: 'batman' , password : "123"},
type: 'post',
dataType: "json",
success: function(output) {
alert(output);
}
});
});
});
The issue's likely to be that you need to stop the form from being submitted after your button click event is executed. As written, once the script has completed, the page is refreshed and there is no opportunity to process the results of the post request. Return 'false' from the click function:
$("button").click(function() {
$.post("www.mydomain.com/api/session",
{
username: "batman",
password: "123"
},
function(data,status)
{
alert("Data: " + data + "\nStatus: " + status);
});
return false;
}
);
This done you should see whether your post request is returning any data. Note that because you're posting to a directory, the script will default to looking for an index file, e.g. index.php. If that's an issue, change your URL to point directly to the relevant server-side script.
Below is the for creating an Ajax call, now what you have to do it. You have to return the data into json format from the URL, then try console.log(output) in the success function, you will get the idea that hot it is works.
$.ajax({ url: 'your_url_here',
data: {username: 'batman' , password : "123"},
type: 'post',
dataType: "json",
success: function(output) {
alert(output);
}
});
let me know if you dont understand anywhere,

jquery ajax in codeigniter returns nothing

this is my function in controller
function show_data()
{
return " this is me ";
}
this is my view:
<html>
<head>
<title>ajax call first time</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
alert("hello");
$.ajax({
type:'POST',
dataType: "text",
url:'elements/show_data',
success:function(res){
console.log(res);
$('#response').html(res);
},
fail:function()
{
$('#response').html("done");
}
});
});
</script>
</head>
<body>
<div class="response" id="response" ></div>
<div class="container" id="container" ></div>
</body>
</html>
the console says empty string returned why?
This is how I use $.ajax
$.ajax({
type: 'POST',
dataType: 'text',
url: 'the/url',
data: {data1: "value", data2: "value"}
}).done(function(res) {
console.log(res);
});
You may want to check your url elements/show_data with browser (use GET) to make sure that your controller works.

Categories