So here's the problem. I have three pages that make web service calls. The first time I land on the page and make the call it works fine, however if I switch to the second page it tries to make a web service call to the wrong service. Here's some info:
pages:
Page1.aspx - has Page1.js
Page2.aspx - has Page2.js
js files:
Page1.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page1List").html(html);
}
Page2.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page2List").html(html);
}
So both have the same calls and the same information and the only real difference is that the results are different and they make a web service call to different web services that get different data.
Now each time that I switch between I get a new js file which is
jQuery-1.7.1.min.js/eval/seq/1
jQuery-1.7.1.min.js/eval/seq/2
jQuery-1.7.1.min.js/eval/seq/3
jQuery-1.7.1.min.js/eval/seq/4
depending on how many times I switch back an forth. Is there any way to stop the eval or is there something in my code that is causing the jQuery to store evals of the code I am using and what can I do to resolve it?
So the problem was that I was loading page transitions from jquery mobile. What was happening was that jquery mobile appends new page data to the DOM instead of forcing a page load. This was causing both javascript files to be loaded simultaneously meaning that which ever js file was loaded last was the primary and because both js files were calling functions with the same name it would load them multiple times.
Resolution
remove the $.mobile.load() event and force the click event to append the pathname to the url
$("#GoPage1").on("click", function () { window.location = "/dir/Page1.aspx"; });
$("#GoPage2").on("click", function () { window.location = "/dir/Page2.aspx"; });
Related
I currently have my project working about 75% of the time, I create report/reports add them to a zip, unzip them to a certain location. When I run this in debug mode it works correctly. When i run it normally sometimes the ajax will run out of order and it will try to unzip the file before its zipped (nothing is there). I have been doing trial and error with this trying many different methods to get this to work.
I tried multiple ways to do this: with the success: of ajax. I tried a .done promise after ajax. I tried a bool : if statement I tried many different conditions. It seems to finally be working in the correct order when i first open the project and select the records and the button click. Only 1 time it will do it successful.
When I try to select new records and run it a 2nd time the unzip folder isnt always created Or if it'll be created but will be empty (No reports unzipped to it).
Here is what I currently have which sometime works. Once I have this going good then I have to create the last step which will be to create an email and attach the document.
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks },
success: function () {
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
},
error: function (request, status, error) {
alert("Error Generating Files");
//+ request.responseText);
}
}).done(function () {
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
//alert("success in unzip");
CallEmail();
}
})
});
Here is another way i been doing this.
if (isValid) { /* At least 1 record is selected */
var phaseOne = $.ajax({
type: "GET",
async: false,
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
successful = true
},
complete: function () {
if (successful)
isZipped = true;
}
});
}
$.when(phaseOne).always(function () {
if (isZipped) { /* Files are Zipped to start this phase */
$.ajax({
type: "POST",
async: false,
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
traditional: true,
});
}
})
P.S. I have both Controller Actions UnZipDownload and UnZipDocument (both similar) if needing to see the action i will post.
You have to call your the second function only if the first is successful
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks }
}).done(function(){
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8"
}).done(function(){
//alert("success in unzip");
CallEmail();
});
}).fail(function(){
alert("Error Generating Files");
//+ request.responseText);
});
So I have tried SO MANY DIFFERENT results to try to get this to work with the click of 1 button. BUT the only way I have found out a way to get this to work is to have 1 button to do the report creating and zipping of the files. Then to have a second button (mines currently in a modal) and on this button click I am unzipping the file and creating the email. I have not been able to do everything all in 1 call. When I try my unzip functions is being called before my zip function I have tried many different ways to try to not have this happen [success, .done(), deferred objects, javascript promises]
$('#btnGetChkEmail').on('click', function() {
var arrChkBoxes = [];
var arrSelectedChks = [];
var myJSON = {};
var phaseOne, phaseTwo;
var isValid = false;
var bool = false;
var isZipped = false;
//var unZipped = false;
var successful = false;
// Turn all selected checkbox T/F values into QuoteIDs
$("input:checked").each(function (index, value) {
arrChkBoxes.push($(value).val());
});
// Push all Selected QIDs on NEW ARRAY
$.each(arrChkBoxes, function (key, value) {
if (IsPositiveInteger(value)) {
arrSelectedChks.push(value);
}
});
if (arrSelectedChks.length === 0) { // Create Modal (Error ~ None ~ Selected)
isValid = false;
alert("No Records Selected");
} else {
isValid = true;
}
/* EDITION LIKE GETCHKS */
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
},
error: function (request, status, error) {
alert("Error Generating Reports");
}
}).done(function (data) {
/* Only way to do this 100% at the moment is to bring up a Button in a Modal */
var zipModal = $("#zipModEmail");
var modalHead = "<h3 class='modal-title'>Generate Email Messages</h3>";
var modalBody = "<span class='glyphicon glyphicon-ok-sign' style='font-size:5em; color:green;'></span>" +
"<p><b>Attach PDF's to email Confirmation</b></p>" +
"<p>Click 'OK' to Confirm</p>";
//var modalFoot = "";
zipModal.find(".modal-header").html(modalHead);
zipModal.find(".modal-header").addClass("alert-success");
zipModal.find(".modal-body").html(modalBody);
zipModal.modal("show");
});
}
$("#btnUnNemail").click(function (e) {
var myJSON = {};
var bool = false;
var ajaxCall = $.ajax({
type: "POST",
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response.Status == "Unzipped") {
myJSON = { "Status": "Unzipped", "FilePath": response.FilePath, "FileName": response.FileName, "FileNames": response.FileNames };
bool = true;
}
$("#zipModEmail").modal("hide");
}
});
// Try switching to 'POST'
$.when(ajaxCall).then(function () {
if (bool) {
//debugger;
$.ajax({
type: "GET",
url: '#Url.Action("CreateEmailReport", "Service")',
contentType: "application/json; charset=utf-8;",
data: { "folderData": myJSON },
traditional: true,
})
}
});
});
I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this
I want to read data which is posted in JSON in my c#.net application? I am very new with this JSON and POST method?
Can anyone please help me?
I am posting data from page1. to other page2 (smsstaus.aspx in my case) for testing purspoe.
I want to read that JSON posted data in PageLoad of Page2.
Sample code.....
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
You could define a WebMethod in your smsstatus.aspx (SendStatus for example)
An implementation could look something like this (from the top of my head)
[WebMethod]
public static void SendStatus(string sid, string status)
{
// retrieve status
}
Now you can create a request to consume this method, like this:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx/SendStatus",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
.NET wil deserialize the json string to and pass them as arguments to SendStatus
when you are using Jquery and you throw JSON in the data thingy it will change in a normal Post but what you are now doing is gonna give problems change the code to:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: {"SmsSid":$("#<%= txtSmsSid.ClientID%>").val(),"SmsStaus": $("#<%= txtSmsStaus.ClientID%>").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
and you can use the normal POST but if you want to play with JSON in C# see this aritcle
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Do not change the contentType if you want to request the aspx (WebForm) and not the WebMethod. (When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded").
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
dataType: "json", // The type of data that you're expecting back from the server.
success: function (msg) {
alert(msg.d);
},
error: function () { }
});
Receive data from the Page_Load handler,
//Read Form data
string testData = Request["SmsSid"] + " " + Request["SmsStaus"];
//Prepare Json string - output
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{ \"d\": \"" + testData +"\" }");
Response.Flush();
Response.End();
I need to call a handler (ashx) file from jQuery to fetch some data at runtime.
My jQuery function looks like:
var pID = 3;
var tID = 6;
$("#Button1").click(function() {
var urlToHandler = "Controller/TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: "{'pID':'" + pID + "', 'tID':'" + tID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
My handler code:
<%# WebHandler Language="C#" Class="TestHandler" %>
using System;
using System.Web;
public class TestHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
String pID = context.Request.Params["pID"];
String tID = context.Request.Params["tID"];
context.Response.ContentType = "text/plain";
context.Response.Write(pID + " " + tID);
}
public bool IsReusable
{
get {
return false;
}
}
}
The problem is the code execution doesn't reach to the handler code.
I can call other web forms (aspx) files from the same jQuery function from the same directory, where the handler file is residing. So it isn't any path issue.
I am new to this handler file concept. I googled a lot but couldn't find anything wrong in my code.
It worked after changing the way I was passing the json data (as suggested by #DRAKO) and removing the contentType from the ajax post back call. Also corrected the path.
$("#Button1").click(function() {
var urlToHandler = "TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: { pID: pID, tID: tID },
dataType: "json",
success: function(msg) {
//do something with the msg here...
}
});
});
I think the way you are passing the json data to the handler is incorrect.
Also make sure the path to the handler is correct and write a line to the console in the handler to check if it is getting called. Try this code out
$("#Button1").click(function(){
$.ajax({
type: "POST",
url: "/Controller/TestHandler.ashx",
data: {pID:pID, tID:tID},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(){
alert("Error");
}
});
});
I am using Jquery Ajax to set the values of a Label and a ListBox in my form. I realize that values are set properly by the function. But just after that , the page just refreshes clearing all previously set values . Why is this happening ? Iam new to Jquery/Ajax. Am I missing any fundamentals here ? Thanks in Advance.
Iam pasting the entire code
$(document).ready(function () {
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
})
});
Button1 in your code is an asp button which is a submit button. When you click on it, it will submit the page and refresh the whole page. If you want to stop the page from being submitted on button click return false, it will work.
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
return false;
})