I am running the script below whe a timer has run out of time, the post was working fine when i started passing the data through that is need for the final information is saved. that when got an internal error.
JavaScript ajax call
var selectedval;
if (document.getElementById('RadioButtonList1_0').checked == true) {
selectedval = document.getElementById('RadioButtonList1_0').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_2').checked == true) {
selectedval = document.getElementById('RadioButtonList1_2').value
}
else if (document.getElementById('RadioButtonList1_3').checked == true) {
selectedval = document.getElementById('RadioButtonList1_3').value
}
else {
selectedval = '';
}
var qustNo = document.getElementById('ltlQuestNos').innerHTML;
`enter code here` $.ajax({
type: "GET",
data: '{questNo:'+ qustNo.trim().toString()+',selectedoption:'+ selectedval.toString()+'}',
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function (result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
Vb.net code.
<WebMethod()>
Public Shared Function timeFinished(questNo As String, selectedoption As String) As String
Dim objExam As New examClass()
If selectedoption = "-1" Then
'lblWarning.Visible = True
'lblWarning.Text = "Please answer Question!"
Else
' lblMessage.Text = "Navigation = " & Request.Form("textNav")
objExam.answerQuestion(HttpContext.Current.Session("examid"), questNo, selectedoption, "00:00:00")
' lblWarning.Visible = False
'close connection
objExam.Dispose()
End If
objExam.finishTest(Convert.ToInt32(HttpContext.Current.Session("examid").ToString()))
objExam.Dispose()
' HttpContext.Current.Response.Redirect("ChapterTestSummary.aspx", true);
Dim url As String = "testsummary.aspx"
Return url
End Function
I think the problem is with data part in ajax. Because, if you are building the data as string by yourself, key and value should enclosed in double quotes. Otherwise make it as an object and use JSON.stringify() method to make it as string.
$.ajax({
type: "GET",
data: JSON.stringify({
questNo: qustNo.trim(),
selectedoption: selectedval
}),
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function(result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
});
Related
I want to make the data alert successfully saved or fail after the user selects on the confirmation message. In this case data checking occurs after the user confirms the message I made.
This is my Javascript Code :
$('#add-btn').on('click', function(event){
var confirmation = confirm("Do you want to save ?");
if (confirmation == true) {
var code = $('#code').val();
var name = $('#name').val();
var unit = $('#unit').val();
var price_code = $('#price_code').val();
var type = $('#type').val();
var final = $('#final').val();
var dataString = 'code=' +code+ '&unit=' +unit+ '&price_code=' +price_code+ '&type=' +type;
if (code != '' && name != '' && unit != '' && price_code != '' && type != '' && final != ''){
event.preventDefault();
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.status == 'success'){
alert("Success !");
}
else if(data.status == 'error'){
alert("Data already used !");
}
}
});
}
else{
alert('Please fill all fields !');
}
}
});
All input success to save but the alert cannot show.
I think problem in your php file. your JOSN data is not in correct format that you received in success.Please try this in your add_data.php file
//All code goes here and after insert try this
$array = array();
if(if data insert successfully) {
$array['status '] = 'success';
} else {
$array['status '] = 'error';
}
header('Content-Type: application/json');
echo json_encode($array);
The success function is only executed if everything went well. If there has been any error, you need to add the Ajax failure function as follows:
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
alert("Success !");
}
}).fail(function () {
alert("Data already used !");
});
finally I find my solution. I'm sorry for my carelessness.
That happened because my variable dataString did not complete.
It should be :
var dataString = 'code=' +code+ '&name=' +name+ '&unit=' +unit+
'&price_code=' +price_code+ '&type=' +type+ '&final=' +final;
Thank you all for your kindness :-)
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.
I have a c# method which I would like to call on client side.
I used ajax calling to achieve this
function ValidateIfDuplicate()
{
debugger
var billtext = $("#ctl00_ContentPlaceHolder2_textBoxBillNumber").val();
var retailer= $("#ctl00_ContentPlaceHolder2_dropDownListRetailers").val();
var billdate = $("#ctl00_ContentPlaceHolder2_textBoxBillDate").val();
if (billtext == "")
{
alert("Bill Number cannot be left empty");
return false;
}
else if (retailer == 0) {
alert("Please select a Retailer");
return false;
}
else if (billdate == '') {
alert("Date cannot be left empty");
return false;
}
else if (billtext != '' && retailer != '' && billdate != '')
{
$.ajax({
Type: "POST",
url: "CAInvoiceEntry.aspx/ValidateDuplicateEntry",
contentType: "application/json; charset=utf-8",
data: { billtext1: billtext, billdate1: billdate, retailer1: retailer },
dataType: "json",
success: function (result) {
debugger
alert(result.d);
}
});
return true;
}
}
and this is my c# method
[System.Web.Script.Services.ScriptService]
public partial class CAInvoiceEntry: BaseClass
{
[WebMethod, ScriptMethod()]
public static int ValidateDuplicateEntry(string billtext1, string billdate1, string retailer1)
{
string validatebill = objCAInvoiceEntry.validatebilldate(textBoxBillNumber.Text, billdate1.ToString(), ViewState[AppConstants.UploadedBy].ToString(), dropDownListRetailers.SelectedValue);
if (validatebill == "1")
{
return 1;
}
else
return 0;
}
}
but the web method is not fired.
I have also tried using pagemethods.methodname() as an alternative(by registring the script with enablepagemethods=true) but with no effect.
If someone can guide me on where i am doing it wrong?
Just to be clear..
in the below image you can see the breakpoint execution, where the ajax call gets skipped.
I was facing similar issue today. In my case i had RouteConfig in App_start folder, So i solved my problem by commenting this line
//settings.AutoRedirectMode = RedirectMode.Permanent;
which was the cause of the problem.
also Your web method needs to be public and static.
something like
public static int MethodName()
{
// your method
}
There seems to be as issue with the way you are passing parameters through ajax.
Try this.
if (billtext != '' && retailer != '' && billdate != '')
{
debugger
$.ajax({
type: "POST",
url: "CAInvoiceEntry.aspx/ValidateDuplicateEntry",
data: "{ billtext1:" + "'" + billtext + "'" + ", billdate1:" + "'" + billdate + "'" + ", retailer1:" + "'" + retailer + "'" + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
if (msg == "1")
alert("Already exists");
else
alert("valid");
},
error: function (msg) {
debugger;
alert(msg);
}
})
return false;
}
You have a tiny typo in your javascript. Remember that javascript is case-sensitive. You are passing in:
Type: "POST"
But in fact you should be passing in:
type: "POST"
If you use F12 on the Network tab, you will noticed that your current AJAX call is making a GET request, not a POST request.
I have a Javascript function on a button click with a POST to a WebMethod. After getting the response back; which is a redirect URL, the code goes to the IsPostBack event of the redirected page but that page never loads. I have written redirects all over the place but somehow this one just stays on the page it is called from.
jQuery.ajax({
type: "POST",
url: "MyProfile.aspx/UpdateProfile_Clicked",
async: false,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != '') {
alert("Your profile has been updated.");
// response.d = "SubmitRequest.aspx"
var data = response.d;
if (data.indexOf("aspx", 0) > -1) {
redirect(data);
}
}
return false;
},
error: function (httpRequest, textStatus, errorThrown) {
LogAjaxErrorToServer(httpRequest, textStatus, errorThrown, parms, "UpdateProfile_Clicked");
}
});
function redirect(url) {
if (url == "") { return false; }
var indx = window.location.pathname.lastIndexOf('/', 0);
if (indx < 0) { indx = 0; }
var local = window.location.pathname.substr(0, indx);
local += "/" + url;
location.href = local;
return false;
}
So the code does go to the (!IsPostBack) for SubmitRequest.aspx but stays on the Profile.aspx. What am I missing? Thank you in advance for helping me
May
the ajax request is part of a larger function. I am trying to refrain from clogging up the page with code so here is the request itself:
$.ajax({
url: "PubMedNewSnp.aspx/GetEdits",
data: "{ 'Drug':'" + drug + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (alreadyInDB) {
var TableName = "combo";
var curRow = curComboRow;
if (alreadyInDB) {
TableName = "edit";
curRow = curEditRow;
curEditRow++;
}
else {
curComboRow++;
}
do stuff...
}
});
Here is the aspx.cs file:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static bool GetEdits (string Drug) {
//masterDBDataContext masterDB = new masterDBDataContext();
bool alreadyInDB = false;
if (Drug == "bannana")
{
alreadyInDB = true;
}
//var inTbl = (from a in masterDB.tbl_custom_SNPs_Alls
// join
// where a.PubMedInfoId == Convert.ToInt32(curRow[0]) &&
// a.DrugId == Convert.ToInt32(curRow[0])
// select r).ToList();
return alreadyInDB;
}
for some reason there is no response coming back. In the network tab all I see are the Request Headers and the Request payload. There is also a warning: Provisional headers are shown. Not sure what that means. Sorry if the question is phrased vaguely or not information is given. I will be glad to provide more, just not sure what else is needed.
Thanks in advance.
This is your output for alreadyInDB which is in json format.
Object {d:true} or Object {d:false}
$.ajax({
url: "PubMedNewSnp.aspx/GetEdits",
data: "{ 'Drug':'" + drug + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (alreadyInDB) { // alreadyInDB is in json format. you need to access object property.
var TableName = "combo";
var curRow = curComboRow;
if (alreadyInDB.d) {
TableName = "edit";
curRow = curEditRow;
curEditRow++;
}
else {
curComboRow++;
}
}
});
Hope that helps.