How do I place a json value using jquery? - javascript

I am sending selected fields to an API(3rd party app) from wordpress.
This is how my data array looks like:
var data_array = {
"order": {
"customer": {
"name": "The User"
}
}
}
I want to substitute the value of the "name" key to a javascript variable that contains a jquery selector. For example:
var name = j('.billing_company_name').html(result.meta_data[1].value);
I am thinking that the new code for the data_array will be:
var data_array = {
"order": {
"customer": {
"name": name(variable name jquery selector)
}
}
}
Do you know the correct syntax so I can substitute the value of "name" key with the value of the jquery selector?
The final code will look like the code below:
j.ajax({
type: 'POST',
url: 'http://mywebsite/api/orderdetails',
cache: false,
data: {
"data_array": data_array
},
beforeSend: function() {
},
success: function(result) {
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {
}
});

I need the value of the element to be place inside the value of data_array.order.customer.name
In this case you can use val() to select that property. If you want to do it as you instantiate the object, use this:
var data_array = {
"order": {
"customer": {
"name": name.val()
}
}
}
Or if you want to do it after declaring data_array (which is badly named, as it's an object not an array), then you can use this line:
data_array.order.customer.name = name.val();

Related

Datatable returning 0 results

I need to load a datatable with a JSON dataset. I don't want to do server side processing. but I do want to retrieve the full set of data from a URL. I got to the point where there's no error on load but for some reason, the table stays empty with 0 results.
I am building the JSON on the server side like this:
public static function datatableOutput($array){
foreach($array as $key=>$line){
$output[] = [
"href"=>$line['href'],
"code"=>$line['code'],
"time"=>$line['time'],
"img_count"=>$line['img_count'],
"int_count"=>$line['int_count'],
"ext_count"=>$line['ext_count']
];
}
return array('data'=> $output);
}
Later in the code it returns a json string like this:
return response()->json($this::datatableOutput($links));
And in the view my script looks like this:
$.ajax({
url: '/crawl',
type: "post",
data: {
url: $("#url").val(),
pages: $("#pages").val(),
_token:"{{ csrf_token() }}"
},
dataType : 'json',
success: function(data){
// Done state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#crawl').hide();
$('#report_section').show();
$('#report').DataTable( {
data: data,
columns: [
{ title: "href" },
{ title: "code" },
{ title: "time" },
{ title: "img_count" },
{ title: "int_count" },
{ title: "ext_count" }
]
} );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Error state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#goaheaddude').show();
$('#error').show();
}
});
The JSON data set returned looks like this:
{
"data":[
{
"href":"\/",
"code":200,
"time":0.2746608257293701,
"img_count":6,
"int_count":204,
"ext_count":6
},
{
"href":"\/feature\/automated-marketing-reports",
"code":200,
"time":0.1753251552581787,
"img_count":7,
"int_count":72,
"ext_count":6
},
{
"href":"\/feature\/marketing-dashboard-2",
"code":200,
"time":0.15781521797180176,
"img_count":8,
"int_count":73,
"ext_count":6
}
]
}
Everything seems to be valid but for some reason I still get 0 results ... I am probably missing something obvious thought. I tried the JSON with and with out the "data" array.

extract an URL from a JSON response of wikipedia api

I need to extract the URL of an image from a JSON response (maybe I could put it in a variable).
I read this page on the MediaWiki API help
I follow this example to get the information about images on a page:
https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
that return this JSON:
{
"batchcomplete": "",
"query": {
"pages": {
"2061": {
"pageid": 2061,
"ns": 0,
"title": "Albert Einstein",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/75px-Albert_Einstein_Head.jpg",
"width": 75,
"height": 100
},
"pageimage": "Albert_Einstein_Head.jpg"
}
}
}
In which way can I extract the URL of the image?
I tried this:
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages.2061.thumbnail.source;
var stgurl = JSON.stringify(urlImage);
alert(stg);
}
})
but doesn't work.
Yes, it doesn't work because this url: https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100 doesn't return JSON but HTML. If you want the JSON representation, you need to append &format=json to your url.
Change data.query.pages.2061.thumbnail.source to data.query.pages["2061"].thumbnail.source as you can't use numbers in a dot notation.
And also the alert; change stg to stgurl
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages["2061"].thumbnail.source;
//var stgurl = JSON.stringify(urlImage); - unnecessary JSON.stringify
var stgurl = urlImage;
alert(stgurl);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to use the solution in this post:
iterating through json object javascript
Use the recursion in this way:
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
it seems to work.

How to print out object properties within for-in loop?

I'm getting a list of objects from an API which looks like this:
{
"results": [
{
"date": "2014-09-25 19:00:00",
"title": "Hitjeskanon"
},
{
"date": "2014-09-25 21:00:00",
"title": "Black & White ESN House & Techno"
},
{
"date": "2014-09-25 21:00:00",
"title": "Hit It!"
}
]
}
I now get these results from the API, and want to log them, which I try as follows:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result['results']);
for (event in result['results']) {
console.log(event['title']);
}
}
});
In the console, I correctly see the objects with the first two logs, but the console.log(event['title']) only prints out undefined.
What am I doing wrong here? All tips are welcome!
result['results'] is actually an Array. So, you should iterate it with normal for loop like this
for (var i = 0; i < result['results'].length; i += 1) {
console.log(result['results'][i]['title']);
}
Or you can use Array.prototype.forEach like this
result['results'].forEach(function(currentObject) {
console.log(currentObject['title']);
});
Also, you can access the attributes with the dot operator, like this
console.log(result.results[i].title);
or
console.log(currentObject.title);
You could use a traditional for loop, but if you don't need random access (e.g., results[2]) you can use a for...of statement (introduced in ECMAScript6). In your code, just change for...in to for...of:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result['results']);
for (event of result['results']) {
console.log(event['title']);
}
}
});
And like #thefourtheye mentioned, you can access the results array and the event's title property with the dot operator:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result.results);
for (event of result.results) {
console.log(event.title);
}
}
});
This page is a great reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

returning another page's variables using AJAX

I am using AJAX to try and return list items. The list items are stored on another page as a var. The var is called WPQListData. This var is viewable in the page source.
var WPQ2ListData = { "Row" :
[{
"ID": "1",
"PermMask": "0x7fffffffffffffff",
"FSObjType": "0",
"Title": "test",
"FileLeafRef": "1_.000",
"Created_x0020_Date.ifnew": "",
"FileRef": "\u002fsites\u002fResilient\u002fLists\u002fNewsSliderList\u002f1_.000",
"File_x0020_Type": "",
"File_x0020_Type.mapapp": "",
"HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon": "",
"HTML_x0020_File_x0020_Type.File_x0020_Type.mapico": "icgen.gif",
"ContentTypeId": "0x0100B87D22D691BA4B419255256292F918AA00B2962D0F358E9442AFF496C5DFF6AB1F",
"Body1": "test"
}
Id like to get this variable using AJAX. I'm currently trying the following:
$.ajax({
url: ctx.HttpRoot+"/Lists/NewsSliderList/AllItems.aspx",
type: "GET",
success: function (data) {
var dataDom = $(data);
var stripped_data = $(dataDom).find("WPQ2ListData");
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
Is it possible to get Vars via AJAX, and if so then what am i doing wrong?
thanks

loading a JavaScript file with vars not set at load time

the post title may not explain fully, but here is what I am hoping to do: I have my JavaScript code in a separate file, and I have it arranged like so
var PK = {
"vars" : {
"uris" : {
"app1": "http://this/server/",
"app2": "http://that/server/"
},
"something": {
"objects": [],
"obj1": { "url": PK.vars.uris.app1 },
"obj2": { "url": PK.vars.uris.app2 }
}
},
"methods" : {
"doThis" : function(a) {
$.ajax({
url: PK.vars.uris.app1,
data: data,
type: "GET",
success: function(data) { .. do something .. }
});
},
"doThat" : function(a) {
$.ajax({
url: PK.vars.uris.app2,
data: data,
type: "GET",
success: function(data) { .. do something else .. }
});
},
"init" : function(position) {
if (position) { PK.methods.doThis();
}
else {
PK.methods.doThat();
}
}
}
};
and then, in my html, I have the following
$(document).ready(function() {
PK.vars.uris.app1 = "[% app1 %]";
PK.vars.uris.app2 = "[% app2 %]";
PK.methods.init();
});
where the values of app1 and app2 are sent from the server based on a config file. Except, it doesn't work as expected, because, when the separate JavaScript loads, PK.vars.uris is not defined at that time. Of course, everything works beautifully if I have PK.vars.uris{} hardcoded.
How can I delay the evaluation of var PK until after the document has loaded and PK.vars.uris is available to be used in the JavaScript code?
Is the problem that you need to pass values into an initialiser?
How's this approach:
In your external file:
function PK_Constructor(app1Uri, app2Uri) {
this.vars = { "uris" : {
"app1" : app1Uri,
"app2" : app2Uri
},
"something": {
"objects": [],
"obj1": { "url": app1Uri },
"obj2": { "url": app1Uri }
},
};
this.doThis = function(a) {
$.ajax({
url: this.vars.uris.app1,
data: data,
type: "GET",
success: function(data) { .. do something .. }
});
// etc
}
And in you HTML:
// Ensuring PK has global scope
var PK = undefined;
$(document).ready(function() {
PK = new PK_Constructor("[% app1 %]", "[% app2 %]");
});

Categories

Resources