Laravel 5 Eloquent objects and ajax - javascript

I am a beginner in Javascript and Jquery and I am trying to get data from the server, access them and display them without reloading the page with Ajax and Laravel 5.
So here is what I do:
My controller:
public function get_media_details(){
$media_id = $_POST['media_id'];
$media_details = Media::find($media_id);
print_r ($media_details);
}
My JS function:
function show_media_detail(media_id){
$.ajax({
url: "get_media_details",
type:"POST",
data: { media_id: media_id },
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success:function(data){
console.log(data);
},
error:function(){
console.log("No data returned");
}
});
}
And the result of console.log(data):
"App\Media Object
(
[table:protected] => media
[fillable:protected] => Array
(
[0] => name
[1] => feed_url
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[name] => TechCrunch
[description] => Breaking technology news and analysis.
[link] => http://techcrunch.com/
[feed_url] => http://techcrunch.com/feed/
[thumbnail] => Rll0vnSkWk3bvTTWdthYzagXGnLHt9EHpU3Qe8XK
)
etc...
But know I am trying to access specific value of this object, like for example, the name of my media.
I tried many things and searched a lot, but I keep failing miserably...
Any help would be greatly appreciated !
Thank you

change this
print_r ($media_details);
to
return $media_details;
in js file
... success:function(data){
for (var x in data){
console.log(data.description); // should output description
}
....

Related

Trying to pass object through another function, coming back as undefined

I want to pass the data from this one function, fetched from an API, into another. But the data does not want to carry over. Can you help? It keeps coming back as undefined. When I console log it in the other function, it just returns "object object" over and over.
Much appreciated.
app.getDisruptionData = () => {
$.ajax ({
url: "https://data.edmonton.ca/resource/5yvt-mcye.json",
method:"GET",
dataType: "json",
data: {
"$limit" : 500000,
"$$app_token" : "J33yX1FYA0vwnOA36tGBFLd6l"
},
complete: function(data) {
setTimeout(app.getDisruptionData, 300000);
$serviceDisruptions.empty();
const htmlToAppend =
`<li class="stationGrid">
<div>
ROUTE
</div>
<div>
DESCRIPTION
</div>
<div>
DISRUPTION START
</div>
<div>
EXPECTED END TIME
</div>
</li>`
$serviceDisruptions.append(htmlToAppend);
}
}).then((response) => {
console.log(response)
app.sortDisruptions(response)
// response.forEach ( (disruptionObject) => {
// const routeID = disruptionObject.route_ID;
// const routeName = disruptionObject.route_long_name;
// const disruptionStart = disruptionObject.start_dttm;
// })
});
}
app.sortDisruptions = (data) => {
console.log(`look at this data ` + data)
}
jQuery's promise-like handling can be a bit weird. Also, complete doesn't receive data, only the jqXhr object and a text status.
I would consolidate your complete and then callbacks into a single done()
$.getJSON("https://data.edmonton.ca/resource/5yvt-mcye.json", {
$limit: 500000,
$$app_token: "J33yX1FYA0vwnOA36tGBFLd6l",
}).done((data) => {
setTimeout(app.getDisruptionData, 300000);
// setting html is the same as empty + append
$serviceDisruptions.html(
`<li class="stationGrid">
<div>
ROUTE
</div>
<div>
DESCRIPTION
</div>
<div>
DISRUPTION START
</div>
<div>
EXPECTED END TIME
</div>
</li>`
);
app.sortDisruptions(data);
});
Also, try not to concatenate objects to strings in logging. A stringified object almost always displays as [object Object]
app.sortDisruptions = (data) => {
console.log("sortDisruptions", data);
// or just
console.log(data);
};

I get undefined when i try to add an Object from an api to my mongodb atlas db NODE JS

I get a list of pokemons from a third party API. I want to add specific ones to a favorites list when I click the add button. but whenever I try to render the list of favourite pokemon i just get objects saying undefined.
Any help would be appreciated.
//Here i try to add the fetched object to my rest api//
function createPokemonCard(data) {
const pokeContainer = document.getElementById("poke-container");
const pokemonEl = document.createElement('div');
pokemonEl.classList.add('pokemon');
const pokeInnerHtml = `
<div class="img-container">
<img src="${data.sprites.front_default}">
</div>
<div class="pokeCard">
<h1 id="id">${data.id}</h1>
<h3 id="name">${data.name}</h3>
<h4 id="type">${data.types.map(type => type.type.name).join(", ")}</h4>
<button onclick="addFavourite()">Add</button>
</div>
`;
pokemonEl.innerHTML = pokeInnerHtml;
pokeContainer.appendChild(pokemonEl);
}
// i am trying to get the value//
async function addFavourite() {
let name = document.getElementById('name').value ;
let type = document.getElementById('type').value ;
let data = {
"name": name,
"type": type
}
await fetch('https://web2-course-project-api-somrad.herokuapp.com/api/pokemons', {
method: "POST",
mode: 'cors',
headers: {
'Content-type': 'application/json; charset=utf-8'
},
body: JSON.stringify(data)
});
}
// my back end post request//
pokemonRouter.route('/pokemons')
//POST YOUR FAVOURITE POKEMON
.post((req, res)=>{
const collection = db.collection("pokedex");
collection.insertOne(req.body).then(
() => {
res.status(200).json({
message: 'Added!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
});
})
this is my collection, the first three entries is added manually
The list probably prints "undefined" since some of the objects provided by the database don't have a name.
[
{"_id":"610d3316bf52a4e260126877","name":"Pikachu","type":"Electric"},
{"_id":"610e689defe3ad8654648ec3","name":"Charmander","type":"Fire"},
{"_id":"610e68acefe3ad8654648ec4","name":"Bulbasaur","type":"Grass"},
{"_id":"6118df7554b38705559eaacd"},
{"_id":"6118f0e493b20fefb0fd1689"},
{"_id":"6118f1e7128dd43ee68f8140"},
{"_id":"6118f2e8128dd43ee68f8141","name":"test","type":"grass"},
{"_id":"6118f57a128dd43ee68f8142"},
{"_id":"6118f5ca128dd43ee68f8143"},
{"_id":"6118f6a6128dd43ee68f8144"},
{"_id":"6118f6da128dd43ee68f8145"},
{"_id":"6118f6fd128dd43ee68f8146"},
{"_id":"6118f86f128dd43ee68f8147"},
{"_id":"6118f8e4128dd43ee68f8148"},
{"_id":"6118f924128dd43ee68f8149"},
{"_id":"6118fb34128dd43ee68f814a"}
]
This already includes my other suggestions.
I recommend that you filter out the invalid ones before rendering the rest.
// your list with the pokemon before you create the html elements
// this simply removes all pokemon from the list that don't have a name or type
const yourList = [];
const yourFilteredList = yourList.filter(item => {
if(item.name === undefined) return false;
if(item.type === undefined) return false;
return true;
})
Please also note that in mongoDB the Primary Key of the database is _id not id
<h1 id="id">${data._id}</h1>
This could also be an issue, since the type field of the API you provided is a string not a list as indicated. This may result in an Uncaught TypeError: something.join is not a function
<h4 id="type">${data.types.map(type => type.type.name).join(", ")}</h4>

Unable to show questions of the second page

I'm working on a flask app, where there're questions paginated in 2 pages,
the problem is that clicking on the number 2 to change the page doesn't change the questions, I don't know which part of the code should be responsible for that, if there any code snippets required to help solving this problem just tell me to edit the question.
backend
def paginate_questions(request, selection):
page = request.args.get('page', 1, type=int)
start = (page - 1) * QUESTIONS_PER_PAGE
end = start + QUESTIONS_PER_PAGE
questions = [question.format() for question in selection]
current_questions = questions[start:end]
return current_questions
#app.route('/questions')
def get_paginated_questions():
categories = Category.query.order_by(Category.id).all()
selection = Question.query.order_by(Question.id).all()
current_questions = paginate_questions(request, selection)
if len(current_questions) == 0:
abort(404)
return jsonify({
'success': True,
'questions': current_questions,
'total_questions': len(selection),
'current_category': None,
'categories': {category.format()['id']: category.format()['type']
for category in categories}
})
frontend
getQuestions = () => {
$.ajax({
url: `/questions`, //TODO: update request URL
type: "GET",
success: (result) => {
this.setState({
questions: result.questions,
totalQuestions: result.total_questions,
categories: result.categories,
currentCategory: result.current_category })
return;
},
error: (error) => {
alert('Unable to load questions. Please try your request again')
return;
}
})
}
selectPage(num) {
this.setState({page: num}, () => this.getQuestions());
}

Get additionalData from Onesignal (Phonegap)

I read the doc here : https://documentation.onesignal.com/docs/cordova-sdk but it's totally not clear !
I try severals test nothing, I event test to get the title but still nothing
document.addEventListener('deviceready', function () {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
alert('notificationCallback: ' + JSON.stringify(jsonData)); => json data
alert('Title : '+ JSON.stringify(jsonData.payload.title)); => nothing
alert('Title2 : '+ jsonData.payload.title); => nothing
alert('Additional data: '+ jsonData.payload.additionalData); => nothing
};
window.plugins.OneSignal
.startInit("MY_ID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
}, false);
How to retrieve this data..
Thanks
After multiple debugs on my app, I finally found the application. The JSON structure of jsonData is :
jsonData
notification: {
payload: {
title: "YOUR_TITLE",
body: "BODY",
additionalData: {
"YOUR_KEY" : "YOUR_VALUE"
},
So to retrieve your data :
JSON.stringify(jsonData.notification.payload.additionalData.<YOUR_KEY>)
Instead of jsonData.payload try with jsonData.OSNotificationPayload
Ex: to access title
jsonData.OSNotificationPayload.title

A Mystery in my Code

I have fixed the issue with ajax on typo3. Now comes another issue in hand. This time is related to returning the object found in the action to Javascript. So I tell you what I do exactly.
here is first my ajax call function:
function getContent(id)
{
console.log("Starting process ...");
$.ajax({
async: 'true',
url: 'index.php',
type: 'POST',
data: {
eID: "ajaxDispatcher",
request: {
pluginName: 'listapp',
controller: 'Pays',
action: 'getMyCompanys',
arguments: {
'id': id
}
}
},
dataType: "json",
success: function(result) {
var data = JSON.parse(result)
console.log(data.nom);
},
error: function(error) {
console.log(error);
}
});
}
and here is the "getMyCompanys" action:
public function getMyCompanysAction()
{
$argument = $this->request->getArguments('id');
$company = $this->entrepriseRepository->findBypays(2); // just to test with the id 2
$result = (array) $company;
return json_encode($result);
}
Now on the console I get this Output:
{"\u0000*\u0000dataMapper":{},"\u0000*\u0000persistenceManager":{},"\u0000*\u0000query":{},"\u0000*\u0000queryResult":null}
So at the first glance , i thought the object was not passed to the javascript , but when I tried to add an attribute to the object $company ($company->att = 'val';)
I get this output :
{"\u0000*\u0000dataMapper":{},"\u0000*\u0000persistenceManager":{},"\u0000*\u0000query":{},"\u0000*\u0000queryResult":null**,"att":"val"}**
notice that the added attribute and its value get showed
so I now I'm convinced that there is something wrong with the object. I am also 100 % sure that the method findBypays(2); is working, I tried it in a listAction.
I don't really know what could be the problem :/
Just for your Information: this is part of an extension in typo3 that I developed myself using JBuilder
well after struggling for a long time , I tried a trick and it worked and it proved me that the json_encode does not return an object in typo3 eventhough I applied the :
$object->toArray() or (array) $object
to the object , so my solution was :
$companies = array();
foreach ($this->adresseRepository->findByland($id) as $company)
{
$companies[] = array(
'uid' => $company->getUid(),
'firma' => $company->getFirma(),
'strasse' => $company->getStrasse(),
'plz' => $company->getPlz(),
'ort' => $company->getOrt(),
'land' => $company->getLand(),
'telefon' => $company->getTelefon(),
'email' => $company->getEmail(),
'webseite' => $company->getWebseite()
);
}
return json_encode($companies);
and It Worked ;)

Categories