How i can replace data in data (JSRender) - javascript

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

Related

How to shorten URL with Bitly V4 API and jQuery

So I am trying to shorten an URL with the new V4 Bitly API, but I am getting an JSON error.
My code:
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "xxx";
var params = {
"long_url" : encodeURIComponent(url)
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/bitlinks",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: params
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.error(data);
});
});
});
Results: a 422 http error;
"{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}"
But running it with CURL does work though: How to shorten URL using PHP Bitly v4?
What am I doing wrong? Is it not possible with jQuery only?
TIA.
I had made this edit from your code above and its working well.
1) JSON.stringify before sending request (convert your request to JSON format).
2) No need for encodeURIComponent().
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "token";
var params = {
"long_url" : url
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/shorten",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: JSON.stringify(params)
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
});
});

Regex values in JSON response

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

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

How to update jqx grid using jquery

$.ajax({
url: "RequestHandler?usercommand=showcriticaldatezone&useraction=ShowUserPreferenceDashbord_frm&subCommand=criticaldatezone",
type: 'POST',
dataType: 'json',
data: dateText,
contentType: 'application/json',
async:'false',
cache:'false',
success: function (data) {
var parsedJSON = JSON.parse(data);
var tempdate;
alert("parse json - "+parsedJSON.length);
js= [];
for (var i=0;i<parsedJSON.length;i++) {
alert(" critical date is -:"+parsedJSON[i].CriticalDate);
js.push(parsedJSON[i].CriticalDate);
//tempdate='{"Date":['+'"'+ parsedJSON[i].CriticalDate + '"' + ']}';
}
tempdate='{"Date":'+JSON.stringify(js)+'}';
alert("stringify is -:"+tempdate);
selectedDate=tempdate;
jqxgriddata=data;
$(this).datepicker("refresh");
jQuery("#myGrid").setGridParam({ 'data': data}).trigger("reloadGrid");
alert('sucess!');
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
i am using above code to refresh grid after server response but not success i am using jqx grid Server response is json array i am able to display grid at first time but not able to refresh it please help

" Google API message " : " This API does not support parsing form-encoded input. "

I have written the following javascript to create a tasklist in google:
postData = {'title':'Netsuite List'};
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
The response says:
{ "error":
{ "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." }
}
What could be the possible error ?
not working
contentType: 'application/json; charset=UTF-8',
try with this
var headers = { };
headers["Content-Type"] ="application/json ; charset=UTF-8";
//remove to parsing form-encoded input error
data:JSON.stringify( model),
//this use for remove to parse error
Example:
$.ajax({
type: 'Post',
url: postUrl,
headers: headers,
dataType: 'json',//not required in some case
data:JSON.stringify( model),
success: function (data, sts) {
alert('success');
},
error: function (err, sts) {
var msg;
}
});
You sent data like:
title=Netsuite%20List
But Google API waits for JSON:
{ "title": "Netsuite List" }
Try to provide JSON.stringify() output to the requestURL method:
postData = JSON.stringify({'title':'Netsuite List'}); // <-- Added JSON.stringify
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
Also, it's better to get around documentation or source of $$ object you use and check how it can support sending JSON data.
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
beforeSend: (xhr) => {
xhr.setRequestHeader("Content-Type", "application/json");
},
//...
or :
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
contentType: "application/json",
//...

Categories

Resources