How to pass string value from javascript to function in ASHX - javascript

I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!

You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms

Related

Javascript AJAX not working on ASP.NET C# and returns a 404

I have a front end code which sends a POST request to the server and returns nothing as the server needs the information.However in Chrome's log i see a 404
Thanks,
Failed to load resource: the server responded with a status of 404
(Not Found)
The following code sends the server a request:
var data = "hi"
var theIds = JSON.stringify(data);
var UrlFixer = '/Process/Complete';
// Make the ajax call
$.ajax({
type: "POST",
url: UrlFixer,
contentType: "application/json; charset=utf-8",
data: { ids: theIds },
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
Backend(C#):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Quiz3
{
public class Process
{
[HttpPost]
public static void Complete(string[] ids)
{
String[] a = ids;
}
}
}
You can get help from the code below to send data.
You do not have to submit a string item in the form { ids: theIds } You must change the form to JSON.stringify(data) .
var data = "Your Name";
$.ajax({
url: '/home/Complete',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
And your class should not be simple. You must have a controller class
Backend:
public class HomeController : Controller
{
[HttpPost]
public void Complete(string Name)
{
//Code ...
}
}
Maybe send your Ids as a list of id and don't stringify your list
public static void Complete(List<T> Ids)
I managed to get this to work with MVC Empty template by the following method:
Firstly a controller is made(inside the controller folder) and its named 'SubmitController'.Now at first i thought that naming it controller at the end is not important but it turns out it is and the URL would be '/Submit' and not '/SubmitController'.
Inside the C# file a function is made and i called it 'Process' with an POST attribute(HttpPost).The URL now would be '/Submit/Process'.In my case i needed to pass an array from the client to server and that is the extra piece of code used in C# to process it and display on the Output page of Visual studio.
SubmitController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class SubmitController : System.Web.Mvc.Controller
{
[HttpPost]
public PartialViewResult Process(string myArray)
{
String[] Items = myArray.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
//print
Items.ToList().ForEach(i => System.Diagnostics.Debug.WriteLine(i.ToString()));
return null;
}
}
}
SendEvent.js
// Make the ajax call
var myArray = data;
$.ajax({
type: "POST",
url: '/Submit/Process',
data: { 'myArray': myArray.join(',') },
});

Sending JSON string to my backend code to add it to my DB but it's not adding anything

I've been stuck on this problem for a good bit
I'm trying to add an object to my database through jQuery/AJAX. Apparently, there are no errors but it's not adding anything to my DB.
This is my JS/JQuery code:
var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
alert(response.responseJSON);
}
});
My JS code points towards this code I have in my Default.aspx page code:
[WebMethod]
public static void AddStudent(string studentJSONString)
{
JavaScriptSerializer converter = new JavaScriptSerializer();
Student a = converter.Deserialize<Student>(studentJSONString);
WebMethods.AddStudent(a);
}
Which points to this code in my WebMethods.cs class
[WebMethod]
public static void AddStudent(Student student)
{
MasterStudent master = new MasterStudent();
master.AddStudent(student);
}
And finally that goes to my class library and finishes with this method in MasterStudent:
public void AddStudent(Student student)
{
if (string.IsNullOrWhiteSpace(student.Name))
{
throw new Exception("There's no name");
}
if (string.IsNullOrWhiteSpace(student.Email))
{
throw new Exception("There's no email");
}
using (studentEntities model = new studentEntities())
{
model.student.Add(student);
model.SaveChanges();
}
}
I run the code and the Console doesn't log any problems but it also doesn't do anything.
I have run very similar code on a Forms application with no problems so I'm kind of in a pickle right now. Does anyone know why it keeps failing?
Have you tried attaching a debugger to it and verifying that the student object is not null prior to model.SaveChanges() ?
Try debugging and verifying that the student string is being converted to an actual Student object first.
If it is, then try profiling the DB and validate any commands issued.
So I actually did find a solution shortly after posting my question, I changed my JQuery AJAX call to look like this:
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
$("#lblErrorAdd").text(response.responseJSON.Message);
$("#lblErrorAdd").css("display", "block");
}
});
And it actually works now! so either the dataType or contentType were very important for what I was trying to do
Thanks for your answers everybody
var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: student,
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
alert(response.responseJSON);
}
});
Then you can to point to this WebMethod.
[WebMethod]
public static void AddStudent(Student student)
{
MasterStudent master = new MasterStudent();
master.AddStudent(student);
}
Try this.

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

From javascript call play 2.1 controller function that returns json data object

How to make play 2.1 controller function execute a captured external url and return json data object to javascript.
First of all InputStream is not opening an external url. errors out saying no protocol
play doesn't like JSONObject as return.
code underway -
Javascript
$.ajax({
url: "/documents/getjsontext/" + talksUrl ,
type: 'GET',
data: "",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){ do_this(data);},
error: function () {alert("Error in Ajax Call");}
});
Route- /documents/acontext/:jsonurl controllers.Class.acontext(jsonurl: String)
public static JSONObject acontext(String jsonurl) {
InputStream is = new URL(jsonurl).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
first of all you need to add a JsRoutes class. i named it as "myJsRoutes"
public class CommonController extends Controller{
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("myJsRoutes",
routes.javascript.Controller_name.function()
);
}
}
now your js route is defined .and "myJsRoutes" can be further used to call in your scala file as :
myJsRoutes.controllers.Controller_name.function_name().ajax({
//your ajax handlers here
});

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Categories

Resources