Success callback not running - c#

Can anyone tell me why my success callback in this jQuery isn't being called?
$(document).ready(function () {
var queueid = $('#hidqueueid').val();
var queuemax = $('#hidqueuemax').val();
var queuenext = $('#hidqueuenext').val();
var sid = $('#hidsid').val();
var acc = $('#hidacc').val();
var key = getCookie('account_key');
var processNext = function() {
var url = "functions.aspx?sid=" + sid + "&acc=" + acc + "&func=processqueue&id=" + queueid + "&next=" + queuenext + '&key=' + key;
showProgress();
$.post(url, function (data) {
alert(data); // <== never happens :(
var result = $(data).attr('result');
if (result == 'ok') {
queuenext = $(data).attr('next');
if (queuenext > 0) {
$('#hidqueuenext').val(queuenext);
processNext();
} else {
var newurl = 'Data.aspx?sid=' + sid + '&acc=' + acc;
location.href = newurl;
}
}
}, function() {
// error
alert('Oops!');
});
};
var showProgress = function() {
var output = "<div>" + queuenext + " of " + queuemax + "</div>";
$('#divprogress').html(output);
};
processNext();
});
The C# which returns the result is working fine and looks like this:
string xml = new Queue(sid, acc, queueId).ProcessItem(queueNext, key);
Response.ClearContent();
Response.ContentType = "text/xml";
Response.Write(xml);
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
The XML looks fine when I debug the C#
Thanks for any help! All suggestions welcome.

post has three initial parameters, first one is a address, second is data, which should be null in your case, and third is success callback.
If you need a fail callback, use fail method:
$.post('', null, null).fail(function(data) {} );
Also, if you feel more comfortable working with that XMLRequest object, you might want to use complete method:
$.post('/do/action', { Id: 120 }, null).fail(function(data) {
// code
}).complete(function(data) {
// code for complete, which is the same as success callback.
});
There is also .always() method which is being called back always, hehe. And others.

Related

Twilio on Call-Connect or Hangup get call details

I am using ASP.NET MVC Web calling with Twilio
Here is my Connect function
function callCustomer(phoneNumber) {
updateCallStatus("Calling " + phoneNumber + "...");
phoneNumber = phoneNumber.replace(/ /g, '');
var params = { To: phoneNumber };
Twilio.Device.connect(params);
}
Here is my Hangup function
function hangUp() {
Twilio.Device.disconnectAll();
}
Here is my TwiML Bin
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial callerId="++516xxx9999" record="record-from-answer">{{To}}</Dial>
</Response>
I am using Twilio client v1.6
//media.twiliocdn.com/sdk/js/client/v1.6/twilio.min.js
I want to collect complete information of each call as I connect to call or as I hang up the call like Call Duration, Call Sid, Record Sid, Call To, and other. Then with that information I would like implement play recorded call in my application.
I believe one way of doing it is set CALL STATUS CHANGES under Voice & Fax and receive all params.
This is how I ended up handling it.
/* Callback for when a call ends */
Twilio.Device.disconnect(function (connection) {
console.log(connection);
// Disable the hangup button and enable the call buttons
hangUpButton.prop("disabled", true);
callCustomerButtons.prop("disabled", false);
callSupportButton.prop("disabled", false);
updateCallStatus("Ready");
addCallLog(connection.parameters.CallSid);
});
addCallLog function
function addCallLog(id) {
var type = "";
var entityId = Number($("#Id").val());
$.ajax({
url: "/Phone/AddCallLog?callId=" + id,
type: "POST",
contentType: "application/json;",
success: function (data) {
// Handle Success Event
},
error: function (data) {
// Handle Error Event
}
});
}
Controller Method
[HttpPost]
public ActionResult AddCallLog(string callId,string type,int entityId)
{
TwilioClient.Init(_callSetting.Twilio.AccountSid, _callSetting.Twilio.Authtoken);
var records = CallResource.Read(parentCallSid: callId).ToList();
if (records.Any())
{
var callResource= records[0];
var parentRecord = CallResource.Fetch(pathSid: callId);
if (callResource.Status.ToString().Equals("completed", StringComparison.OrdinalIgnoreCase))
{
CallRecord callRecord = new CallRecord
{
EntityKey = entityId,
EntityType = type,
CallDateTimeUtc = callResource.DateCreated ?? DateTime.UtcNow,
CallSId = callResource.Sid,
ParentCallSId = callResource.ParentCallSid,
CalledById = _operatingUser.Id,
DurationInSeconds = parentRecord==null? Convert.ToDouble(callResource.Duration): Convert.ToDouble(parentRecord.Duration),
ToPhone = callResource.To,
CompanyId = _operatingUser.CompanyId
};
var callRecordResult= _callRecordService.Add(callRecord);
var recording = RecordingResource.Read(callSid: callId).ToList();
if (!recording.Any()) return Json(true);
foreach (RecordingResource recordingResource in recording)
{
using (var client = new WebClient())
{
var url =
"https://api.twilio.com" + recordingResource.Uri.Replace(".json", ".mp3");
var content = client.DownloadData(url);
CallRecordMedia callRecordMedia = new CallRecordMedia
{
CallRecordId = callRecordResult.Id,
ContentType = "audio/mpeg",
RecordingSId = recordingResource.Sid,
RecordingCallSId = recordingResource.CallSid,
FileType = "mp3",
Data = content,
Price = Convert.ToDouble(recordingResource.Price),
PriceUnit = recordingResource.PriceUnit,
DurationInSeconds = Convert.ToDouble(recordingResource.Duration)
};
_callRecordService.AddCallRecording(callRecordMedia);
}
}
}
}
return Json(true);
}

<asp:TreeView> Add an additional information to treenode accessible via JavaScript/JQuery?

Is there a way to add an information to the asp:TreeView, in the way that i can access it via JavaScript/Jquery?
My problem: I have to prevent via JQuery/Javascript (on client side) that checkboxes in an asp:TreeView are selectable in different subcategories (or parent-nodes grouped by a stereotype-prefix). It already worked when i asked for the TreeNode-Text with $(this).next().text();, because they had a prefix (stereotype) in the categories, but now i have to hide that information and cannot use it to check.
$("[id*=TreeView1] input[type=checkbox]").bind("click", function () {
var isChecked = $(this).is(":checked");
if (isChecked) {
zuletztSelektiert = zuletztSelektiert + $(this).next().text();
}
else {
zuletztSelektiert = zuletztSelektiert.replace($(this).next().text(), '');
}
if (zuletztSelektiert != '') {
// Welcher Stereotyp ist selektiert?
var stereotype = zuletztSelektiert.substring(zuletztSelektiert.indexOf('«') + 1, zuletztSelektiert.indexOf('»'));
$("[id*=TreeView1] input[type=checkbox]").each(function () {
var currentStereotype = $(this).next().text().substring($(this).next().text().indexOf('«') + 1, $(this).next().text().indexOf('»'));
if (currentStereotype != stereotype) {
var isChecked2 = $(this).is(":checked");
if (isChecked2) {
$(this).removeAttr("checked");
zuletztSelektiert = zuletztSelektiert.replace($(this).next().text(), '');
alert('It is not possible to select elements of different stereotypes. \n\n Selected Items:\n' + zuletztSelektiert);
}
}
});
}
});
Okay because nobody know the answer i just did it by adding the stereotype as GET-Param to the links target URL and navigated to the -Tag in the treenode
$("[id*=TreeView1] input[type=checkbox]").bind("click", function () {
var selectedStereoType = $.trim($(this).next().prop("href").substring($(this).next().prop("href").indexOf("=") + 1));
//return;
var isChecked = $(this).is(":checked");
if (isChecked) {
//zuletztSelektiert = zuletztSelektiert + $(this).next().text();
zuletztSelektiert = zuletztSelektiert + selectedStereoType;
}
else {
//zuletztSelektiert = zuletztSelektiert.replace($(this).next().text(), '');
zuletztSelektiert = zuletztSelektiert.replace(selectedStereoType, '');
}
if (zuletztSelektiert != '') {
// Welcher Stereotyp ist selektiert?
//var stereotype = zuletztSelektiert.substring(zuletztSelektiert.indexOf('«') + 1, zuletztSelektiert.indexOf('»'));
var stereotype = selectedStereoType;
var letzteMeldung = '';
$("[id*=TreeView1] input[type=checkbox]").each(function () {
//var currentStereotype = $(this).next().text().substring($(this).next().text().indexOf('«') + 1, $(this).next().text().indexOf('»'));
var currentStereotype = $.trim( $(this).next().prop("href").substring($(this).next().prop("href").indexOf("=") + 1) );
if (currentStereotype != stereotype) {
var isChecked2 = $(this).is(":checked");
if (isChecked2) {
$(this).removeAttr("checked");
zuletztSelektiert = zuletztSelektiert.replace($.trim( $(this).next().prop("href").substring($(this).next().prop("href").indexOf("=") + 1) ), '');
letzteMeldung='It is not possible to select elements of different stereotypes. \n\n Selected Items: ' + zuletztSelektiert;
}
}
});
if (letzteMeldung != '') alert(letzteMeldung);
}
});
This is how i did it in C#.NET
treeNode.NavigateUrl = "URL?stereotype="+stereotype;

ASP.net Razor return image URL in JSON from upload

Below I have code from my image upload returning JSON information about the image. Near the assignment of the name parameter I am trying to return the URL of the image although it is not working. Currently the below code does not work as nothing is returned to the browser upon return. The code works fine albeit for the line to add to the Name property near the end.
How can I return the URL of the image so as to display the image URL to the user on return?
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadFilesResult>();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Url.Content(Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(hpf.FileName)));
hpf.SaveAs(GetNewPathForDupes(savedFileName));
r.Add(new UploadFilesResult()
{
Name = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(hpf.FileName)),
Length = hpf.ContentLength,
Type = hpf.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
EDIT
my Javascript to process the form in the done parameter i am trying to read the JSON but cant get it to work with the new Jsonresult:
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: "UploadFiles",
autoUpload: true,
done: function (e, data) {
var json = JSON.parse(data);
$('.file_name').html(json.name);
$('.file_type').html(json.type);
$('.file_size').html(json.size);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
So instead of
return this.Content("{\"name\":\"" + r[0].Name + ...
you could simply do this:
return this.Json(r[0]);
When reading the JSON in your jQuery you will need to do
var jsonString = // from the response
var json = $.parseJSON(jsonString);
var name = json.someElement;

Issues with HttpContext.Current.Response.Redirect in a class

I have written a class which gets the post data using jquerypost and then perform some crud operations. Its works fine adding stuff to the database , but it doesnt redirects to the page when passing certain data , below is the code :
$('#clickme').click(function (e) {
e.preventDefault();
indx = $("#DropDownList1 option:selected").index();
indx += 1;
var test = $("#DropDownList" + (indx + 1));
var url = "/Base/performOperations/shootme/"
jQuery.post(url, { name: jQuery("#name").val(), email: jQuery("#email").val(), federation: jQuery(test).val(), selectedscheme: jQuery("#DropDownList1").val() },
function (data) {
if (data == scheme1) {
window.location = "http://www.openme.com"
}
});
});
namespace pw
{
public class performOperations
{
public static string ShootMe() {
HttpRequest post = HttpContext.Current.Request;
string name = post["name"];
string email = post["email"];
string selectedscheme = post["selectedscheme"];
string federation = post["federation"];
string conn = System.Configuration.ConfigurationManager.AppSettings["mydb"];
string sql = "INSERT INTO dbo.mydb(Email,Name,schemes,LoginDate,schemeType) VALUES(#email,#name,#scheme,#dateTime,#federation)";
SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql,
new SqlParameter("#email", email),
new SqlParameter("#name", name),
new SqlParameter("#scheme", selectedscheme),
new SqlParameter("#dateTime", DateTime.Now),
new SqlParameter("#federation", federation));
return selectedscheme;
}
}
}
Any ideas why the redirect doesnt takes place, or am i doing it in a wrong way , i need to redirect to a particular page once the data is injected to the db.
Any assistance will be appreciated
If you are calling the POST method using AJAX, redirection at server side will not work.
You will have to redirect it at client side after request completion using javascript the request.
$('#clickme').click(function (e) {
e.preventDefault();
indx = $("#DropDownList1 option:selected").index();
indx += 1;
var test = $("#DropDownList" + (indx + 1));
var url = "/Base/sample/Hello/"
jQuery.post(url, { name: jQuery("#name").val(), email: jQuery("#email").val(), federation: jQuery(test).val(), selectedscheme: jQuery("#DropDownList1").val() },
function (data) {
if (data == "shoothim") {
window.location = "http://www.cuthishead.com"
}
else if(data == "shoother")
{
window.location = "http://www.chopherbody.com"
}
else if(data == "shootboth")
{
window.location = "http://www.fulldeath.tv"
}
});
return selectedscheme or URL from your page method
set window.location based on web method result on jquery
need to set WebMethod attribute for your C# method
Check Using jQuery to Call ASP.NET AJAX Page Methods – By Example

Return data from jQuery callback ASP.NET 2.0

I am new to jQuery and I am implementing an example I found on CodeProjects.
What I need is to get a string with an imagename and new image index returned from the PageMethod I am calling.
However each time I try to return something else than a number via Response.Write the callback fails and I go into the error function.
$(document).ready(function() {
var imageIndex = $("[id$='hdn_imageIndex']");
var app_path = $("[id$='hdn_app_path']");
$("#btn_next").click(function() {
var json = "{'Index':'" + imageIndex.val() + "'}";
var ajaxPage = app_path.val() + "/JSONProcessor.aspx?NextImage=1"; //this page is where data is to be retrieved and processed
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=UTF-8",
dataType: "json",
async: false,
success: function(result) {
alert("success: " + result.d);
// I want my return value from my PageMethod HERE.
},
error: function(msg) { alert("failed: " + msg.d); }
};
var returnText = $.ajax(options).responseText;
});
});
The PageMethod in JSONProcessor.aspx looks like this:
public void NextImage()
{
System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string line = "";
line = sr.ReadToEnd();
JObject jo = JObject.Parse(line);
int newImageIndex = -1;
int oldImageIndex = int.Parse(Server.UrlDecode((string)jo["Index"]));
List<string> images = (List<string>)Session["ShowHouseImages"];
int noOfImages = images.Count;
if (noOfImages > 0)
{
if (oldImageIndex == noOfImages - 1)
{
newImageIndex = 0;
}
else
{
newImageIndex = oldImageIndex + 1;
}
string[] result = ChangeImage(newImageIndex, images);
Response.StatusCode = 200;
Response.Write("1");
// What I REALLY WANT TO RETURN IS THIS
// Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
}
Response.Write("0");
}
JSON return from WebMethods does not seem to be a part of .NET 2.0. That is why I do it like this. Hope somebody can help me out.
To my understanding in the line
Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
you are not returning a correct JSON object. It should probably look something like
Response.Write(string.Format("{{images:[{0},{1},{2}]}}", result[0], result[1], result[2]));
This returns you an array with three elements. The produced output should be:
{images:[1,2,3]}
In JavaScript you can access data using result.images[0],result.images1, etc.
I'm not sure if you need to specify array object name (images).
I suggest you take a look at JSON website to get a better understanding of the syntax. This way you will be able to construct complex object by yourself.

Categories

Resources