I am using Yii2 framework I need to send an array containing id of person and an array of id of groups from client to server.
I got the data from a Select2 component using jQuery. Then the server will response so the client can show it in a form. I mean it is not a Create or Update button of Yii2.
The client side send this json object:
var jsonData = {
persons: 111,
groups: [222, 333]
};
$.ajax({
url: "/persons/persons?idsGroups=",
data: jsonData,
dataType: 'json',
success: function(res) {
console.log(JSON.stringify(res, null, 4));
}
});
From ther server I need to get the groups but it doens't work:
public function getMyGroups($groups) {
return $groups;
}
My browser shows:
error{"readyState":4,"responseText":"Bad Request (#400): Invalid data received for parameter \"groups\".","status":400,"statusText":"Bad Request"}
But if I change the getMyGroups function to get the persons variable, it works:
public function getMyGroups($persons) {
return $persons;
My browser shows:
111
So what this error means? I think I am sending data in a wrong way but I don't know how to fix it.
I resolved in this way using this help: https://api.jquery.com/jquery.post/
var jsonData = {
'persons': 111,
'groups[]': [222, 333]
};
$.post("/persons/persons", jsonData)
.done(function(data) {
console.log("Data loaded: " + data);
});
Related
My backend API accepts data in JSON format, such as:
{ "article_id" = 1 }
In the front-end, I tried to add the following javascript to a button:
function articleIsSelected(id) {
let data = '{"article_id":' + id + '}';
$.ajax({
url:"https://www.myurl.com",
data: data,
type: "post",
contentType: "application/json",
success: function () {
alert("Selection succeeded!");
},
error: function () {
alert("Selection failed.");
},
});
}
It returns that the request was successful, but my database is not updated. There is something wrong with the data format. Instead of trying to hard code the data in JSON format, one should sign the value to "article_id" and then JSON encode it with JSON.stringify(data).
The data is not proper JSON, change it to:
let data = {"article_id": id};
And make sure you encode it:
JSON.stringify(data)
In asp I have a function as:
public async Task<IHttpActionResult> updateComment(int id, Comment comment)
{
//some stuff
}
To send data to this function I have created an ojbect as (I am working with knockout.js):
var com = {
id: self.id,
description: self.description,
postedBy: self.postedById,
time: new Date($.now()),
adId: self.adId,
};
And in ajax request I am sending data as:
$.ajax({
url: '/api/Comment/updateComment',
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: { id: com.id, comment: com },
success: function (data) {
alert("done");
},
error: function () {
alert("error");
}
});
But request does not goes to above asp.net function. I got error in browser console window 404 (Not Found) . Error is because it is not receiving comment object as it was expecting. I changed ajax request method to get to see url and url is below.
Is there something wrong with my defined com function? Why its not working?
Update:
public async Task<IHttpActionResult> updateComment()
{
//some stuff
}
I changed the function as above and its working fine. So it is confirmed that is some problem with com object. Function is not receiving object as it was expecting.
Update 2:
Now I changed function parameters to:
public async Task<IHttpActionResult> updateComment(Comment comment)
{
//some stuff
}
and send data as:
data: ko.toJSON(com),
and its again working fine!
error code is 405:Method not allowed i guess this is something like, your ajax is type:"Post" request but your backend is expecting some GET requests.
Another suggestion is that you can send a stringified object with this:
data : '{ "id":"' + com.id + '", "comment":"' + com + '"}',
If you are using ajax post with two parameters class object and other type you need to create other obj like below:
Note: Make sure that all properties of com object are same like your Comment class.
var com = {
id: self.id,
description: self.description,
postedBy: self.postedById,
time: new Date($.now()),
adId: self.adId,
};
var obj = {};
obj.id = com.id;
obj.comment = com;
And pass data using JSON.Stringy(obj) like below:
data: JSON.stringify(obj),
I had tested the code it is working check below screen shot:
I'm using angular to save new data on the database, I take the data from my inputs, put it in a object and I convert it to a Json, I send it by POST, but my JSON gets cut off and I have no clue why is it happening.
var myJson = angular.toJson(myObject);
$http({
method: 'POST',
url: 'http://url/file.php',
data: {
'data': myJson
}
})
.success(function (data){
console.log(data);
})
My file.php has a var_dump($_POST) in it, and it shows that:
[
{
"uuid":"56456456456456456456465456"
},
{
"store_name":"",
"store_email":"",
"store_facebook":"",
"contact_name":"John Doe",
"contact_email":"email#email.com",
"contact_facebook":"http://localho
Angular's http post method sends whatever data it is passed to. You should check your generated json data after
var myJson = angular.toJson(myObject); using console.log(myJson);
and that itself must be cut off.
var xyz= {
a: ko.observable(),
b: ko.observable(),
c: ko.observable(),
d: ko.observable()
};
function setupControlEvents()
{
$("#save").on("click",handleSave);
}
function handleSave()
{
var data = ko.toJSON(xyz);
//alert("data to send "+data);
//var d = serializer.serialize(data);
url ="../save";
http.post(url,data).then(function(){
alert("success");
console("save was success");
});
I am able to get the data but unable to save .. when i alert the data that i am sending i get this
data to send {"a":"A","b":"B","c":"C","d":"D","observable":{"full":true}}
i tried to serialize with durandal's serialize.serialize() but still not working ..
i think i am unable to send the data because i am getting obserbvable in json data so please kindly help me to solve this..
You are applying ko.toJSON() twice. The method post from the http plugin in Durandal is already doing it. Take a look at the method code:
post:function(url, data) {
return $.ajax({
url: url,
data: ko.toJSON(data),
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
}
So you only need to do this:
url ="../save";
http.post(url,xyz).then(function(){
alert("success");
console("save was success");
});
Hi I am creating using Javascript an array of object with a key and a value using the following code.
ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });
As a result I have am array of object like this:
key:29; value: 'Country'
Key:12; value: '4,3,5'
when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify
var jObject = JSON.stringify(ValuesArray);
My JSON now which is wrong is:
{
"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"
}
I would like to have a JSON object like this
{
"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]
}
without the quotes around the [] and the character \
Any good idea to solve it.
Thank you
More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:
function PostAPIRequest(address) {
var jObject = JSON.stringify(ValuesArray);
var responseJson = null;
$.ajax({
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
ProcessDataResponse(responseJson);
//TODO: REFRESH THE DATA GRID
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.
alert(xhr.status);
alert(thrownError);
}
})
}
and this how I am receiving it in my API controller
...
// POST api/datavalues/5
public string Post(int id, JObject value)
{
var temp = value;
...
It looks like you are placing a string as the value in your map. You should do something like:
var objMap = {"JObject" : ValuesArray};
var json = JSON.stringify(objMap)
What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.
EDIT
It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for - http://jsfiddle.net/4G5nF/
In your post request, try this
var jObject = {"JObject" : ValuesArray};
$.ajax({ url: address,
type: 'POST',
dataType: 'json',
data: jObject,
success: function (data) { .. }});
Note the change in the data attribute. That is a value that is automatically JSONified for you.
const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))
"{\"a\": 1, \"b\": 2}"
May be you have an old prototype library.
As I remove it, bug has disappeared