When attempting to update a mongoDB collection with an array as the value, the update fails silently.
This does not work:
var arr = ["test","test1","test2"];
$.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , {
type: "PUT",
contentType: "application/json",
data: JSON.stringify({
mykey: arr
}),
success: function() {
// Do something
},
error: function(xhr) {
console.log(xhr.responseText);
}
});
This does:
$.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , {
type: "PUT",
contentType: "application/json",
data: JSON.stringify({
mykey: "test"
}),
success: function() {
// Do something
},
error: function(xhr) {
console.log(xhr.responseText);
}
});
It turns out I need to stringify the array before stringifying it within the ajax data:
var arr = ["test","test1","test2"];
arr = JSON.stringify(arr);
$.ajax('http://mordor.fmr.com:8030/techtest?id=80a2c727de877ac9' , {
type: "PUT",
contentType: "application/json",
data: JSON.stringify({
assignedTechs: arr
}),
success: function() {
// Do something
},
error: function(xhr) {
console.log(xhr.responseText);
}
});
Related
I want to regex JSON response value in AJAX without losing the structure of JSON.
Here is the ajax
$.ajax({
url: "date.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
headers: {
"X-Requested-With": "XMLHttpRequest",
},
success: function(data) {
var formDatax = new FormData();
var date = data.results;
var res = date.map(function(item) {
return {
"images": item.images
};
});
$.ajax({
url: "json.php",
type: "POST",
data: JSON.stringify(res),
processData: false,
contentType: false,
dataType: "json",
headers: {
"X-Requested-With": "XMLHttpRequest",
},
success: function(data) {
},
error: function() {}
});
},
error: function() {}
});
Here is an example of JSON Response
{
"part_number_key":"DDASDAS",
"name":"ASD",
"description":"asd",
"price":12,
"general_stock":12,
"brand":"ASD",
"category_id":2776,
"images":[
{
"url":"https://asd.com/asd/asd/1241.jpg",
"display_type":1
},
{
"url":"https://asd.com/asd/asd/73223.jpg",
"display_type":0
},
{
"url":"https://asd.com/asd/asd/214121.jpg",
"display_type":0
}
],
"warranty":24
},
I want to get the link of the image where the display_type is having value 1, so I thought it's ok if I regex the first url before "display_type":1 but I'm not able because this is not string to regex.
/(https?\:\/\/[^\" ][^]).*("display_type":1)/i
The regex, it's not complete because I saw the problem about the string I didn't tried to complete the regex...
You could parse the JSON and use filter and map to get the images URL
success: function(data) {
var response = JSON.parse(data)
var imagesURL = response.images.filter(image => image.display_type).map(image => image.url)
}
The response type is always parsed JSON. You can just access the images which have display_type: 1 like so:
let fileterImages = data.data.images.map((image) => {
if(image.display_type === 1) return image.url;
}
I have sent request to get Data from API
So data return like
Check here to see Data response
So i want to replace data in "launchUrl" such playerName
This is my code
$.ajax({
type: "POST",
url: "{{ $luckyStreakLobbyAPI }}",
dataType: 'json',
data: {
Data: {
Open: true,
GameTypes: [],
Currencies: []
}
},
headers: {
"Authorization": "Bearer " + "ey"
},
success: function (data) {
$.views.settings.delimiters("<%", "%>");
var data = data.data.games,
tmpl = $.templates('#luckyStreakTables'),
html = tmpl.render(data);
console.log(data);
$('.row.tables').html($('#luckyStreakTables').render(data));
}
});
So data from api will return in "success: function(data)"
How i can replace data in data.data.games.launchUrl
When a user clicks a save button, a JavaScript function uses AJAX to call the Controller and send over JSON data about the objects.
JavaScript Function
$.ajax({
url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
type: "POST",
data: JSON.stringify($scope.items.data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
Controller
[HttpPost]
public ActionResult SendFridgeItems(string items)
{
fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
foreach (fridge item in fridgeItems)
{
bool exists = cookDB.fridges.AsEnumerable()
.Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
if (!exists)
{
cookDB.fridges.Add(item);
cookDB.SaveChangesAsync();
}
}
return null;
}
It works, but I don't think the way of sending my data through the url parameter is correct in my situation, because the data will be big enough. I wanted to know if there is a better way to send my data to the controller?
I tried to send it this way, but the controller receives null value.
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
data: JSON.stringify($scope.items.data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
JSON of $scope.items.data
[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]
$scope.items
$scope.items = {
"count": 2,
"data": [
{
"name": "Item1",
"count": 2,
"type": "pcs.",
"purchased": "12/09/2017",
"wasted": "15/10/2017",
"cam": "Freezer",
"comment": "no comment"
},
{
"name": "Item2",
"count": 30,
"type": "g.",
"purchased": "15/01/1880",
"wasted": "21/03/1882",
"cam": "Cooler",
"comment": "Commented"
}
]
};
Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)
public ActionResult SendFridgeItems(fridge[] items)
{
fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
foreach (fridge item in items)
{
bool exists = cookDB.fridges.AsEnumerable()
.Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
if (!exists)
{
cookDB.fridges.Add(item);
cookDB.SaveChangesAsync();
}
}
return null;
}
The data field in ajax takes in an Object, you are giving it a string. Try and supply only your object, assuming that $scope.items.data is an object. If you give a bit more information on what $scope variable is, then I can give you a better answer.
Code:
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
d̶a̶t̶a̶:̶ ̶$̶s̶c̶o̶p̶e̶.̶i̶t̶e̶m̶s̶.̶d̶a̶t̶a̶,̶
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
Hope this helps!
EDIT:
Further inspection after you have provided the contents of $scope.items.data led me to notice that $scope.items.data is an array of objects. So in order for the ajax to work and actually supply valid JSON, try the following code:
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
data: { "items": $scope.items.data },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
I have verified that { "item": $scope.items.data } is a valid JSON through JSONLint
Hope this solves your problem!
Try JSON Parse to parse data as Object and send it to controller
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
data: JSON.parse($scope.items.data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
I have a result from Fiddler (please see the attached image), how can I get the results where the arrow is pointing to?
This is what I have done so far and thank you:
function GetRefiners() {
$.ajax({
url: "myUrl",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
$.each(data.d.query, function(list){
});
},
error: function(error){
alert("Error message\n" + JSON.stringify(error));
}
}
);
}
Simply go to the results objects and iterates over it
function GetRefiners() {
$.ajax({
url: "myUrl",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
$.each(data.d.query.PrimaryQueryResult.RefinementResults.Refiners.results.Entries.results, function(list){
callWhatYouNeed();
}
};
},
error: function(error){
alert("Error message\n" + JSON.stringify(error));
}
}
);
}
I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}