Invalid JSON Primitive when using a variable - javascript

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
}

Related

Pass null value to controller

I have a variable which I want to pass to controller, it's a date format which I want to send it as seconds,
var f = $("#from").val(); var from_mili = Date.parse(f);
Here is my AJAX request:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("EventEntries", "Turbine")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"from": (from_mili / 1000) }),
success: function (result) {
debugger;
}
});
The problem is when I divide it by 1000 to get seconds out of it in controller I get null but when I send without the division I get the value.
public JsonResult EventEntries(long? from = null)
To complete the #phuzi answer, there's another mistake in your code.
The first is the division of a Date with a number. #phuzi's answer gives a solution for this issue.
The second issue is that you use stringify in you ajax call which is useless because of your contentTypeset to json.
So your code should look like this:
var f = $("#from").val();
var from_mili = Date.parse(f);
var from = Math.floor(from_mili / 1000);
var data = { from: from };
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("EventEntries", "Turbine")",
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
debugger;
}
});
Then, the default value for your fromargument in C# is useless: you're using a nullable type. It does not solve an issue but it's an advice about something which is useless.
public JsonResult EventEntries(long? from)
Your variable from_mili appears to be getting set incorrectly: f is being set to a string which comes out as NaN when passed to Date.parse() which then breaks when divided by 1000.
Try this instead:
var f = $('#from').val();
var from_mili = Date.parse (parseInt (f));
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("EventEntries", "Turbine")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"from": (from_mili / 1000) }),
success: function (result) {
debugger;
}
});
You're trying to divide a Date object by a number!
Change
var from_mili = Date.parse(f);
to
var from_mili = Date.parse(f).valueOf();

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

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.

Convert an xml node to string

I'm getting an xml answer from a server using jquery and I need to have one of its child nodes as a string to further work with it.
Here is my code:
function pollServer(dataObject) {
$.ajax({
type: "POST",
url: '/server.php',
data: dataObject,
success: function (data) {
$xmlDoc = $(data);
$listen = $xmlDoc.find('listen');
console.log($listen);
},
dataType: 'xml'
});
}
I already tried using (new XMLSerializer()).serializeToString(listen) but that gives me an empty string.
The following should work fine for XML:
var listen = $("listen", data)[0].outerHTML;

Categories

Resources