I am currently having an issue learning the basics of Ember and how it communicates with a backend service.
Here is what I'm doing in router.js:
Rugby.RugbyRosterRoute = Ember.Route.extend({
model: function(){
return [{
firstname:$.getJSON("/RugbyAPI")
// $.getJSON("/RugbyAPI") returns "John"
}];
//return this.store.find('roster');
},
renderTemplate: function(controller) {
this.render('rugby/roster', {controller: controller});
// tried this as well
//this.render('rugby/roster', controller);
}
});
But this is whats rendered.... [object Object]
I guess my question is how would I deal with this 'object'. I have been stuck for the past day but now luck...
EDIT:
I run this command in the web browser console...
$.getJSON("/RugbyAPI", function(data) { console.log(data) });
This is the result:
-> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
-> John
My guess is that I have to parse to the key that I need to display... But I can't seem to parse to it.... ['responseJSON'], ['firstname'], etc., nothings working...
{controller: controller}
Is an object.
Try:
this.render('rugby/roster', controller);
or:
this.render('rugby/roster', controller.propertyName);
Related
good afternoon developers, i have fetch data from my api and the data is responded as below
{id: 1, owner: "2", amount: "0", created_at: "2020-09-14 11:04:12", updated_at: "2020-09-14 11:04:12"}
and my code is below
return this.http.post(this.env.API_URL + "auth/wallet", {
id: this.user['id'],
}).subscribe(res => {
this.wallet = res[0];
console.log(this.wallet);
}, (err) => {
console.log(err);
});
when i type {{wallet["amount"}} it returns Cannot read property 'amount' of undefined
You probably need to use the optional chaining operator with dot notation like this:
{{wallet?.amount}}
This will not throw an error when the value is undefined, because it IS undefined until your API request is completed. By the way, this has nothing to do with Ionic, it's more of an Angular thing.
I need to iterate through data that get via JSON with this code:
setInterval(function() {
console.log("running");
$.ajax({
type : 'get',
url : 'data.txt',
dataType : 'json',
success : function(response) {
console.log(response.bookings) // returns undefined
$.each(response.bookings, function(index, booking) {
sc.status(booking.seat_id, 'unavailable');
console.log(booking.seat_id); // returns nothing
});
}
});
}, 3000); //every 3 seconds
The data is currently formatted like this:
[{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}]
But that doesn't seem to be working. What is the correct format that I need to use? I tried a ton of options but can't get it working.
UPDATE:
The error I now get in the console is:
jquery-1.11.0.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined
at Function.each (jquery-1.11.0.min.js:2)
at Object.success ((index):145)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
at x (jquery-1.11.0.min.js:4)
at XMLHttpRequest.b (jquery-1.11.0.min.js:4)
and line 145 is:
$.each(response.bookings, function(index, booking) {
You have options here. key value {"key":value} or {"name":john} is one way. You can do more info like "employee":{ "name":"John", "age":30, "city":"New York" }
as you said I think you are response.bookings array like this $arr = [1,2,3,4,5];.
if you iterate like below
$.each($arr,function(i,k){
console.log(i,k)
})
you will get output 0,1 1,2 2,3...
but I didn't get booking.seat_id means..? can you give us booking array format?
I finally found the solution. Thank you to everyone who helped. It's pretty simple and stupid. I only had to change the JSON response from:
[{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}]
to
{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}
Basically get rid of the []
I have a script with autocomplete, get some data from an external source according to searched term.
I can output the json in the console but I'm struggling to pass it to the response, how do I do that?
$('#test').autocomplete({
source: function(request,response){
$.post('/schoollookup', {
query: request.term
}, function(data){
}, 'json'
);
},
minLength: 2
});
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
This is the syntax for post request. where
url : A string containing the URL to which the request is sent.
data : A plain object or string that is sent to the server with the request.
success : callback function
#Sumesh
$.post('/schoollookup', {
should be working the same, the difficulty that I have is to get response
Thank you for your answer r007ed, the issue was that it was not returning an array.
So the final code for this is :
$('#test').autocomplete({
source: function(request,response){
$.post('/schoollookup',{query: request.term}, response, 'json');
},
minLength: 2
});
I'm making a simple shoutbox and when someone posts a message the message is added to the database just fine. I made a refresh button which populates all the messages in the text area.
I am trying to call the .click() on the refresh button after the person enters the message but I think it happens too fast and doesn't catch the new message in the database. I works if I add an alert to give it more time. Is there a better way?
$("#shoutBtn").click(function(event){
event.preventDefault();
$.post("includes/shoutBoxPost.php", {"message": $("#messageBox").val(),
"name": $("#userNameWelcome").html()});
$("#messageBox").val("");
$("#shoutRefresh").click();
});
I changed my code to the long hand ajax way and it works thanks for answers folks
$.ajax({
type: 'POST',
data: {"message": $("#messageBox").val(),
"name": $("#userNameWelcome").html()},
url : 'includes/shoutBoxPost.php',
success : function(data) {
$("#messageBox").val("");
$("#shoutRefresh").click();
}
});
See the documentation for jQuery .post. You can define a success callback that will only fire once the post request successfully returns.
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
$.post("includes/shoutBoxPost.php",
{"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()},
function( data, textStatus, jqXHR ) {
$("#shoutRefresh").click();
}
);
you can add call back function to your post
$.post( "includes/shoutBoxPost.php",{"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()})
.done(function( data ) {
$("#messageBox").val("");
$("#shoutRefresh").click();
});
You need to wait for your post to finish and send a success message back (via JSON), then do the refresh action.
I've been trying to get DataTables to work with my existing Ajax search function - which works by itself.
I have the following code:
$('#SearchResults').dataTable({
"bProcessing": true,
"bServerSide": true,
"bRetrieve": true,
"sAjaxSource": "process.php?action=searchArtifact",
"fnServerData": function (sSource, aoData, fnCallback){
aoData.push({
"name": "searchName",
"value": $('#ArtifactSearch').attr('value')
});
$.ajax({
"dataType": "json",
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The PHP is returning a valid JSON object (using JSON_FORCE_OBJECT):
{"0":{"ARTIFACT_ID":"4E2FE3BCE356C","ARTIFACT_NAME":"123","ARTIFACT_TYPE":"UI","ARTIFACT_LABEL":"Test_Int_EAS_123","ARTIFACT_LOCATION":"Int","ARTIFACT_DOMAIN":"ABC","ARTIFACT_AUTHOR":null,"REGISTERED_EMAIL":"test#test.com","REGISTERED_DATE":"27-07-2011","REGISTERED_TIME":"11:09:00"}
I can see this all fine in FireBug, but my empty table is not being populated with this data.
Any ideas?
#Kyle: Errr - thats it. I guess I don't have one? This is my first attempt (struggle) with DataTables and I'm just copying from the documentation: http://www.datatables.net/usage/callbacks#fnServerData
#MarcB: Added that - but still no data displayed. Thanks for the help
I was having a similar problem. Turns out I wasn't forming the JSON response properly. This worked for me:
<?php
$arr = array ('aaData' => array(
array('3','35','4', '$14,500', '$15,200','$16,900','5','1'),
array('1','16','4', '$14,200', '$15,100','$14,900','Running','1'),
array('5','25','4', '$14,500', '$15,600','$16,900','Not Running','1')
)
);
echo json_encode($arr);
?>
This plugin expects the returned JSON object to be an object, with a property which is an array of arrays. This property should be called 'aaData'. You are not returning an object; you are just returning the array.
Check out this json resource example from DataTables.net: http://datatables.net/examples/examples_support/json_source.txt. Notice that you are returning json with brackets as compared to the example's braces.
you can remove the $.ajax part, instead you can use the $.getJSON method.
You can also add the following to avoid adding an extra object like "aaData":
"sAjaxDataProp": ''
What are you setting sEcho to?
Your JSON should have this structure:
{
"sEcho": 'refer to "sEcho" in $_GET or $_POST; don't forget to sanitize',
"iTotalRecords": 'for pagination',
"iTotalDisplayRecords": 'number displayed',
"aaData" => { /* your data here */ }
}
This is a few years late but might help someone. :)
DataTable cannot render null values. See defaultContent to set content when data return is null.
See link: https://datatables.net/reference/option/columns.defaultContent
For legacy dataTables, see http://legacy.datatables.net/ref and search for sDefaultContent