$.ajax({
url: "NewUserRegistrationServlet",
type: "post",
cache: false,
data : "username="+username+"&password="+encodeURIComponent(pswd)+"&email="+encodeURIComponent(email),
dataType:"xml",
timeout: 3000,
success: function(data) {
var xml_node = $('ResultSet',data);
var status = xml_node.find('result').text() ;
var result = xml_node.find('status').text() ;
if( (result > 0) && ( status == 'SUCCESS') ) {
alert("This Statement is getting executed");
//window.location.replace("login.jsp"); // Not Working
//window.location.href = 'http://localhost:8080/MyProj/login.jsp'; // Not Working
window.open = ('login.jsp','_top'); // Not Working
}else{
$("#RegisErr").siblings("p").remove();
$("#RegisErr").after("<p>User Registration failed! Please Try Again.</p>");
}
},
error: function(xhr, status, text) {
$("#RegisErr").siblings("p").remove();
$("#RegisErr").after("<p>User Registration failed! Please Try Again.</p>");
}
});
What i am doing wrong
OnSubmit -> Validation of form // Working Fine
If Valid -> Do Ajax Request // Working Fine
On Success of Ajax -> Redirect to other JSP Page // Not Woking
EDIT
Screenshot Chrome Debugger
Solved
windows.location = "login.jsp"
Thanks Everyone for your help.
To make your method work i.e. one of :-
1. window.location.replace("http://stackoverflow.com");
2. window.location.href = "http://stackoverflow.com";
The browser is still submitting the form after your code runs.
Add return false; to the handler to prevent that.
Otherwise, use just window.location = "http://stackoverflow.com";
Refer to this post ( window.location.href not working ) for further clarification. If you still face a problem, tag me again. I will write a detailed answer for you.
This comment is the code for your solution to work - https://stackoverflow.com/a/6094213/1366216
Please trim all white spaces from result. you should write following line before if block.
if(Number(result)>0 && status.trim()==="success")
{
//do anything you want
}
Related
i'm trying to show error message from server to client site using ajax , but it wont work when i make a function for error messages ,
#other codes for saving the post,there is not error
success_meesage = f'success'
return JsonResponse({'success':'success','success_msg':success_meesage})
else:
error_message=f'there is an error into your two dates please make sure check in smaller than check out'
return JsonResponse({'success':False,'error_taken':True,'error_message':error_message})
my ajax code
const form = document.getElementById('post-form')
form.addEventListener("submit",submitHanler);
function submitHanler(e){
e.preventDefault();
$.ajax({
type:'POST',
url:"my-url",
data:$("#post-form").serialize(),
dataType:'json',
success:successFunction,
error:errorFunction,
})
}
function successFunction(data){
// console.log(data)
if(data.success='success' && data.success_msg){
form.reset();
alertify.success(data.success_msg)
}
}
function errorFunction(request, status, error){
console.log(request.responseText)
if(error.error_taken == true){
alertify.alert('warning !','message')
alertify.alert(error.error_message,function(){
});
}
}
}
i also tried this : function errorFunction(jqXHR, exception)
it shows nothing as well , i tried many ways but none of them worked !
thank you in advance ..
You are returning a JsonResponse, but with status code 200, so that means that, according to the status code, the request was successful.
We thus can return a JsonResponse with a status code outside the 200-399 range, for example a 400 HTTP response:
if some_condition:
success_meesage = f'success'
return JsonResponse(
{'success':'success','success_msg':success_meesage}
)
else:
error_message=f'there is an error into your two dates please make sure check in smaller than check out'
return JsonResponse(
{'success':False,'error_taken':True,'error_message':error_message},
status=400
)
I am working on a site built with Code Igniter. It is showing a script error in the console but not the path.
I am having more than 100 files which consists of small or big scripts. Now how I am able to know from which file the error is coming from?
Anyone aware from any tool or any easy method I can try with my site?
Here is my site for reference.
There is error in your ajax , function name as login , In your success response there is missing closing bracket.
Replace code as following :
function login(){
//alert("hhh");
var name = $('#name').val();
// alert(name);
var password = $('#logpassword').val();
//alert(password);
if(name.trim() == '' ){
$('#errorname').html('<span style="color:red;">Please Enter Your Name.</p>');
$('#inputName').focus();
return false;
}else if(password.trim() == '' ){
$('#errorpassword').html('<span style="color:red;">Please Enter Your Password.</p>');
$('#password').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'http://www.edushikshaguide.com/frontend/system_login',
data:{name:name,password:password},
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(data){
console.log('success');
}
});
}
}
}
In any decent browser you just need to click:
Error here is in line 346, column 9, highlighted for your convenience:
In any case, browser-based JavaScript is a client-side language. Neither PHP nor CodeIgniter have anything to do with it unless you use either to generate JavaScript code dynamically.
when i enter the wrong details and run it. it pops up with the error message, but if i then enter the correct details and click run it again. the sign in button changes to "Connecting..." as it should but then nothing else happens
$(document).ready(function() {
var width = ( $(".main").width() - 5);
if (width < 300) {
$(".logo-img").css({"width":width});
};
$("#error").hide();
$(function() {
$('#login').on('click', function(e){
e.preventDefault();
var token = $('#token').val();
var username = $('#username').val();
var password = $('#password').val();
var remember = $('#remember:checked').val();
$.ajax({
url: 'core/functions/ajaxLogin.php',
method: 'POST',
data: { 'username' : username,
'password' : password,
'remember' : remember,
'token' : token },
dataType: 'html',
cache: false,
beforeSend: function() { $('#login').val('Connecting...') },
success: function( data ) {
if (data == 'success') {
setTimeout( "window.location.href='backorderbook';", 500 );
} else if( data == 'userorpass' ) {
$('#error').fadeIn();
$('#error_message')
.html('username or password were entered incorrectly');
$('#error').delay(3500).fadeOut();
$('#login').val('Sign In');
};
}
});
});
});
});
Reason behind working once.
when your ajax fired, first thing to do is show connecting.. then when you get response which is data your statement says
if data == success //redirects
elseif data == userpass //show you have invalid username/password and clear html
So what if your data is not succes / userpass
it will just run your ajax beforeSend() and not will remove connecting that seems to you running once.
I recommend that your data should be an object and check if there's an error with the message on it , in short have it on your backend and just jquery show that message
There is a token generated when the login page is loaded and sent with the Ajax. But my PHP token system doesn't like the same token being sent over and over and blocks the request.
run your function with Fiddler .. and/or add the error parameter to your ajax... odds are your web request isn't a success.
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
So I have this JavaScript which works fine up to the $.ajax({. Then it just hangs on the loader and nothing happens.
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
alert('This works');
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
Try replacing:
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
with:
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success. The complete event is triggered even in the case of an exception.
Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.