jQuery trying to handle ajax failure and sucess not working - javascript

I had a working jQuery ajax call but i wanted to check the result of the request so i added
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
}
but this is not working and made my whole function stop working even.so here is the whole function,can some one tell me what am doing wrong`
function addGoal() {
var description = $('.description').val();
var measure = $('.measure').val();
if( description.trim() && measure.trim() ){
if(window.confirm("Are you sure? You can't edit or remove goal(s) you have added here.")==true) {
$.ajax({
url: '${g.createLink( controller:'review', action:'saveGoal', params:[id: params.id] )}',
data: {
"description": description,
"measure": measure
},
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
}
type: 'POST'
});
}
}else {
showErrorMessage("Description and Measure fields cant be empty");
}
}`
when i remove the success it works as i expected it to.And if it matters am using grails

There is a syntax error which is a missing comma
function addGoal() {
var description = $('.description').val();
var measure = $('.measure').val();
if( description.trim() && measure.trim() ){
if(window.confirm("Are you sure? You can't edit or remove goal(s) you have added here.")==true) {
$.ajax({
url: '${g.createLink( controller:'review', dataType: "json", action:'saveGoal', params:[id: params.id] )}',
data: {
"description": description,
"measure": measure
},
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
type: 'POST'
});
}
}else {
showErrorMessage("Description and Measure fields cant be empty");
}
}`
This will fix the issue

Related

confirmation dialog isn't showing

document.querySelector('#select').addEventListener("change", function() {
var confirm = confirm("Do you want to update data?");
if (confirm == true) {
if (this.value == "1") {
$.ajax({
url: "update.php",
type: "POST",
data: {
id: <?php echo $row['serial']?>,
type: "pending"
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
alert("Successfully updated");
location.replace("../deposit/");
}
else if(dataResult.statusCode==201){
alert("Something went wrong");
}else{
alert("Everything went wrong");
}
}
});
}else if(this.value == "2"){
$.ajax({
url: "update.php",
type: "POST",
data: {
id: <?php echo $row['serial']?>,
type: "succeed"
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
alert("Successfully updated");
location.replace("../deposit/");
}
else if(dataResult.statusCode==201){
alert("Something went wrong");
}else{
alert("Everything went wrong");
}
}
});
}else if(this.value=="3"){
$.ajax({
url: "update.php",
type: "POST",
data: {
id: <?php echo $row['serial']?>,
type: "canceled"
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
alert("Successfully updated");
location.replace("../deposit/");
}
else if(dataResult.statusCode==201){
alert("Something went wrong");
}else{
alert("Everything went wrong");
}
}
});
}else{
console.log("Update canceled");
}
}
});
I added a confirmation dialog while user changes option. When I run the code, and changed option I am not getting any confirmation dialog but, when I was working without confirmation dialog everything was working fine. Why it's happening? I got error in console Uncaught TypeError: confirm is not a function at HTMLSelectElement.<anonymous> I was looking at w3schools courses but, i am unable to understand anything
You can use window.confirm as it is a global function exposed to Window.
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
You can also change your code to just this (you don't need the var confirm. This is also the issue, since you use confirm twice, but for different purposes.
if (confirm("Do you want to update data?")) {
If you do want the variable, use the standard naming convention for booleans, which is to add "is", "has","can" or "should" before the variable name:
var hasConfirmed = confirm("Do you want to update data?");
if (hasConfirmed == true) {
You should avoid using the name of HTML and Window objects and properties:
https://www.w3schools.com/js/js_reserved.asp
don't use confirm use ConfirmDialog or something!

alert is not working on error message

// Alert is not working on error message , I want to insert only few 4 issue after that it should not work.
success: function(msg, String, jqXHR) {
window.location = 'home.html';
$("#result").html(msg, String, jqXHR)
alert("Data Uploaded: ");
if (msg.success == 'Error') {
alert("Please close the previous issue");
window.location = 'home.html';
}
// here (msg.success=='Error') is not working i want to display this message - "Please close the previous issue" on this .
Hope this works for you.
$(document).ready(function(){
$('#your_form').submit(function(event) {
event.preventDefault();
dataString = $("#your_form").serialize();
$.ajax({
type: "post",
url: "post.php",
dataType:"json",
data: dataString,
success: function (response) {
if(response.status === "success") {
// do something with response.message or whatever other data on success
alert("Data Uploaded: ");
window.location='home.html';
} else if(response.status === "error") {
alert("Please close the previous issue");
window.location='home.html';
}
}
})
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Redirect somewhere else upon JSON success?

My Code:
<script>
$('#form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
}
});
return false;
});
</script>
The FORM:
<form id="form" class="center" action="http://localhost/products/index.php?route=checkout/cart/add" method="post">
<input type="text" name="cname">
<input type="hidden" name="product_id" value="51">
<input type="submit">
</form>
When the form presses submit it goes to the action page which is just a JSON success message, what I want to do is redirect to a different page other than the action page, but my code does not seem to be working?
What exactly is wrong with my code, can someone help me fix it?
I would be so grateful if you could help me out, many thanks!
You aren't posting any data which makes a POST fairly useless .
Also you have no error handler either
Try:
$(function(){
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function(){
// do something when request fails - See $.ajax docs
}
})
return false;
});
});
You can used this code for error handling! You also check this question on stackOverflow for redirecting to another page using jQuery/JavaScript:
click here
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
},
});
});
You need to have separate error and success handlerS like below.
In success method you can redirect to other pages/sites (window.location.href = "http://www.EXAMPLE.com";)
var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully, //Separate method for handling success
error: showError //Separate method for handling error
};

why my ajax call is not getting generated as my js file which contain ajax is included inside an iframe?

In below code , url is not called actually ajax is not working is there any jquery conflict or else ..
var request = $.ajax({
url: "https://subscribe.php",
data: params,
type: 'post',
dataType: 'json',
success: function(data) {
if (!data == '') {
alert(data);
if (data.success == 1) {
alert('Thank you for subscribing.');
return false;
} else {
alert(data.message);
return false;
}
}
}
});
thanking you in advanced...
Ajax is an asynchronous call and $.ajax() does not returns any response.
Please see the http://api.jquery.com/jquery.ajax/ link to find out jQuery.ajax() usage.
Your code should be :
$.ajax({
url: "https://subscribe.php",
data : params,
type : 'post',
dataType: 'application/json',
success: function(data){ // this is a call back function.
if (!data == ''){
alert(data);
if (data.success == 1){
alert('Thank you for subscribing.');
// Do your call
}else{
alert(data.message);
return false;
}
}
}
});
You can use many other options in jQuery.ajax(). To know the detailed usage go to above mentioned URL.

Jquery and ajax call being fired multiple times

Hi I'm making an ajax call to my php side to add or edit in the database. I return three options depending on what was completed. After debugging with firebug I see that after each submit of with add/edit/delete there is more than one call to the php side (doubles each time) I've done a lot reading of trying to unbind and bind which only allows the event handler to execute once but once I do that the submit buttons don't work until the page is reloaded which isn't what I want. Please help!
Javascript page:
//$('#addAgeGroupForm').trigger("reset");
//$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen:false,
maxWidth:600,
maxHeight: 500,
width: 500,
height: 350,
async: false,
close: function(){
$('#addAgeGroupForm').trigger("reset");
$.ajax({
type: "GET",
url: "/Ajax/ajax_reset_id.php",
async: false,
success: function(html){
$("#responce_event").html(html);
}
});
}
});
$("#addAgeGroup").on("click", function()
{
$("#dialog").dialog("open");
});
$("#addAgeGroupForm").submit(function(e)
{
e.preventDefault();
var postData = jQuery(this).serialize();
var data = "";
$("#dialog").dialog("close")
$.ajax({
type: "POST",
url: "/Add/AddAgeGroups.php",
dataType: 'json',
async: false,
data: postData,
success: function(result){
data = result;
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
if (data==1)
{
alert("Error: Please fill in all fields");
}
else if(data==2)
{
alert("Error: Duplicate Age Group entry for this Meet");
}
else
{
alert(data);
//alert("success");
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
}
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
$('[id^="editAgeGroup"]').submit(function(e)
{
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "/Get/GetAgeGroup.php",
async: false,
dataType: 'json',
data: editData,
success: function(data){
var form = document.forms['addAgeGroupForm'];
form.id.value=data.id;
form.agegroup.value=data.agegroup;
form.abbrev.value=data.abbrev;
form.sort.value=data.sort;
}
});
$("#dialog").dialog("open");
});
$("#dialog2").dialog({
autoOpen:false,
maxWidth:600,
maxHeight: 500,
width: 500,
height: 300,
async: false,
close: function(){
$('#deleteAgeGroupForm').trigger("reset");
$.ajax({
type: "GET",
url: "/Ajax/Delete/ajax_delete_ageGroup.php",
async: false,
success: function(html){
$("#responce_delete").html(html);
}
});
}
});
$('[id^="deleteAgeGroup"]').submit(function(e)
{
e.preventDefault();
var deleteData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "/Get/GetAgeGroup.php",
dataType: 'json',
data: deleteData,
success: function(data){
var form = document.forms['deleteAgeGroupForm'];
var id = data.id;
var name = data.agegroup;
form.age_group_id.value = data.id;
$.ajax({
type: "GET",
url: "/Ajax/Delete/ajax_delete_ageGroup.php?id="+id+"&name="+name,
async: false,
success: function(html){
$("#responce_delete").html(html);
}
});
}
});
$("#dialog2").dialog("open");
});
$("#deleteAgeGroupForm").submit(function(e)
{
e.preventDefault();
var postData = jQuery(this).serialize();
var editData = jQuery(this).serialize();
$("#dialog2").dialog("close")
$.ajax({
type: "POST",
url: "/Get/GetAgeGroup.php",
dataType: 'json',
async: false,
data: editData,
success: function(data){
var id = data.id;
//alert(data.id);
//alert(data.schoolname);
$.ajax({
type: "Get",
url: "Delete/DeleteAgeGroup.php?id="+id,
dataType: 'json',
async: false,
data: postData,
success: function(data){
//alert(data);
//alert("success");
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}});
});
/******************/
})
function updateTable()
{
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
}
PHP side:
session_start();
if($_SESSION["logged_in"] == 0)
header("Location: ****");
else if($_SESSION["type"] == "general")
header("Location: ****");
else
{
$agegroup = addslashes($_POST['agegroup']);
$abbrev = addslashes($_POST['abbrev']);
$sort = addslashes($_POST['sort']);
$id = $_POST['id'];
$managerID = $_SESSION["manager_id"];
$meetID = $_SESSION["meet_id"];
$db = mysqli_connect("****", "****", "****","****");
if(!$db){
exit("Error in database connection");
}
else
{
$exists = mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong` = '$agegroup' AND `AgeGroupShort` = '$abbrev' AND `ManagerID` = $managerID AND `MeetID` = $meetID ");
$row = mysqli_fetch_array($exists);
if($_POST['agegroup']=="" || $_POST['abbrev']=="" || $meetID=="")
{
//exit(json_encode(1));
echo json_encode(1);
}
else if($id == "" && $row > 0)
{
echo json_encode(2);
}
else
{
$result = mysqli_query($db, "SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegroup' AND `AgeGroupShort` = '$abbrev'");
//$row = mysqli_fetch_array($result);
if($id == "")
{
mysqli_query($db, "INSERT INTO `AgeGroup` (`AgeGroupLong`,`AgeGroupShort`,`Sort`, `ManagerID`, `MeetID`) VALUES ('$agegroup', '$abbrev', $sort, $managerID, $meetID)");
}
else
{
$AgeGroup_id = $row['AgeGroupID'];
mysqli_query($db, "UPDATE `AgeGroup` SET `AgeGroupLong`='$agegroup',`AgeGroupShort` = '$abbrev', `Sort`=$sort WHERE `AgeGroupID`=$id");
}
$ageGroup = array
(
'agegroup' => stripslashes($agegroup),
'abbrev' => stripslashes($abbrev),
'sort' => stripslashes($sort)
);
echo json_encode($ageGroup);
}
}
}
mysql_close($db);
declare global variable and make ajax request one time:-
var is_request_sent = false;
function like_post(wall_post,obj)
{
if(is_request_sent == false)
{
$.ajax({
type: "POST",
dataType: "json",
url: base_url+"ajax_timeline/like_post",
data: "action=like_post&wall_post_id="+wall_post,
success: function(result){//alert(result);alert('here');
is_request_sent = false;
},
error: function(a,b,c)
{
is_request_sent = false;
//fbalert('Error', 'Error occured. Please try again.');
},
beforeSend: function(jqXHR, plain_jqXHR){
is_request_sent = jqXHR;
// Handle the beforeSend event
},
complete: function(){
is_request_sent = false;
// Handle the complete event
}
});
}
}
i hope this will help you

Categories

Resources