Javascript error parsing http response - javascript

I am trying to parse the response from the www.skiddle.com API in Javascript:
$.ajax({
url: 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
type: "GET",
success: function(response) {
var list = [];
$(response).find("results").each(function() {
var el = $(this);
var obj = {
"eventname": el.find("eventname").text(),
"imageurl" : el.find("imageurl").text(),
};
list.push(obj);
});
The response actually has a results property with one element in the array:
{error: 0, totalcount: "1", pagecount: 1, results: Array(1)}
but I can't seem to parse it correctly, $(response).find("results") returns nothing.

If you are sure that there will be a result array property in your response, you may simply use response.results which gives you the array.
success: function(response) {
$.each(response.results,function(indx,item){
console.log(item);
var obj = {
eventname: item.eventname,
imageurl : item.imageurl
};
list.push(obj);
});
}
Assuming list is an array defined earlier.
Also if you are sure there will be only one item in the array, you do not need a loop, you can access it via response.results[0]
success: function(response) {
if (response.results.length>0) {
var obj = { eventName: response.results[0].eventname,
imageurl : response.results[0].imageurl };
list.push(obj);
}
}
I also noticed that the your new object has the same property names as the object you are iterating. In that case, you can simply add the same object
list.push(response.results[0]);
Of course this will add the first item as it is , which means if that has additional properties (other than eventname and imageurl) those will be present in the item you are adding to list now..

The response you are getting is a JSON, you are trying to parse it as XML.
The list you are trying to get can be obtained by simply using
success: function(response) {
var list = (response.results || []).map(function(result) {
return {
eventname: result.eventname,
imageurl : result.imageurl
};
});
}

Related

Passing an array to parse through AJAX

I'm trying to pass an array through an AJAX call to the backend, the array gets pushed to the backend, but I'm getting the error "Trying to get property 'id' of non-object"
This is the
var items = [];
$("input:checkbox[name='refundcheck']:checked").each(function(){
let id = $(this).val();
let item = {
"id": id,
"quantity": $('#quantity'+id).val()
};
items.push(item);
});
$.ajax({
type: "GET",
url: '{{url("/")}}/products',
data: {items:items},
dataType: 'JSON',
beforeSend:function (){
//$("#loadingDiv").show();
} ,
success: function( msg ) {
}
});
This is the console log for that array
I've tried both of these possibilities
$productarraylist = $request->items;
foreach($productarraylist as $item){
$product= dbtable::find($item->id);
}
AND
foreach($productarraylist as $i=> $item){
$product= dbtable::find($item->id);
}
This is the var_dump result of the array in the backend.
I tried to JSON.decode the array on the backend, and it says I need to pass a string, not an object.
You are dealing with arrays and not objects, try this:
foreach($productarraylist as $item){
$product= dbtable::find($item['id']);
}

Parsing associative array via AJAX

I have the following associative array and i try to send it to the server via AJAX.
Checking my console, in the network tab, it's posted but nothing is parsed.
Array creation:
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
Assoc array (console.log):
[category: "6", Type1: "998", Type2: "20100100"]
Request:
$.ajax({
type: POST,
url: 'something.php',
data: {
data: FiltersArray
}
}).done(function(data) {
console.log('Server Response: ' + data);
})
Complete code:
$(document).ready(function() {
var filters = {
category: $("#categoryInp"),
type1: $("#type1Inp"),
type2: $("#type2Inp"),
button: $("#FilterBtn"),
returnArray: function() {
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
return FiltersArray;
},
sendRequest: function(type, URL) {
$.ajax({
type: type,
url: URL,
data: JSON.stringify(this.returnArray()),
beforeSend: function() {}
}).done(function(data) {
console.log('Server Response: ' + data);
}).fail(function() {
alert("An error occurred!");
});
}
};
filters.button.on('click', e => {
console.log(filters.returnArray());
filters.sendRequest('POST', 'Modules/Products.order.module.php');
});
});
There is no such thing as an associative array in JavaScript.
There are objects, which hold key:value pairs of data.
There are arrays, which are a type of object that provides special behaviour when the key name is an integer.
jQuery distinguishes between arrays and other kinds of objects when you pass one in data.
If you pass an array it will not do anything with key:value pairs where the key is not an integer.
Use a plain object and not an array for this.
Aside: Variable names beginning with a capital letter are traditionally reserved for storing constructor functions in JavaScript. Don't use that naming convention for other kinds of data.
var filters = {};
filters['category'] = this.category.val();
filters['Type1'] = this.type1.val();
filters['Type2'] = this.type2.val();
It would be easier to just collect all the data as you create the object though:
var filters = {
category: this.category.val(),
Type1: this.type1.val(),
Type2: this.type2.val()
};
Aside
data: {
data: FiltersArray
}
This will create a (seemingly pointlessly) complex data structure that you'll need to access in PHP as $_POST['data']['category'].
You probably want just:
data: filters
Aside
data: JSON.stringify(this.returnArray()),
This will send JSON instead of form encoded data.
If you do that then you'll also need to:
Set the contentType of the request to indicate that you are sending JSON
Explicitly parse the JSON in PHP
So you probably don't want to do that.

Accessing an object property without knowing it's parent with a for in loop

I am trying to access a value retrieved from an external API. Specifically, it's a shortened URL. The shortener takes the long URL saves it as an object itself within an object and places the shortened URL within this object (see screenshot).
I won't know the exact value of the long URL so I am trying to use a for in loop to access the shortUrl (since I know that is always the name if it's key) and for now print it to the console.
I get variations of undefined, [object, object] or null.
What is missing here?
longUrl = "longUrl=" + longUrl;
$.ajax({
type: 'get',
dataType: 'jsonp',
url:'http://api.shortswitch.com/shorten?apiKey=3f5f69733156cce575b9a7ab1783ff4f4f0a8b5c&format=json&',
crossDomain: true,
data: longUrl,
success: function(data){
for (var shortUrl in data){
if(data.hasOwnProperty(shortUrl)) {
console.log(data[shortUrl]);
}
}
}
});
Please try use data.results instead of data:
var shortURLs = [];
for(var key in data.results) {
shortURLs.push(data.results[key].shortUrl);
}
console.log(shortURLs);
Demo:
var longUrl = {longUrl: "http://stackoverflow.com/questions/38417777/accessing-an-object-property-without-knowing-its-parent-with-a-for-in-loop/38417810#38417810"};
$.ajax({
type: 'GET',
dataType: 'jsonp',
url:'http://api.shortswitch.com/shorten?apiKey=3f5f69733156cce575b9a7ab1783ff4f4f0a8b5c&format=json&',
crossDomain: true,
data: longUrl,
success: function(data){
var shortURLs = [];
for(var key in data.results) {
shortURLs.push(data.results[key].shortUrl);
}
console.log(shortURLs);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You appear to be on the right track with iterating through the object's property and accessing that key. Based on your example data, you should be checking data.result not data.
Here's an example plunkr: https://plnkr.co/edit/7De7ZVPHz7x2n1OcKXmi?p=info
Here's the relevant code:
var data = {
errorMessage: "",
statusCode: "OK",
errorCode: "0",
results: {
"http://hello?cmp=EXP:da:paid::320x50": {
hash: "B3uXHF",
shortUrl: "http://at.law.com/B3uXHf",
longUrl: "http://hello?cmp=EXP:da:paid::320x50"
}
}
};
function getShortURL(data) {
for (var property in data.results) {
if (data.results.hasOwnProperty(property)) {
return data.results[property].shortUrl;
}
}
}
console.log(getShortURL(data));
Since you do not know the longUrl, you just need to access that object's child properties to access the shortUrl key. You really are just iterating through the indexes of the object.

Backbone.js Unable to parse response from collectio.toJSON()

I am learning Backbone and it would be great if someone can help me with this issue. After I do a fetch on my collection, in success callback I get the parsed data using collection.toJSON(), this actually returns an object and I am unable to get anything out of this object. This object actually has data that I need.
My question is how do I access rows property in my object. Here is my code for your reference
var testCollection = Backbone.Collection.extend({
model:myModel,
url: '/myApiEndPoint',
data: '',
initialize: function(models, options) {
this.data = models.data;
},
fetch: function(options) {
var ajaxConfig = {
url: this.url,
data: this.data,
type: 'POST',
dataType: 'text',
contentType: 'text/xml',
parse: true
};
options = _.extend({}, ajaxConfig, options);
return Backbone.Collection.prototype.fetch.call(this, options);
},
parse: function(xmlResponse) {
// I have some parsing logic to extract uid and rows from my xmlResponse
return {
uid: uid,
rows: rows
};
},
});
var collObj = new testCollection({data: xmlQuery1});
collObj.fetch({
success: function(collection){
// This code block will be triggered only after receiving the data.
console.log(collection.toJSON());
}
});
As the name toJSON suggests, it returns you the array of JSON objects where each object is a Model's JSON object. You can fetch the required properties in this way:
collObj.fetch({
success: function(collection){
// This code block will be triggered only after receiving the data.
console.log(collection.toJSON());
var uid = 'uid-of-an-object-to-access';
var rows = collection.get(uid).get('rows');
console.log(rows);
}
});

Cannot copy object property in javascript

I have an ajax call which gathers the parent and child dependencies for some entities. Inside the success function I assign what ajax returns (data) to a global level object.
$.ajax(
{
type: "POST",
url: 'ajax_handler.php',
data: {action:'get_dependencies', relation:relation, 'jobs[]':jobs, project:project},
dataType: 'json',
async: false, //do not change
success: function(data)
{
for(var key in data)
{
if( data.hasOwnProperty(key) )
{
//Copy data object to document level existingDependency object
existingDependency[key] = data[key];
}
}
},
error: function(xhr)
{
alert('error2:'+xhr.responseText);
}
});
I call this AJAX which is in a function twice. One for parents and one for children. I figured that this line existingDependency[key] = data[key]; is reassigning the object thus the previous assignment is lost. In other words the existingDependency object cannot hold both ['parent'] and ['child'] properties together.
To fix this I did the below changes so that existingDependency holds both properties:
success: function(data)
{
for(var key in data)
{
if( data[key].hasOwnProperty(relation) )
{
//Copy data object to document level existingDependency object
existingDependency[key][relation] = data[key][relation];
}
}
}
But this does not work at all. existingDependency object is empty. Below alerts empty.
var keys = '';
for(key in existingDependency)
{
keys += key+'\n';
}
alert(keys);
Any ideas why this assignment existingDependency[key][relation] = data[key][relation] does not work? data[key][relation] holds an array if it makes any difference.
Use extend:
$.ajax({
type: "POST",
url: 'ajax_handler.php',
data: {
action:'get_dependencies',
relation:relation,
'jobs[]':jobs,
project:project
},
dataType: 'json',
async: false, //do not change
success: function(data) {
$.extend(true, existingDependency, data);//this will copy/merge "data" into "existingDependency". properties from "data" that also exist in "existingDependency" will be overwritten with those from "data".
},
error: function(xhr) {
alert('error2:'+xhr.responseText);
}
});
As for why eD[key] = data[key] works while eD[key][relation] = data[key][relation] does not its hard to say without being able to run your code and debug it. But if eD[key] did not yet exist yet then it would not be able to add "relation" to it. A possible fix for that would have been:
if (!eD.hasOwnProperty(key)){
eD[key] = {};
}
eD[key][relation] = data[key][relation];

Categories