Regex values in JSON response - javascript

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;
}

Related

Update (Javascript) collection column in MongoDB with array

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);
}
});

How i can replace data in data (JSRender)

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

Null parameter in controller from ajax

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");
}
});

How to properly format data object that includes array of objects for jQuery ajax put request? [duplicate]

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}

Post JSON data along with id in Jquery AJAX

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
});
}

Categories

Resources