Using click event to show response in console log - javascript

I am following a link to allow a person to reset a password, however, everything that I have done so far isn't working and I can't figure out why as I am following the tutorial closely. I am using javascript and html so far, but there are no errors in the console so i am unsure what is wrong.
HTML
<div class="container-forgotPassword">
<div class ="row justify-content-center">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<img id="logologin" src="../img/logo1.png" alt="logo"/>
<input class="formPassword" id="email" placeholder="Please enter your Email Address">
<input type="button" class="btn-forgotPassword" value="Reset Password">
</div>
</div>
</div>
</div><!-- /container -->
jQuery
var email = $("#email");
$(document).ready(function () {
$('.btn-forgotPassword').on('click', function () {
if (email.val() != "") {
email.css('border', '1px solid green');
$.ajax({
url: 'php/forgotPassword.php',
method: 'POST',
dataType: 'text',
data: {
email: email.val()
}, success: function (response) {
console.log(response);
}
});
} else
email.css('border', '1px solid red');
});
});
In the tutorial so far he has gotten the input box to turn green/ red and when he enters text into the input field and then clicks the button it will create a response in the console log. But as I said mine is doing nothing, does anyone know how I can fix this? Not sure what I am doing wrong

you need error callback in ajax to show you the error
you miss write. there is no parameter named method in jquery ajax. this should be type
.
$.ajax({
url: 'php/forgotPassword.php',
type: 'POST', //not method
dataType: 'text',
data: {
email: email.val()
}, success: function (response) {
console.log('success');
console.log(response);
}, error: function(response){
console.log('error');
console.log(response); //get all error response
console.log(response.responseText);//get error responseText
}
});

Related

ajax Uncaught ReferenceError: post is not defined at HTMLButtonElement.<anonymous>

Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});

jQuery validation AJAX form

I'm trying to add validation to my ResetPassword function. validation its work fine, but I got another problem my ResetPassword function not going to work after I add validation.Can anyone direct me in the right direction? thx.
HTML code:
<div class="PopUpBG">
<div class="PopUp">
<h3 class="modal-title">
<span>Reset PAssword</span>
</h3>
<form id="form">
<input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>
<input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>
</form>
</div>
</div>
ResetPassword & validation code:
function ResetPassword(e) {
var email = $("#ResetEmail").val();
if ($("#form").validate()) {
return true;
} else {
return false;
}
$(".PopUp").html("We have sent mail to you");
$.ajax(
{
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: email,
},
complete: function () {
console.log("send");
$(".PopUpBG").fadeOut();
}
})
}
The issue is because you're always exiting the function before you send the AJAX request due to your use of the return statement in both conditions of your if statement.
Change your logic to only exit the function if the validation fails:
function ResetPassword(e) {
if (!$("#form").validate())
return false;
$.ajax({
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: $("#ResetEmail").val().trim(),
},
success: function() {
console.log("send");
$(".PopUp").html("We have sent mail to you");
setTimeout(function() {
$(".PopUpBG").fadeOut();
}, 10000); // fadeout the message after a few seconds
},
error: function() {
console.log('something went wrong - debug it!');
}
})
}
Also note that I amended the logic to only show the successful email message after the request completes. Your current code can show the 'email sent' message to the user, even though there is still scope for the function to fail.

How to evaluate json response data - ajax form?

I don't know how to write a proper question. But please let me explain this. I sent from with ajax and return with json. Each json value contain its status. So I need to test/evaluate the status and do something with it.
JSON
{url:"error",email:"ok",name:"ok"}
JS
//new port
$('#pflBtn').on('click',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'inc/wcont8_port_db.php',
data :$(this).closest('form').serialize(),
dataType: 'json',
success: function(data){
if(data.url=="err"){//if url=error
$('#plf_url').addClass('error');//will add .error into #plf_url class
}else{
$('#plf_url').addClass('success');
}
}
})//ajax
})
html
<form class="pflForm">
<div class="form-group form-float">
<div class="form-line" id="pfl_url">
<input type="text" class="form-control" name="pfl_url" value="URL" required />
<label class="form-label">URL (www.domain.com)</label>
</div>
</div><!-- form-group form-float -->
<button type="submit" id="pflBtn">Save</button>
</form>
There are two mistakes you have made, check my comments with the code and try again by changing them:
$('#pflBtn').on('click',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'inc/wcont8_port_db.php',
data :$(this).closest('form').serialize(),
dataType: 'json',
success: function(data){
if(data.url=="error"){// url has value 'error', but this was checking 'err'
$('#plf_url').addClass('error');//will add .error into #plf_url class but the class is not available in your html,
}else{
$('#plf_url').addClass('success');
}
}
})//ajax
})

Facing AJAX issue with JSP

I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});

Return False not working on form

I have a log in form that I am trying to submit via AJAX. I have a similar form for registration that is working perfect; however, the return false statement isn't firing.
My log in form looks like this:
<form name="loginForm" id="loginForm" action="userSystem/userSystem.php" method="post">
<div class="loginTable">
<div class="loginRow">
<div class="loginCell"><label for="username">Username:</label></div>
<div class="loginCell"><input type="text" name=="username" id="loginFormUser"></div>
</div>
<div class="loginRow">
<div class="loginCell"><label for="password">Password:</label></div>
<div class="loginCell"><input type="password" name="password" id="loginFormPass"></div>
</div>
<div class="loginRow">
<div class="loginCell"> </div>
<div class="loginCell"><input type="submit" name="submit" value="Log In" id="loginFormSubmit"></div>
</div>
</div>
</form>
</section>
<section id="loginBarRegForm">
<h1>Step Two</h1>
<form name="regForm" id="regForm" action="usersystem/register.php" method="post">
<div class="loginTable">
<div class="loginRow">
<div class="loginCell"><label for="r_username">Username:</label></div>
<div class="loginCell"><input type="text" name="r_username" id="r_username"></div>
<div class="loginCell"><span id="r_usernameFeedback"></span></div>
</div>
<div class="loginRow">
<div class="loginCell"><label for="r_password">Password:</label></div>
<div class="loginCell"><input type="password" name="r_password" id="r_password"></div>
<div class="loginCell"><span id="r_passwordFeedback"></span></div>
</div>
<div class="loginRow">
<div class="loginCell"><label for"r_vpassword">Verify Password</label></div>
<div class="loginCell"><input type="password" name="r_vpassword" id="r_vpassword"></div>
<div class="loginCell"><span id="r_vpasswordFeedback"></span></div>
</div>
<div class="loginRow">
<div class="loginCell"><label for="email">Email:</label></div>
<div class="loginCell"><input type="text" name="r_email" id="r_email"></div>
<div class="loginCell"><span id="r_emailFeedback"></span></div>
</div>
<div class="loginRow">
<div class="loginCell"></div>
<div class="loginCell"><input type="submit" name="r_submit" value="Register" id="r_submit"></div>
<div class="loginCell"></div>
</div>
</div>
</form>
And the javascript that I'm trying to execute when the submit button is clicked on
$("#loginFormSubmit").click(function() {
form_data = {
username: $("#loginFormUser").val(),
password: $("#loginFormPass").val(),
operation: "login",
is_ajax: 1
}
$.ajax({
type: "POST",
url: "userSystem/userSystem.php",
data: form_data,
dataType: json,
success: function(data) {
if(data.success) {
$("#loginBarLoginForm").fadeOut("slow");
$("#userDetailsUsername").html(data.username);
$("#userDetailsEmail").html(data.email);
$("#userDetails").fadeIn('slow');
} else {
$("#loginbarLoginForm").fadeOut("slow");
$("#loginBoxResponseDiv").html(data.message);
$("#loginBoxResponseFrame").fadeIn("slow");
}
}
});
return false;
});
So far this is about the most in depth application I've developed, but it just doesn't make sense as to why return false will work in one instance, but not another. They are nearly identical functions except for the data.
Thank you for any help you can provide :)
EDIT: Updated Code.
$("#loginFormSubmit").click(function() {
console.log("Click Event Firing");
var form_data = {
username: $("#loginFormUser").val(),
password: $("#loginFormPass").val(),
operation: "login",
is_ajax: 1
};
console.log("variables Assigned " + form_data['username'] + " " + form_data ['password']);
$.ajax({
type: "POST",
url: "userSystem/userSystem.php",
data: form_data,
success: function(data) {
console.log("Ajax Working");
if(data.success === true) {
$("#loginBarLoginForm").hide();
$("#loginBoxResponseDiv").html("<p>You have been loged in " + data.username + "!");
$("#loginBoxResponseFrame").fadeIn("slow");
} else {
$("#loginBarRegForm").hide();
$("#loginBoxResponseDiv").html(data.message);
$("#loginBoxResponseFrame").fadeIn("slow");
}
}
});
});
The code will now return a JSON respones, but the function for success is not being fired.
return false inside the handler but outside the ajax to prevent the default action of the submit.
$("#loginForm").on('submit',function() { //attach handler to form
form_data = {...} //form data
$.ajax({...}); //fire ajax
return false; //prevent default action
});
The return false is working as required, but the problem is that the Success method is a callback , which is called by Jquery implicitly whenever there is a successful message from the server side on ajax call, so at that time, you dont have any handle to get the value from it, so either you need to define your logic in another method and make the method call here, as its the callback ,you dont have handle to manipulate.
and yes if you want to return the $.ajax() call to return false, you can remove the return false statement to outside the scope of the success method.
Just an idea, but change the type of the input from "submit" to "button".
And, just for debugging purposes, don't dynamically assign a click event. Change your JS to this:
function NamedFunction() {
form_data = {
username: $("#loginFormUser").val(),
password: $("#loginFormPass").val(),
operation: "login",
is_ajax: 1
}
$.ajax({
type: "POST",
url: "userSystem/userSystem.php",
data: form_data,
dataType: json,
success: function(data) {
if(data.success) {
$("#loginBarLoginForm").fadeOut("slow");
$("#userDetailsUsername").html(data.username);
$("#userDetailsEmail").html(data.email);
$("#userDetails").fadeIn('slow');
} else {
$("#loginbarLoginForm").fadeOut("slow");
$("#loginBoxResponseDiv").html(data.message);
$("#loginBoxResponseFrame").fadeIn("slow");
}
}
});
return false;
}
Then add this to your submit button
onclick="NamedFunction(); return false;"
I'm not recommending you keep it that way, but perhaps with those 2 changes you can really track down what's happening.
It turns out that all along, I was just missing some quotes in my solution. I needed to replace:
dataType: json,
with:
dataType: "json",
Once I got that, the solution came into place and now my users will be able to log in without a page refresh. I still have a long way to go on this project, but thank you all for helping point me in the right direction. Also I feel acomplished that I was able to find the answer on my own; however, I never would have, had it not been for the fine help and tips that I received from the SO community. You guys are one in a million!
The final solution ended up looking like this:
$("#loginFormSubmit").click(function() {
console.log("Click Event Firing");
var form_data = {
username: $("#loginFormUser").val(),
password: $("#loginFormPass").val(),
operation: "login",
is_ajax: 1
};
console.log("variables Assigned " + form_data['username'] + " " + form_data ['password']);
$.ajax({
type: "POST",
url: "userSystem/userSystem.php",
dataType: "json",
data: form_data,
success: function(data) {
console.log("Ajax Working");
console.log("data.success: " + data.success);
console.log("data.username: " + data.username);
if(data.success === true) {
console.log("data.success was true");
$("#loginBarLoginForm").hide();
$("#loginBoxResponseDiv").html("<p>You have been loged in " + data.username + "!");
$("#loginBoxResponseFrame").fadeIn("slow");
$("#notLoggedIn").fadeOut("slow");
$("#currentlyLoggedIn").fadeIn("slow");
$.cookie("username", data.username, {expires: 7, path: "/"});
$.cookie("id", data.id, {expires: 7, path: "/"});
$.cookie("email", data.email, {expires: 7, path: "/"});
$.cookie("user_level", data.user_level, {expires: 7, path: "/"});
$.cookie("active", data.active, {expires: 7, path: "/"});
$.cookie("reg_date", data.reg_date, {expires: 7, path: "/"});
$.cookie("last_login", data.last_login, {expires: 7, path: "/"});
$("#cookieUsername").html($.cookie("username"));
$("#cookieID").html($.cookie("id"));
$("#cookieEmail").html($.cookie("email"));
$("#cookieUserLevel").html($.cookie("user_level"));
$("#cookieActive").html($.cookie("active"));
$("#cookieRegDate").html($.cookie("reg_date"));
$("#cookieLastLogin").html($.cookie("last_login"));
} else {
console.log("data.success was false");
$("#loginBarRegForm").hide();
$("#loginBoxResponseDiv").html(data.message);
$("#loginBoxResponseFrame").fadeIn("slow");
}
}
});
});

Categories

Resources