outputting response to browser - javascript

am posting half code coz the rest is working.
just need to see if wat i want can work
Question: is it possible to send alert() errors to browsers. because alert() just output errors in popup window up the browser
so i want to do it like in success function where u do
$('#resp').text(response.feedback); and send response to html like <div id="resp"></div>
so my main question is it possible to send alert() errors to browser than popup up on browser.
to send it in browser and call it with id like above success function
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
alert("Text-field is empty.");
return false;
}
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},

if I understood you correctly:
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
$('#resp').text('TextField is Empty');
return false;
},
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},

You will need to send some flag/message back to the browser in your server response. Then check for that flag/message, and present an alert() in your client side code.
e.g.
function showMessage(msg){
alert(msg);
}
//in your success bit
success: function(response){
if(response.someFlagYouSet == "NO_SUPPLIES_LEFT"){
showMessage("There are no supplies left... sorry");
}
}

Rather than
alert("Text-field is empty.");
do
$('#resp').text("Text-field is empty.");

Related

javascript not show results on success

I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.

jquery ajax post sends me to action page and wont show result data

I have the following script for making Ajax/Jquery post request.
The script works (I get correct response on back-end).
But I cant seem to make any alerts, so I think there is some problem with the success function.
Do you guys see any obvious mistakes?
The browser gets the correct responses (Inspect webpage in chrome).
<script>
$(document).ready(function() {
var frm = $('#registerform');
frm.submit(function(x) {
x.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/v1/register',
data: frm.serialize(),
crossDomain: true,
success: function(data){
if(data == 200){
alert("successfully registered");
$('#alert').append("successfully registered");
}
if (data == 400){
alert("email or password empty");
}
if(data == 403){
alert("passwords do not match");
}
}
});
});
});
</script>
You are trying to compare your data that you are getting back from your request with HTTP status codes. So, what you need do is put in some additional parameters in your success function. Here is a nice Fiddle that I seen on another stackoverflow question that might help you out. http://jsfiddle.net/magicaj/55HQq/3/.
$.ajax({
url: "/echo/xml/",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType:"text xml",
success: function(xml, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
}
});
The xhr.status is what you will need to compare against instead of your data.
When playing with console.log i found out that sending res.sendStatus(200) from the backend results in the client (browser) getting the response "OK". So when changing to res.json on the server it works...

jQuery AJAX Page Redirection Error

$.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
}

AJAX request confusion in jQuery

I am unable to understand that why the jquery AJAX is not fetching data from the ajax page.
Can someone please help.
<script type="text/javascript">
$(function() {
$('#lms_id').change(function(){
if ($(this).val() != "") {
// alert("1");
} else {
// alert("0");
}
});
$('#lms_user_role_id').change(function(){
if (($(this).val() == "7" || $(this).val() == "8")) {
$('#t_lms_dealers').show();
} else {
$('#t_lms_dealers').hide();
}
});
});
function loadAjax(message)
{
//alert(message);
//$.get("<?php echo $App['wwwroot'].'er.php' ?>?activity="+message);
$.get("http://www.abc.loc/er.php");
}
</script>
In loadAjax function, alert is alerting fine, but only the AJAX part is not working.
How do you know it is "not working"?
$.get("http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php");
Even if it did, this statement would accomplish nothing. You need to put a handler in there:
$.get(
"http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
function (data) {
alert("Retrieved :"+data);
}
);
You should also use some kind of in browser developer tool (eg, firebug) that will allow you to trace the request in real time. Finally, the plain jquery get lacks an error handler; you might want to instead use:
$.ajax ({
url: "http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
success: function (data) {
alert(data);
},
error: function (xhr, err, code) {
alert("Error: "+err);
}
});
And read the query documentation:
http://api.jquery.com/category/ajax/
if i am not wrong 2nd possibility is may be you are trying "cross domain ajax call", if yes then you have to set header "Access-Control-Allow-Origin" and "crossDomain: true" for $.ajax call.

jQuery ajax: how to destroy submit if ajax validation fails?

I have email field in user's settings area. All emails are unique, of course, so I need to check is email not used already by someone else before submitting the form.
Here is the code:
var email = $("input#email-id").val();
$("#form-id").submit(function(){
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
}
});
});
So, if data is not 'ok' it must destroy submitting the form because if() returns false, but it doesn't and the form submits as usual and even alert doesn't appear!
I've checked ajax answer and it works fine (returns 'user_already' if email is used).
So what I did wrong?
Thanks!
Since ajax is async by nature you cannot do that. If you really want to do that you can submit the form inside the success handler. Try this.
function submitHandler(){
var email = $("input#email-id").val();
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
else{
//Once the data is ok you can unbind the submit handler and
//then submit the form so that the handler is not called this time
$("#form-id").unbind('submit').submit();
}
}
});
return false;//This will prevent the form to submit
}
$("#form-id").submit(submitHandler);
It's because the Ajax request to check the email is asynchronous. It will not complete before the submit event handler is finished. You'd have to do something like this:
$('#form-id').submit(function() {
if($(this).data('valid')) {
//you've already validated, allow the form to submit
return true;
} else {
//send an ajax request and wait for the response to really submit
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data == 'ok') {
//submit the form again, but set valid data so you don't do another Ajax request
$('#form-id').data('valid', true);
$('#form-id').submit();
} else {
alert("Email is used already");
}
}
});
return false;
}
//clear the validation flat
$(this).data('valid', false);
});
There's an accepted answer but I thought I'd share another way to do this.
You can use an extra parameter with the .trigger() function to first test the user's email, and if it comes back available then re-trigger the submit event but set a flag to not check the username:
$("#form-id").submit(function(event, forceSubmit){
//the normal submit will not have the extra parameter so we need to initialize it to not throw any errors,
//typeof is great for this since it always returns a string
if (typeof(forceSubmit) == 'undefined') { forceSubmit = false; }
//now check if this is a normal submit or flagged to allow submission
if (forceSubmit === false) {
var $form = $(this);
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
} else {
$form.trigger('submit', true);
}
}
});
//since this submit event is for checking the username's availability we return false to basically: event.preventDefault(); event.stopPropagation();
return false;
}
});
.trigger(): http://api.jquery.com/trigger
In your code you have two functions. One is the function passed to submit:
$("#form-id").submit(function() {
// code
});
The other is the function passed to the success handler of the AJAX call:
success: function(data) {
// code
}
You are returning false from the second function. This means that when the first function returns, it is not returning false. But the form submission is stopped, only if the first function returns false.
What you should do is to make the function passed to submit always return false and handle submission programmatically.
This code helps you to achieve this:
var submitHandler = function() {
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data) {
if (data != 'ok') {
alert("Email is used already");
// no need to do anything here
} else {
// success, we should submit the form programmatically
// first we de-attach the handler, so that submitHandler won't be called again
// and then we submit
$("#form-id").unbind('submit').submit();
// now we reattach the handler, so that submit handler is executed if the user
// submits the form again
$("#form-id").submit(submitHandler);
}
}
});
// always return false, because if validation succeeds, we will submit the
// form using JavaScript
return false;
};
$("#form-id").submit(submitHandler);
I already +1 #ShankarSangoli because he got it right however, I don't feel its 100% complete as there is also an error state that can occur upon network issues or server fault.
$('#form-id').submit(function(ev) {
ev.preventDefault(); // cancels event in jQuery typical fashion
$.ajax({
url: "/ajax/email",
data : { email: $("input#email-id").val()},
success : function(d) {
if (d !== 'ok') {
alert('email in use');
}
},
error : function(a,b,c) {
// put your error handling here
alert('a connection error occured');
}
});
});
There are even better ways to handle this as I've written some great form plugins for jQuery that are HTML5 compliant and rival jQuery tools for ease of use.
You can see an example here -> http://www.zipstory.com/signup
Happy coding.
If JSON is involved, the returned data is in data.d - see http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ for an explanation.

Categories