Passing jQuery variables to Controller via AJAX - javascript

I am trying to send the variables from the GetTelephoneFunction to the AJAX query so it can reach the controller, but what I have tried does not work. Please help and thank you.
jQuery:
$.ajax({
type: "POST",
url: "/Status/GetUrlSource",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "url": $("#urlInput").val(), "user": $("#user").val(), "pass":$("#pass").val(),"freq": $("#freqInput").val() }),
dataType: "html",
success: function (result, status, xhr) {
//Code
}
function GetUrlTelePhone(html, status, result) {
var geturlUser = url.split('?username=')[1].split('&password')[0];
var geturlPass = url.split("&password=")[1];
var getUrlMain = url.split("?")[0];
var geturlParameters = url.split("aspx")[1];
}
Controller
public string GetUrlSource(string url, string freq, string user, string pass)
{
//user = user.Substring(0, 10) != "?" ? "?" + user : user;
//pass = pass.Substring(0,20) != "&" ? "&" + pass : pass;
url = url.Substring(0, 4) != "http" ? "http://" + url : url;
string htmlCode = "";
using (WebClient client = new WebClient())
{
try
{
htmlCode = client.DownloadString(url);
}
catch (Exception)
{
return "Not Found";
}
}
//SqlConnect(url);
Hangfire(url,freq,user,pass);
return htmlCode;
}

Related

Sending Large data from View to Controller in MVC

I am getting table records, I need to send it to Controller so that I can send email. When I tried with following code, it's throwing error
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "GET",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
data: "{'emailList': '" + JSON.stringify(emailList) + "', body' : '" + body + "' }",
success: function (json) {
alert(json);
}
});
Error as : HTTP Error 404.15 - Not Found The request filtering module
is configured to deny a request where the query string is too long.
Most likely causes: Request filtering is configured on the Web server
to deny the request because the query string is too long.
I have tried to add following code, still same error
var formData = new FormData();
var objArr = [];
objArr.push({ "emIl": emailList, });
//JSON obj
formData.append('objArr', JSON.stringify(objArr))
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "POST",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
processData: false,
contentType: false,
data: formData,
Here is Controller Code
[HttpGet]
public JsonResult GetFinanceSendMail(string emailList, string body)
{
List<string> emails = emailList.Split(',').ToList();
// Send Email add optiona arg to the method
_openPobl.TriggerFinanceEmail(body, emails);
return Json(emails, JsonRequestBehavior.AllowGet);
}
fix the action, remove [get]
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(string emailList, string body)
and ajax
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
var body = 'Hi Team';
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: {emailList: emailList, body : body },
success: function (json) {
alert(json);
}
});
but if you want to use post much more reliable to create a viewmodel class
public class ViewModel
{
public string EmailList {get;set;}
public string Body {get;set;}
}
action
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(ViewModel model)
.....
and ajax
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: { model: {emailList: emailList, body : body } },
success: function (json) {
alert(json);
}
});

Calling SaveChanges through Web service

I try to Save data in Db using EF6 through Web service , but it runs forever without any indicators to error .
My web method :
[System.Web.Script.Services.ScriptService]
public class FamilyRelationService : System.Web.Services.WebService
{
[WebMethod]
public int Update(int id, string name)
{
int result = -1;
try
{
using (HRCTX ctx = new HRCTX())
{
using (FamilyRelationRepository familyRelationRepo = new FamilyRelationRepository(ctx))
{
FAMILYRELATION family = familyRelationRepo.Find(id);
family.RELATION_NAME = name;
family.State = StateInterface.State.Modified;
familyRelationRepo.InsertOrUpdate(family);
result = ctx.Save();
}
}
}
catch (Exception ee)
{
throw;
}
return result;
}
}
My Calling function :
function Update(e) {
name = $("#txt_relation_name").val();
id = $("#lbl_relation_code").text();
$.ajax({
type: "POST",
url: "FamilyRelationService.asmx/Update",
data: "{'id':'" + id + "', 'name':'" + name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = response.d;
if (result > 0) {
$("#name", row).text(name);
row.removeClass("highlightRow");
CloseEditStudentDialog();
}
else {
alert('Error...');
}
},
failure: function (msg) {
alert(msg);
}
});
return false;
}
<input type="submit" id="btn_save" value="Save" onclick="Update(); return false;" />
In FireBug Console :
I see the following :

asmx, javascript, HTTP GET issue

First of all- I know I should use HTTP POST and I know how to do it.
But my task is to use HTTP GET anyway. Now, there's a problem. I have a WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet =true)]
public List<string> AddToCollection(string name, string lastname)
{
collection.Add(name + " " + lastname);
return collection;
}
Now, code from .js :
function AddToArray() {
var name = document.getElementById("name_add").value;
var lastname = document.getElementById("surname_add").value;
if (name == "" || lastname == "") {
alert("Wrong!");
} else {
var dataT = JSON.stringify({"name":name,"lastname":lastname});
$.ajax({
type: "GET",
url: "http://localhost:45250/ServiceJava.asmx/AddToCollection",
data: dataT,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
}
Now the thing is: it works perfect when I use type POST. But with GET I get the error that the parameter name cannot be recognized. What should I change to make it work?

How get json parameters if I use post method in vertx?

I want to get all post parameters.
This is my vertx code:
var vertx = require('vertx/http');
var console = require('vertx/console');
var Server= vertx.createHttpServer();
Server.requestHandler(function(req) {
console.log(req.path());
console.log(req.method());
console.log(req.params());
// nothing
if(myPostparametersContainAnyitem){ //do anything}
else{
var file = req.path() === '/' ? 'index.html' : req.path();
req.response.sendFile('html/' + file);}
}).listen(8081)
This is my button click code:
$.ajax({
data: {name:'foo',age:'13'},
url: '/somedir',
type: 'post',
dataType: 'json',
success: function (response) {
alert(response);
}
});
I discovered how to do it thanks
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
console.log(req);
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
//do
req.response.end(data);
});
}

How to Parse Collection in JQuery

I have a IEnumerable Collection of Custom DataType that I'm sending to the Client.
I want to parse the collection in my JQuery method. Currently I'm getting value as "undefined". Below is my code:
Service:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<CustomData> GetSetting(long userId);
public IEnumerable<CustomData> GetSetting(long userId)
{
var tempData = Context.DialogSettings.Where(item => item.id == userId).ToList();
return tempData.Select(dialogSetting => new CustomData { KeyName = dialogSetting.KeyName, KeyValue = dialogSetting.KeyValue }).ToList();
}
[DataContract]
public class CustomData
{
[DataMember]
public String KeyName;
[DataMember]
public String KeyValue;
}
Client:
function LoadSetting() {
$.ajax({
type: "GET",
url: "SampleService.svc/GetSetting",
data: '{"userId": "' + 1 + '"}',
processData: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myHistoryList = data.d;
alert(myHistoryList); // here I'm getting value: undefined
},
error: function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
});
}
});
From the comments on the question I can safely presume that the following js code will work:
if(typeof data != 'undefined'){
alert(data[0].KeyName); //this will yield a value.
}
else
alert('Ok. This is weird');

Categories

Resources