Syntax error in ajax - javascript

I got this script from the web and I've manipulated it to fit my way but it tells me syntax error
$(document).ready(function(){
$Addr = localStorage.getItem('eaddress');
$email7 = $('#email7')
if ($Addr !== null) {
$('#email7').val($Addr);
}
if ($Addr != '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
}
});

Missing a bunch of bracing:
$(document).ready(function() {
var $Addr = localStorage.getItem('eaddress');
if ($Addr) {
$('#email7').val($Addr);
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if (result === "ok") {
window.location = 'page.html';
}
}
});
}
});
Not absolutely required, but I also added var to local variables, simplified and combined and if test and removed a local variable not being used.
In the future, you can paste a block of code into http://jshint.com/ and it will show you where you've gone wrong. It also makes other recommendations for robust code.

Close all semicolons and braces: add });} before very last });
Result:
$(document).ready(function () {
$Addr = localStorage.getItem('eaddress');
$email7 = $('#email7')
if ($Addr != null) {
$('#email7').val($Addr);
}
if ($Addr !== '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function (data) {
$('#log_msg').html(data);
var result = $.trim(data);
if (result === "ok") {
window.location = 'page.html';
}
}
});
}
});

Related

How to use javascript variable within another javascript script?

So in an earlier part of my code, within tags I set the value of variable charge to a different link.
How do I use the value of this variable in the later javascript as 'url: charge' does not work. Do I need to write the variable differently.
'Url: chargesilver.php' works, but 'url: charge' doesn't.
<script>
function setmembershipayment(){
if (usermembershipchoice == "Silver") {
var charge = "chargesilver.php";
alert(charge);
} else if (usermembershipchoice == "Gold") {
var charge = "chargegold.php";
alert(charge);
} else if (usermembershipchoice == "Platinum") {
var charge = "chargeplatinum.php";
alert(charge);
} else {
alert("ERROR");
} // THE MISSED BRACKED!! ;)
}
</script>
.
<script>
$.ajax({
type: "POST",
url: charge,
data: form.serialize(),
success: function(response){
</script>
The easiest way is to make your function return the charge you want to use.
function getMembershipPayment(){
if (usermembershipchoice == "Silver") {
return "chargesilver.php";
} else if (usermembershipchoice == "Gold") {
return "chargegold.php";
} else if (usermembershipchoice == "Platinum") {
return "chargeplatinum.php";
} else {
alert("ERROR");
return "some default value"
} // THE MISSED BRACKED!! ;)
}
$.ajax({
type: "POST",
url: getMembershipPayment() // returns the value of charge,
data: form.serialize(),
success: function(response){}
})
Perhaps call the function from url to return the correct string value. And perhaps use a switch instead of an if/else structure as it's a little easier to read.
function setmembershipayment(usermembershipchoice) {
switch (usermembershipchoice) {
case 'Silver': return "chargesilver.php";
case 'Gold': return "chargegold.php";
case 'Platinum': return "chargeplatinum.php";
default: console.log('error'); break;
}
}
$.ajax({
type: "POST",
url: setmembershipayment(usermembershipchoice),
data: form.serialize(),
success: function(response) {
...
}
});
charge is not global.
Its scope is just within the function
Declare it outside the function
var charge = ''
function setmembershipayment(){
....
Sample
<script>
var charge = ''
function setmembershipayment(){
if (usermembershipchoice == "Silver") {
charge = "chargesilver.php";
alert(charge);
} else if (usermembershipchoice == "Gold") {
charge = "chargegold.php";
alert(charge);
} else if (usermembershipchoice == "Platinum") {
charge = "chargeplatinum.php";
alert(charge);
} else {
alert("ERROR");
} // THE MISSED BRACKED!! ;)
}
setmembershipayment()
$.ajax({
type: "POST",
url: charge, // OR Just return it from the function here and make sure there is a default value
data: form.serialize(),
success: function(response){
</script>
OR Just return it from the function and make sure there is a default value

ajax loading indicator stopped in between

I am saving data on a save button click that calls ajax and passing json data to a controller method but when we save it loading starts and suddenly stop though the data is not saved.
It is not working I have tried it in all way but not working please help me on this.
<button type="button" id="saveDeleg" class="btn_reg_back btnmainsize btnautowidth btngrad btnrds btnbdr btnsavesize " aria-hidden="true" data-icon="">#Resources.Resource.Save</button>
$('#saveDeleg').click(function() {
var response = Validation();
if (!response) {
return false;
}
$("#overlay").show();
$('.loading').show();
if ($('#organName').val() == '') {
$('#validorganisation').show();
return false;
} else {
$('#validorganisation').hide();
}
//Contact name
var SubDelegation = $('#subdelegation').is(':checked');
var CopyNotification = $('#copynotification').is(':checked');
var ArrangementId = $("#ArrangementId").val();
var paramList = {
ArrangementId: ArrangementId,
ArrangementName: $('#arrangName').val(),
OrganisationName: $('#organName').val(),
OrganisationId: $('#OrganisationId').val(),
ContactName: $('#contactName').val(),
ContactId: $('#ContactId').val(),
SubDelegation: $('#subdelegation').is(':checked'),
CopyNotification: $('#copynotification').is(':checked'),
ContactType: $('#ContactType').val(),
SelectedTypeName: $("input[name$=SelectedType]:checked").val()
};
setTimeout(function() {
$.ajax({
async: false,
type: "POST",
url: '#Url.Action("SaveDelegation", "Structures")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paramList),
processdata: true,
success: function(result) {
//stopAnimation()
paramList = null;
if (result == 0) {
window.location.href = '../Structures/MyDelegationArrangement';
} else if (result == 1) {
window.location.href = '../Structures/CreateDelegation';
} else if (result == 2) {
window.location.href = '../Home/Error';
} else if (result == 3) {
window.location.href = '../Account/Login';
} else {
//validation message
alert('Error');
}
},
error: function() {},
complete: function() {
$("#overlay").hide();
$('.loading').hide();
}
});
}, 500);
});
The problem with the loading indicator is because you used async: false which locks up the UI. Remove that setting.
Also note that if the data is not being saved I would assume that your AJAX call is returning an error. If so, check the console to see the response code. It may also be worth putting some logic in the error callback function to give you some information on whats happened, as well as inform your users about what to do next.

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

if return data is null alert ajax success

How to show can alert message in the ajax return request if the return request does not contain any data !!!
i have tried in the ajax success but nothing is working!
This is my script ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (returnedData) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
// how can i do something where so if the return value is null alert
}
}
});
return false;
});
});
</script>
console.log(returnedData) output
Do anyone knows how i can make an alert when the return value is null !!!
how about?
success: function (returnedData) {
if(!returnedData) alert('message');
}
Try this one....
< script >
$(document).ready(function() {
$("#searchform").on('submit', function(e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function(returnedData) {
if(returnedData != "") { $("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert("Data is Null");
}
}
}
});
return false;
});
}); < /script>
success: function (returnedData) {
if(!!returnedData && returnedData != null) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert('No data');
}
}
Or this:
success: function (returnedData) {
if(returnedData && returnedData.length) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert('No data');
}
}
success: function (returnedData) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
// check whether your returned data is null
if(returnedData == null)
{
alert("Your message");
}
}
Replace it here --
success: function (returnedData) {
if($.trim(returnedData.length))
$("#displayResult").html($(returnedData).find("#displayResult").html());
else
alert('Nothing got');
}
}
May be you would like to do this:
success: function (returnedData) {
var data = $(returnedData).find("#displayResult").html() || ""; // this won't alert but
$("#displayResult").html(data); // sets a value if that's null
}
I also wanted to do the same thingy. You can try the following code fragment. It checks your callback data`s length. Depends on it, you can trigger your success message etc. If the length of return data is zero which means NO DATA, you can trigger the message relevant to that scenario.
success: function (returnedData) {
var sizeOfData = returnedData.length; // check the size of return data, be it zero means NO DATA
if (sizeOfData != 0) {
alert('Data exists !! Success !!');
}
else {
alert('No Data !! Error !!');
}
You can try as below :
if (returnedData == 'null' || returnedData == null){
alert('I am null');
}

jQuery AJAX works on mobile safari, but not a UIWebView?

I have a basic jQuery ajax function to log the user in via a UIWebView. However, for some reason it returns blank when it's in a UIWebView. It works fine in mobile safari, and chrome and firefox on my computer.
Here's my code:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});
The theRetrievedData just returns blank on the alert.
Please help!
PS: The app is called "Dudles" in the app store (it's free) if you want to try to login. You will get a blank message from the alert.
Can you post your PHP code as well?
I refactored the code you wrote into how I would write it just to see if I could spot any bugs, and nothing seemed glaringly incorrect. Here is what I have so far:
$(document.body).on('click', '#login_button', function () {
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: $(this).closest('form').serialize(),
success: function (response) {
var delimiter = "?!?success?!?";
var isSuccessful = response.indexOf(delimiter) !== -1;
if (!isSuccessful) {
// handle error
return;
}
$('#content').fadeOut(500, function () {
location = response.split(delimiter)[1];
});
}
});
});
try to send ajax request with async:true, like this:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
async:true,
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});

Categories

Resources