List from Javascript to Post Method c# - javascript

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

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.

how to overload an array in javascript?

thsi is my code:
var data_book_list=new Array();
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book:book},
success: function(data){
for(var i=0;i<data.length;i++)
{
data_list.push(data[i]);
}
}
});
imagine database like: list1 has a1,a2,a3 & list2 b1,b2,b3
if i selected value list1 ajax get that value and sent it to php.
php using where case so it gives back to ajaxa1,a2,a3
now data has a1,a2,a3 i make it that a new array form for loop like ['a1','a2','a3']
i push this to a var data_book_list=[];
it work great.
but my problem is if i select option list2
data hasb1,b2,b3 and data_book_list=[] has a1,a2,a3
for loop push data b1,b2,b3 to array data_book_list it will extend like ['a1','a2','a3', 'b1','b2','b3']
but i need like this ['b1','b2','b3] in array data_book_list. how to clear or overload old array data automatically.
If you need to keep track of all the values retrieved so far, then you will have to use an object and have the value as array, corresponding to the keys.
var data_book_list_obj = {};
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book: test_type},
success: function(data){
for(var i=0;i<data.length;i++)
{
data_book_list_obj[test_type] = data_book_list_obj[test_type] || [];
data_book_list_obj[test_type].push(data[i]);
}
}
});
Or if you need only the recent information, then just assign the value.
var data_book_list=new Array();
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book: test_type},
success: function(data){
// Edit removed for loop wrongly put here
data_book_list = data;
}
});

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.

Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "html",
success: function (data) {
var dataObj = data.replace(/"/g, '"');
console.log(dataObj);
}
});
I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:
[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?
You can use JSON.parse
JSON.parse(dataObj);
You can parse the returned HTML fragment as JSON:
JSON.parse(dataObj);
Change "dataType" to "json" and it will convert it for you:
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
}
});
If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.

Invalid JSON Primitive when using a variable

I have code that makes an AJAX call to an MVC controller method and it'll work without a hitch if I do this:
var obj = '{"titlename":"whatever"}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
But if I do this:
var stringed="whatever"
var obj = '{"titlename":stringed}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
It craps out on me with an "invalid JSON primitive" error. I keep trying various single and double quote permutations, but they all keep giving me the same error. How can I insert a string variable into a JSON object?
Try this:
var stringed = "whatever";
var obj = '{"titlename": "' + stringed + '"}';
Also you may want to take a look at a JSON2 library, which can stringify your data automatically.
Why are you declaring your object as a String?
Have you tried doing:
var stringed="whatever";
var obj = {
"titlename":stringed
};
var obj = {"titlename":stringed};
This is probably what you need.
Try this:
var stringed="whatever";
var obj = {"titlename": stringed};
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
What you had was just a string that contained the the string "stringed", you need a object literal.
jQuery can take an object and it'll take care of sending the json string to the server instead.
You should do:
var stringed="whatever";
var obj_as_object = {titlename: stringed};
var obj_as_string = JSON.stringify(obj_as_object);
...
data: obj_as_string //This goes in your ajax call
With this, we're auto encoding the obj with JSON.
JSON.stringify will work in modern browsers. If you want support to an older browser (for example, IE6) you should use a library such as json2 from http://json.org.
Hope this helps. Cheers
This isn't a great way to do it but..
var stringed="whatever"
var obj = '{"titlename":'+stringed+'}';
Or
var obj = {
"titlename":stringed
}

Categories

Resources