i am comparing the response i got from jsp page to ajax . i want to perform if out.print() print success message so i want to perform action in success ajax function . i am comparing data . but it is not working . i always go to else section . i am new in ajax . can please help me out with this problem.
$.ajax({
url: "login.jsp",
//datatype: "text",
type: "POST",
data: datatopost,
success: function(data){
if(data.search("success")!=-1){
console.log(data.data);
$('#loginmessage').html(data);
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
// window.location = "mainpageloggedin.jsp";
//$('#loginmessage').text(data);
}else{
// $('#loginmessage').text(data);
//hide spinner
//window.location = "mainpageloggedin.jsp";
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
}
},
error: function(){
$("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax
Call. Please try again later.</div>");
//hide spinner
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
}
});
jsp code...
<%# include file="connection.jsp"%>
<%
String email=request.getParameter("loginemail");
String loginpass=request.getParameter("loginpassword");
ResultSet rs=st.executeQuery("select password from users where email='"+email+"'");
if(rs.next())
{
String password1=rs.getString(1);
if(password1.equals(loginpass))
{
session.setAttribute("email",email);
out.print("success");
}
else
{
out.print("invalid combination of email and password");
}
} else
{out.print("this account does not have information");
}
%>
I suspect it's related to the .search() or the type of data that is being returned.
First, always review console and network to see what data package is being sent and received for AJAX. If you're not getting what's expected back, you may need to look at your Java.
If you're getting whats expected, consider the following code.
$.ajax({
url: "login.jsp",
datatype: "text html",
type: "POST",
data: datatopost,
success: function(data){
console.log(data);
if(data.search("success") > -1){
console.log("Found 'success' in AJAX Package.");
$('#loginmessage').html(data);
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
} else {
$("#spinner").css("display", "none");
//show message
$('#loginmessage').html("Login Failed. " + data);
$("#loginmessage").slideDown();
}
},
error: function(x, stat, err){
$("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax. Please try again later. (" + stat +", " + err + ")</div>");
//hide spinner
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
}
});
In most cases, the AJAX will not error unless there is an error with the Web Server, so a 401, 404, or 500 error. So we want to make sure we're doing most of the work in in success, which is triggered when we get a 200 status.
So some text package is coming back. Based on your Java, this could be success, invalid combination of email and password, or this account does not have information. We can see what that package is upfront with console now. We then need to test it.
Since this is for AJAX, there is no way to test it for me. It's often best to use the simplest logical test. So != -1will work, yet > -1 is just as good and less confusing.
Can you try something like this
function crudPost(e) {
e.preventDefault();
let name = document.querySelector('#name').value;
let email = document.querySelector('#email').value;
let parameters = "name=" + name + "&email=" + email;
let xhr = new XMLHttpRequest();
xhr.open('POST', 'process.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.onload = function () {
if (this.status == 200) {
console.log(this.responseText)//get response from ur jsp
// do stuff
}
let parameters = "name=" + name + "&email=" + email; //pass values when send
}
xhr.send(parameters)
form.reset();
}
I just dont understand the problem u r facing in the code but try in this format it might help
Related
I am sending data to a PHP file using AJAX and depending on what data is sent, an alert() is either shown or not shown.
Inside the success function in AJAX, how do I detect if an alert box was shown?
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if(alert box was shown) {
// something happens
}else{
// alert box wasn't shown, something else happens.
}
}
});
send.php:
<?php
if($_POST['name'] == 'john') {
echo'
<script>
alert("Correct name");
</script>
';
}
It would be better to send back a result form the ajax request and show/don't show the alert in the success callback:
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if ( data == "show" ) {
// something happens
alert("Correct name");
} else {
// alert box wasn't shown, something else happens.
}
}
});
And on your server:
if ( $_POST['name'] == 'john' ) {
echo "show";
}
You could use json_encode() php function to return data from php.
This will be a better approach :
PHP :
if (!isset($_POST['name'] || empty($_POST['name']) {
die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
die(json_encode(array('return' => true)));
} else {
die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}
At this point, you will be allowed to check the returned values from JS and decide if you need to display the success alert or send an error message to the console (or do what ever you want...).
JS :
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
dataType: "JSON", // set the type of returned data to json
data: {name: called}, // use more readable syntaxe
success: function(data) {
if (data.return) { // access the json data object
alert("Congrats ! Your name is John !");
} else {
console.log("Sorry, something went wrong : " + data.error);
}
}
});
So, json_encode() allows to return easy accessible object from JS and will also allows you to set and display error messages easily in case the return is false.
Hope it helps !
PHP does not know if an alert has been shown, because in javascript the alert() function has no return value and no events which you could use to send an ajax request a click confirmation to the server.
One solution is to use a confirm() command inside the success event of your $.ajax(), which sends anothe ajax request if the user clicked "ok" or "cancel".
Something like this
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,
success: function(data) {
if (data == "show") {
var clicked = confirm("Correct name");
if (clicked == true || clicked == false) {
$.ajax({
url: "send.php?clicked=1",
});
}
}
else {
// Whatever to do than...
}
}
});
I have an application that displays a YouTube video and has a rate button to allow a user to like or unlike the video. On the click event 3 functions are called chained together through the success function of the ajax. The flow is this: ytvRate() -> getRating() -> showRating()
When I log the actions and results the response from getRating() does not have the value that I sent in ytvRate(). If I wait a while and refresh the page, the result of getRating() comes back correct. I call getRating() inside the success function of the ajax in ytvRate(). Doesn't that mean the function should not be called until a success response is received?
Here is an example of my logs:
rating sent: like
call get rating
this is my rating: none
call show rating
As you can see, the rating returned from the API is not correct - it should be the rating I just sent. Upon refresh the same call does return the correct rating... so, is there a delay or something to the data api updating the correct information? How can I get the correct rating on the same button click that sends the request?
Here are the functions (showRating does not seem relevant to the problem. It works fine as long as it gets the correct rating - which it is not.)
function ytvRate(id, rating, event){
event.preventDefault()
var apiKey = 'This is a valid key';
var client_id = 'This is a valid client id';
var redirect_uri = 'This is a redirect uri';
var scope = 'https://www.googleapis.com/auth/youtube';
var rateUrl = 'https://www.googleapis.com/youtube/v3/videos/rate?id='+id+'&key='+apiKey+'&rating='+rating;
if(getHash().access_token){
var token = getHash().access_token;
$.ajax({
type: "POST",
url: rateUrl,
beforeSend: function (request){
request.setRequestHeader('Authorization', 'Bearer ' + token);
},
success: function(data){
console.log('rating sent: '+rating);
getRating(id);
},
error: function(e) {
console.log(e);
}
});
} else{
window.location = 'https://accounts.google.com/o/oauth2/v2/auth?client_id='+client_id+'&redirect_uri='+redirect_uri+'&scope='+scope+'&response_type=token&prompt=consent&include_granted_scopes=false';
}
return false;
}
function getRating(id){
var getRatingUrl = 'https://www.googleapis.com/youtube/v3/videos/getRating?id='+id;
console.log('call get rating');
if(getHash().access_token){
var token = getHash().access_token;
$.ajax({
type: "GET",
url: getRatingUrl,
beforeSend: function (request){
request.setRequestHeader('Authorization', 'Bearer ' + token);
},
success: function(data){
var rating = data.items[0].rating;
console.log("this is my rating: " + rating);
showRating(rating, id);
}
});
}
}
function showRating(response, id){
console.log('call show rating');
numLikes(id);
if(response == 'like'){
document.getElementById("notliked").className = "hide";
document.getElementById("liked").className = "";
document.getElementById("like-btn").style.color = "#87CEFA";
document.getElementById("like-btn").setAttribute("onclick", "ytvRate('"+id+"', 'none', event)");
} else{
document.getElementById("notliked").className = "";
document.getElementById("liked").className = "hide";
document.getElementById("like-btn").style.color = "inherit";
document.getElementById("like-btn").setAttribute("onclick", "ytvRate('"+id+"', 'like', event)");
}
}
Edit:
Interestingly, if I call the youtube/v3/videos resource in a new method instead of youtube/v3/videos/getRating and access the statistics.likeCount, the number is instantly updated. Why can I not receive the user rating with the same efficiency?
After the discussion in the comments I suggest you to take a different approach. When ytvRate success you don't need to fetch getRating as you already know what is the rating set by the user.
The rate method is like a setter in regular programming language - if it successed (didn't throw an exception or returned an error) you can assume the current value is the one you set without fetching it again. This might be wrong assumption in multithreaded/distributed enviroments but might be ok in your case.
function ytvRate(id, rating, event){
...
success: function(data){
console.log('rating sent: '+rating);
showRating(rating, id);
}
...
}
I am trying to redirect to Homepage from SignIn Page after the validation of user credentials is done. The response is working perfectly fine.
On getting a successful response, I want to redirect to Homepage.
I am using Javascript for client side and PHP on server side.
I have tried all the possible solutions provided elsewhere on this site.
Here is the script for redirection on SignIn page:
$(document).ready(function(){
$("#SignInForm").submit(function(){
var em = document.getElementById("Email").value;
var ps = document.getElementById("Password").value; var obj; $.ajax({
url: 'WebService/SignIn.php',
type: 'post',
async: false,
data: {
Email: em,
Password: ps
},
dataType: 'json',
success: function(data) { var str = JSON.stringify(data); obj = JSON.parse(str);
if(obj.status == 1) {
window.location="Homepage.html";
} else { alert("Invalid Username/Password") }
},
error: function(xhr){ //alert("An error occured: " + xhr.status + " " + xhr.statusText ); alert("An error occured. Please Try Again"); }
})
}); }); </script>
A simple
window.location="Homepage.html";
should be suffice. But it isn't working.
Any help is appreciated.
window.location.href = "homepage.html" ?
The problem is related to the submit action:
By default, in fact, the submit action redirects to the url provided in the action (form parameter): https://developer.mozilla.org/en/docs/Web/API/HTMLFormElement/submit
Hence, in order to be able to perform an AJAX request, you have to first prevent the default action performed by the submit.
Just replace:
$("#SignInForm").submit(function(){
var em = document.getElementById("Email").value;
With:
$("#SignInForm").submit(function(e){ // <-- note the e
e.preventDefault();
var em = document.getElementById("Email").value;
Live example of what happens WITHOUT preventing the default action:
http://jsfiddle.net/hhjqqeza/
Live example of what happens by PREVENTING the default action:
http://jsfiddle.net/hhjqqeza/1/
Hello fellow programmers!
I'm fairly new to PHP/JavaScript and have to admit it is quite the learning experience, but I am enjoying it quite a bit. I have a bit of a problem when I'm saving to a Database using Ajax however. The save works perfectly fine, but instead of falling into my "success" code it falls into the "error" section and gives me a Status of 200. I'm not sure what the status 200 means and am confused because it does actually save to the Database correctly. Eventually what I want to do is use a JavaScript function to updated fields (when successfully saving to the DB), but right now I'm just trying to display a message to the user. Also, in the JavaScript code I have to have the single quotes (') around the ajax variables (i.e. url, type, dataType, etc.) for it to work. I've tried adding the single quotes around success and error and their associated functions to no avail. Thanks!
Javascript:
function SaveUserBlankAnswer(form) {
if (form.Answer.value != "") {
var answer = form.Answer.value;
var contentID = form.ContentID.value;
var userID = form.UserID.value;
$.ajax({
'url': 'Database/SaveUserBlankAnswer_db.php',
'type': 'POST',
'dataType': 'json',
'data': { ContentID: contentID, UserID: userID, Answer: answer },
success: function(){
alert('BOOSH!');
},
error: function(data){
alert(data.status);
}
});
}
}
PHP:
<?php
session_start();
include("DBConnection.php");
$duplicateCheck = "SELECT UserID FROM BlankAnswer WHERE ContentID = " . $_POST[ContentID] . " AND UserID = " . $_POST[UserID];
if ($duplicateResult = $mysqli->query($duplicateCheck)) {
$rowCount = $duplicateResult->num_rows;
if ($rowCount == 0) {
$SQL = "INSERT INTO BlankAnswer (UserID, ContentID, Answer)
VALUES('$_POST[UserID]', '$_POST[ContentID]', '$_POST[Answer]');";
} else {
$SQL = "UPDATE BlankAnswer SET Answer = '" . $_POST[Answer] . "' WHERE ContentID = '" . $_POST[ContentID] . "' AND UserID = '" . $_POST[UserID] . "'";
}
$mysqli->query($SQL);
}
$mysqli->close();
?>
Use Jquery serialize method to create the form data for submission as you are not escaping the data on directly passing it.
Return 1 on success and 0 in failure from PHP script. No data is bad. Your POST request has no response, so maybe it thinks as an error. and the error in callback is for AJAX error. You can pass 0 or any message on DB level error.
function SaveUserBlankAnswer(form) {
//do validations here
var formData = $('#formId').serialize();
$.ajax({
type: "post",
url: "Database/SaveUserBlankAnswer_db.php",
dataType:"json",
data: formData,
success: function (data) {
if(data.status === "1") {
//Show success
} else if(data.status === "0") {
// alert for error on saving to DB
}
},
error: function(error){
alert('AJAX ERROR');
}
});
}
Hope it helps
Happy Coding !!!
On the event of a form submit, I have a jquery ajax function that queries for the amount of data uploaded from a file that I can use in making a progress bar. This is my js file:
var submitted = '';
var counter = 0;
$('#webfileuploadform').submit(function(){
if(submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
update_progress_bar();
function update_progress_bar(){
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
counter ++
console.log('hit success ' + counter);
},
complete: function(jqXHR, status){
if (status == 'success'){
console.log('hit complete', status == success')
} else {
console.lot('hit complete', status == something else')
}
}
});
setTimeout(function(){update_progress_bar()}, freq);
}
submitted = 'submitted'; // marks form as submitted
});
So, the user will use the form to select the file then click submit. This all happens just fine. The form submits, the file is uploaded, and the progress shows just fine when I open my ajax view in a separate tab and keep refreshing it. What I don't understand is why the update_progress_bar function runs once until I stop the page. I'll upload a file but until I click the 'x' on my browser I won't get any of the 'hit success' in my console. After I hit stop, the console spits out the 'hit success ' plus the counter. But I shouldn't have to hit stop to do this. I need this to work when the file is uploading.
Any ideas what my problem is?
**
EDIT
**
Not sure if it makes a difference, but I am doing all this on a django development server. Which I think shouldn't have a problem with two XMLHTTPRequests in the same session.
Try this:
var $submitted = '';
$('#webfileuploadform').submit(function(){
if($submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
update_progress_bar();
function update_progress_bar(){
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
console.log("hit success");
},
complete:function(jqXHR, status) {
if (status == 'success') {
setTimeout(update_progress_bar, freq);
}
}
});
}
$submitted = 'submitted'; // marks form as submitted
});
As it stands, the code looks good to me. I would add some more console logging to make sure the ajax call is returning with the status you expect:
complete:function(jqXHR, status) {
console.log('got to complete, status: ', status);
if (status == 'success') {
console.log('status is success, calling setTimeout.');
setTimeout(update_progress_bar, freq);
}
}
In the ajax function I set the async setting to false:
$.ajax({
async: false,
...
});
This has solved the problem. I have no idea how. From what I understand, this setting forces the ajax request to wait until all other http requests are finished before allowing it to continue. With that being the case, I have no idea how this works. I'll keep from answering my own question in case someone knows why this is working this way...