$('#srch').click(function(e){
if ($("#form").validationEngine({returnIsValid:true})) {
$("#loader").dialog('open');
$.ajax({
type: "GET",
url: "/cdr/abc.php",
cache: false,
data: $("#srch").serialize(),
timeout: 5000,
error: function (XMLHttpRequest, textStatus, errorThrown) {
//ajaxSubmitError(XMLHttpRequest, textStatus, errorThrown);
},
success: function (data) {
$('#submit-dialog').dialog('close');
}
});
e.preventDefault();
}
});
In The Above Function Iam Not able to navigate to the The Action (php) Page.and The Dialog runs Indefinitely and how should i close the dialog when The Form submits
In my model window I use an AJAX form with MVC, but the solution should work regardless of technology.
<% using (Ajax.BeginForm("Index", "Message", new AjaxOptions { OnBegin = "SubmitMessage", OnSuccess = "CloseDialog" }, new { #id = "Index-Message" })) { %>
<input type="submit" value="Send" class="Button" />
<% } %>
Then I place this small function in the calling window.
function CloseDialog() {
$("#Modal").dialog("close");
}
you could also close the dialog in the error event.
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#submit-dialog').dialog('close');
},
You actually need something like this:
$('#srch').click(function(e){
var $dialogContent = $("#form");
$dialogContent.dialog({
modal: true,
title: "Test",
close: function() {
$dialogContent.dialog("destroy");
$dialogContent.hide();
},
buttons: {
save : function() {
$.ajax({
type: "GET",
url: "/cdr/abc.php",
cache: false,
data: $("#srch").serialize(),
timeout: 5000,
error: function (XMLHttpRequest, textStatus, errorThrown) { //ajaxSubmitError(XMLHttpRequest, textStatus, errorThrown); },
success: function (data) {
$dialogContent.dialog("close");
}
});
},
cancel : function() {
$dialogContent.dialog("close");
}
}
}).show();
e.preventDefault();
}
Any validation you can do within the save function.
Related
Hi this code is working great, i am new in javascript ,what i am trying to do , print js default error message in my div.
<script type="text/javascript">
$(document).ready(function () {
var contranumber = <?php echo json_encode($data); ?>;
debugger;
if(contranumber)
{
$.ajax({
url: ApiUrl+'ActivateUser?contraNumber='+contranumber,
type: 'get',
success: function (data, xhr) {
alert(data.ErrorMessage);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
}else
{
}
});
</script>
<div><center>javascript message</center></div>
<center><h3> Check your Email</h3></center>
A few quick things first:
Remove center tags, as it is deprecated. (Official example is "No, really, don't use it.")
Remove debugger;, unless you want your browser to stop.
Give your elements some sort of identification, be it a class or ID.
$(document).ready(function() {
var contranumber = '{ "hello": "world" }';
var message = $('.message'); // the element the message will go in
if (contranumber) {
$.ajax({
url: ApiUrl + 'ActivateUser?contraNumber=' + contranumber,
type: 'get',
success: function(data, textStatus, xhr) { // you missed the textStatus parameter
message.text('it was successful'); // why log an error on success?
},
error: function(xhr, textStatus, errorThrown) {
message.text('Error in Operation:' + errorThrown); // give the actual error text
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message"></div>
<h3>Check your Email</h3>
$('#example center').text(data.ErrorMessage);
I usually do this:
$.ajax({
type: 'POST',
url: validateAjaxURL,
success: function (data) {
var returnData = data;
if (returnData.match("^selectedUno-")) {
$('#new_caregiver_popup_div').dialog('close');
} else {
$("#new_caregiver_popup_div").html(data);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
UPDATE :
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#DivID').text(errorThrown);
}
Here is the link for your reference :
Show Error
I am using mvc 4 ,I need to call controller actions using ajax.So I created a new scripts.js file at Scripts folder.In my project there are lot of controllers and I wrote ajax functions for each of them in the same js file.But except the default controller other controllers are not initiated by the ajax code. Scripts.js file contains:
$(document).ready(function () {
//END COUNTRY ................................................................
$("#savecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/SaveCountry',
data: {name: $('#country').val() },
dataType: 'json', encode: true,
async: false,
cache: false,
//contentType: 'application/json; charset=utf-8',
success: function (data, status, jqXHR) {
// alert("success");
console.log(jqXHR);
console.log(status);
console.log(data);
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(jqXHR);
//console.log(textStatus);
//console.log(errorThrown);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$("#updatecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/Update',
data: { id:$('#id').val(), name:$('#country').val() },
dataType: 'json', encode : true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$('#cancel').click(function () {
$('input:text').val('');
});
//$('.deleteRow').click(function () {
// alert('ewewrwr');
// $.ajax({
// type: "POST",
// data: { id: $('#id').val() },
// url: "/Country/DeleteCountry",
// dataType: 'json', encode: true,
// async: false,
// cache: false,
// success: function (data, status, jqXHR) {
// alert("success");
// //$.each(data, function (index, customer) {
// // alert(customer.Name + " " + customer.UserName);
// //});
// },
// error: function (jqXHR, textStatus, errorThrown) {
// console.log(jqXHR);
// if (typeof (console) != 'undefined') {
// alert("oooppss");
// }
// else { alert("something went wrong"); }
// }
// });
//});
$("#updateoffer").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Offer/Update',
// contentType: "application/json; charset=utf-8",
data: { id: $('#id').val(), name: $('#offer').val(), description: $('#description') },
dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
});
Here Country is the default controller and ajax call working well.But call to Offer controller Update ajax not working .Page not responding error will result.
You should take project name to baseUrl for call ajax function.
$(document).ready(function(){
var baseurl = "";//your project name
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry', // baserurl+"/controller name/action"
.....
}
The accepted answer has a serious flaw in commercial deployments, so offering alternatives.
Yes, you need the base address of the website, but you do not want to hard-wire it into the code.
Option 1
You can inject a global javascript variable into your master page as a string constant.
e.g. put this at the top of your master page
<script>
window.baseurl = "#Url.Content("~/")";
</script>
then just use window.baseurl prepended to your URLs
e.g
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: window.baseurl+'/Country/SaveCountry',
Option 2
You can inject a data- attribute into the DOM in your master page. e.g. on the body tag
then extract it using jQuery:
e.g.
var baseurl = $('body').data('baseurl');
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry',
Option 3 (I do not advise this one)
Inject the string literal into your Javascript
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("SaveCountry", "Country")",
This is bad for maintenance and debugging as the code must be in a Razor view in order to work.
We used to use option 2 a lot, but now tend to use option 1.
i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});
I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.
The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?
Here is my code:
$('input[type=button]').click(function () {
bookingID = $(this).closest('tr').attr('id');
sendEmail(bookingID, this);
});
function sendEmail(id, thisContext) {
var data = JSON.stringify({ 'id': id });
/*******
This calls setButtonSuccess AND setButtonFailed which is wrong
I want to execute only setButtonSuccess OR setButtonFailed depending on whether successful or not
*******/
jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};
function setButtonSuccess(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-success");
};
function setButtonFailed(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-warning");
};
function jsonPOST (pWebServiceFunction, pData, pOnCallbackSuccess, pOnCallbackFailed, async) {
$.ajax({
type: "POST",
url: url + pWebServiceFunction,
data: pData,
contentType: "application/raw; charset=utf-8", dataType: "json",
async:async,
processdata: true,
success: function (msg) {
if (msg.success === true) {
pOnCallbackSuccess(msg);
}
else {
pOnCallbackFailed(url + pWebServiceFunction);
}
},
error: function (xhr, ajaxOptions, thrownError) //When Service call fails
{
pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
}
});
};
Thanks
You're calling the functions immediately instead of passing a function that will call them later. It should be:
jsonPOST("~Booking/ResendEmail", data, function() {
setButtonSuccess(thisContext, "Email Sent");
}, function() {
setButtonFailed(thisContext, "Email Failed");
}, false);
I am doing the following through jQuery, but it looks like they are almost happening simultaneously.
Is there a way to make sure itemNameContainer.removeClass('NoDisplay') in the complete callback to run only after the loadingContainer.addClass('NoDisplay') is completed?
Visually, it looks like I am seeing 'Please wait..' and the item name show up at the same time..
function onToggleItemCompletionStatus(currentItem) {
var itemId, toggle = !currentItem.Completed,
loadingContainer, itemNameContainer;
itemId = currentItem.ItemId;
loadingContainer = $('#loading_' + itemId);
itemNameContainer = $('#name_' + itemId);
$.ajax({
beforeSend: function (xhr, settings) {
loadingContainer.removeClass('noDisplay');
itemNameContainer.addClass('noDisplay');
},
complete: function (xhr, textStatus) {
loadingContainer.addClass('noDisplay');
itemNameContainer.removeClass('noDisplay');
},
data: {
accessToken: aToken,
listId: currentGroceryList.Id,
itemId: currentItem.ItemId,
completed: toggle
},
dateType: 'json',
error: function (xhr, textStatus, errorThrown) {
$.publish(customEvent.ItemToggledFail, [currentItem]);
},
success: function (data, textStatus, xhr) {
var success = data.success;
if (success) {
$.publish(customEvent.ItemToggledSuccess, [currentItem]);
} else {
$.publish(customEvent.ItemToggledFail, [currentItem]);
}
},
type: 'POST',
url: actionUrls.toggleItemCompletionStatus
});
}
EDIT
I pasted the actual function to give a better idea
Not that I know of, but you could try...
loadContainer.fadeOut(300, function() {
itemNameContainer.removeClass('NoDisplay');
});