Can we send data to controller till my array gets empty? - javascript

I have big array which exceed request object length so i am thinking to send data to controller in small data frames so that it will not get crashed on extending http request object limit and data will in after certain interval of time.....
var param = "&table=" + table; //remove first three charactor 'btn' from id
param = param + "&tblheader=" + tblheader;
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
dataType: 'text',
contentType: 'application/text; charset=utf-8'
});
controller :
[HttpPost]
public ActionResult SendReport(string table, string tblheader)
{
}

I Thinks your url isnt validate :
check this code please :
var param = { Table: table
Tblheader: tblheader }; //json data
var request = $.ajax({
url: '../Reports/SendReport'
data: param,
type: 'POST',
cache: false,
dataType: 'json',
contentType: 'application/text; charset=utf-8'
});

Create Json object and send using ajax
var ajaxPostDatastr = '{"table":"' + table + '","tblheader":"'+tblheader+'" }';
var jsonData = JSON.parse(ajaxPostDatastr);
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
contentType: 'application/text; charset=utf-8',
data: jsonData});
In controller use same as what you did right now.
Hope this will solve your issue

You can send large data via JSON. But you need to increase the maxlength of the json data in web.config.
Refer the post : Getting "The JSON request was too large to be deserialized"

All above way right to send data but when we are using
var param = "&table=" + table; //remove first three charactor 'btn' from id
param = param + "&tblheader=" + tblheader;
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
dataType: 'text',
contentType: 'application/text; charset=utf-8'
});
then we are passing data as a parameter to the $.ajax then it has a certain limit around param.length = 1600 then after $.ajax fail to execute
if you want to send huge data then you have to use View Model object and assign this values on data so it will work easily..
because as i m using Asp.net MVC ,in that view model is strongly bonded to view.so we can assign .if nay having better soln please share

Related

AJAX Call to Update table goes Null - ASP.NET

I'm trying to update my table using Ajax Call through this code
var customer = {};
customer.CustomerId = row.find(".CustomerId").find("span").html();
customer.Nome = row.find(".Nome").find("span").html();
customer.Tipo = row.find(".Tipo").find("span").html();
customer.NCM = row.find(".NCM").find("span").html();
customer.Contabil = row.find(".Contabil").find("span").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
But when I click to update the value it returns a System.NullReferenceException, I can't see where I'm doing wrong.
Here's my Controller Code
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
entities.SaveChanges();
}
return new EmptyResult();
}
System.NullReferenceException revealed the value updatedCustomer or customer is null.You need check which is null.
And when you want to update a enity in EF,you need add code like :
context.Entry(existingBlog).State = EntityState.Modified;
Howerver,Why you need Query A Entity befor update?I guess you want to do this:
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Entry(customer).State = EntityState.Modified;
entities.SaveChanges();
}
return new EmptyResult();
}
This AJAX callback below actually passed JSON string containing JSON object, which is wrong and causing customer contains null value which throwing NullReferenceException (it is strongly advised to put null check before using EF entity context):
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}', // this is wrong
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Instead of passing JSON string like that, just use data: JSON.stringify(customer) or simply passing entire object directly with data: customer and remove contentType setting:
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: customer,
dataType: "json",
success: function (result) {
// do something
}
});
Regarding second issue which selected data from table query is not updated, it depends on auto-tracking setting from EF. If auto-tracking is disabled, you need to set EntityState.Modified before using SaveChanges():
if (customer != null)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
// if EF auto-tracking is disabled, this line is mandatory
entities.Entry(updatedCustomer).State = System.Data.Entity.EntityState.Modified;
entities.SaveChanges();
}
}
Notes:
1) You can see all methods to update existing data with EF in this reference.
2) This fiddle contains sample to make AJAX request from a table contents.

Jquery.ajax GET not ending parameters

I am creating a UI for a content production area on a company intranet. I created the middleware API in a previous project. This is my first time using RESTful methods (and I'm fairly new to Javascript and jquery in the first place)
When I call my debugging local api from the jquery.ajax the JSON object is not being passed properly on my GET method.
In the C# API
[ActionName("THING")]
[HttpGet()]
public string GetThing(object json)
{
GetData getData;
if (json == null)
return null;
else if (json is string && (json as string).StartsWith("{"))
getData = JsonConvert.DeserializeObject<GetData>(json as string);
else
return null;
ItemReturn retVAl = new ItemReturn();
[logic to use JSON]
return retVal;
in the web page
loadThings: function (thingNumber, showBool) {
showBool = (showBool === true);
$.ajax({
type: "GET",
dataType: "json",
data: '{ "GetData" : {"ThingNumber":"' + thingNumber + '","Show": ' + showBool + '}}',
url: "http://localhost:11422/api/THING/THING/GetThing",
contentType: "application/json; charset=utf-8",
success: function (result) {
[logic to display things]
}
I can hit my breakPoint in GetThing fine, have it all working, but I can't seem to figure out why the object (json) in my overload is coming in null. I know it's something in the javascript, my unit tests work fine and my JavaScript is getting me to my breakpoint in the method, I just need to overload JSON object to actually be passed in
UPDATE
It is on the api side. I changed the overload of GetThing from (object json) to ([FromUri()] object json). This fixed the immediate issue but it is currently just translating the JSON object into a blank object
++Note: I had to change my post method overload to [FromBody()] rather than [FromUri()], I am yet to update the DELETE method to see which one that uses
So problem no1, you can't do this with GET. Two options
Use POST
stringify and use GET
1) So this is how you use POST
Fix your ajax request as follows:
$.ajax({
type: "POST",
dataType: "json",
data: { "GetData" : {"ThingNumber": thingNumber ,"Show": showBool }}, // JS object not string
url: "http://localhost:11422/api/THING/THING/GetThing",
contentType: "application/json; charset=utf-8",
Please read the $.ajax post documentation for instructions https://api.jquery.com/jquery.post/
2) Use GET
var obj = JSON.stringify({ "GetData" : {"ThingNumber": thingNumber ,"Show": showBool }}),
url = "http://localhost:11422/api/THING/THING/GetThing?json=" + encodeURIComponent(obj);
$.ajax({
type: "GET",
dataType: "json",
url: url, // Here we encode the obj for server
contentType: "application/json; charset=utf-8",
If you use this method you must change your controller to get json parameter as String and then parse it to JSON using your library of choice. How can I parse JSON with C#?
Could you try adding in the ajax settings: traditional:true,?

jQuery ajax post URL with query string cannot get $_POST in server side

My url parameter need to included the query string due to the system need to pass the token everytime request a link. I would like to use ajax POST to my PHP page.
Below is my ajax code:-
var data = new Array();
data[0] = $('#coupon_code').val();
data[1] = $('#coupon_value').val();
var jsondata = {"data": data}
var json = JSON.stringify(jsondata);
$.ajax({
url:"index.php?route=coupon/create&token=csrf1234567",
cache:false,
processData: false,
type: 'post',
dataType: 'json',
contentType: 'application/json',
data:{json},
success:function(){}
});
However, my PHP script is like below to make sure I have everything passed to server side:
public function create()
{
var_dump($_REQUEST);
}
It only have following output:-
array(2) {
["route"]=>
string(13) "coupon/create"
["token"]=>
string(11) "csrf1234567"
}
Inside the chrome insepct it shows
**Query String Paramaters**
route:coupon/create
token:csrf1234567
**Request Payload**
[object Object]
It does not have POST variable to pass to my PHP. I want to use type POST, and json to accomplish this, any idea how to solve it?
SOLVED:
data:{json},
change to
data:json,
Thanks for the solution!
SOLVED:
data:{json},
change to
data:json,
Thanks for guest271314!

Having trouble getting JSON data from database with AJAX

So as the title suggests, I am having difficulty retrieving data from my database with these technologies. This is my current situation:
var username = $('#username').val();
var password = $('#password').val();
// For the sake of example this is a dummy IP
var url = 'http://55.55.55.55/dbfuncts.php?action=getuser&user=' + username;
// For debugging purposes I compare this object with the one I get with the ajax function
var obj1 = {
"name" : "Dave"
};
var obj = $.ajax({
url: url,
type: 'POST',
dataType: 'json'
});
The format of my JSON is supposed to be like this:
{"UserID":"User","Password":"User","Email":"User#questionmark.com","Fname":"Web","Lname":"User","isManager":"0"}
When I go to the URL I am able to see this JSON string in my browser.
Currently when debugging, I find that I keep getting the jqXHR object instead of the json object that I want.
How do I retrieve the information as a JSON from the database?
I don't think jQuery ajax call will return the result directly as you did (but I'm not sure).
I used to get result from ajax call by using callback function as below.
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data) {
// data argument is the result you want
console.log(data);
}
});
Try this:
Place the url which gives the json data in the url column.
var jsonData = $.ajax({
url: '*',
dataType:"json",
async: false
}).responseText;
var parsed = JSON.parse(jsonData);
If this does not then try this:
var jsonData1 = $.ajax({
xhrFields: { withCredentials: true },
type:'GET',
url: '*',
dataType:"json",
crossDomain: true,
async: false
}).responseText;
var parsed1 = JSON.parse(jsonData1);
TRY 2:
Ok so try it with Spring MVC. Get the data from the database, and keep it in a url. As given in this link. Ckick Here And then use the above ajax call to access the data from the url.

List from Javascript to Post Method c#

Hi everyone i have a problem on javascript for pass the list from the result of form to post method in c#.
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#runProcess').click(function() {
var request = new WebPay();// is only a method where i take the result from the fiel of the form
var list = new Array();
list.push(JSON.stringify(request));
var jsonstr = {'':list};
$.ajax({
type: "POST"
url: "http://localhost:4556/Pay_Info"
datatype: "JSON",
data: jsonstr,
traditional: true,
success:function (data,textStatus, jqHr){
//build a grid with jquery
The post method is :
public HttpResponseMessage Pay_Info([FromBody] List Pay)
The fields are good i mean when i take the result from a form i have the right Json String but when i pass the array (list) in the post method the fields are empty i mean i have only the default fields of the form and not my json string result. The problem is when i pass the array to the post method.
Can you help me ??
list.push(JSON.stringify(request));
var jsonstr = {'':list};
You can not have object with empty key.make it like
list.push(request);
var jsonstr = JSON.stringify(list);
So with:
var list = new Array();
list.push(JSON.stringify(request));
var jsonstr = { '' : list };
$.ajax({
type: "POST",
url: "http://localhost:4556/Pay_Info",
dataType: "json",
data: jsonstr,
traditional: true,
something pass in the post method but the fields are with default values and not with my json string value. When i debug the count of the list is 1
With:
list.push(request);
var jsonstr = JSON.stringify(list);
$.ajax({
type: "POST",
url: "http://localhost:4556/Pay_Info",
dataType: "json",
data: jsonstr,
traditional: true,
In the list of post method the count was 0 and nothing pass
With:
var jsonstr = {Key:list}; or var jsonstr = {"Pay":list};
The count of the list in post method is 0 so nothing is passed

Categories

Resources