I'm using Nuxt.js 3 and I want to display the content of a client side POST request on my index page. When the page is hotloaded from a change I'm getting the result that I want, but when it loads fresh it'll always return an error and the text won't load in.
I've never really worked in javascript of any sort before so I'm sure I'm missing something obvious, but I'm not sure what.
I've tried doing it like this:
my-component.vue
<template>
<div>
<h2>{{ myResponseTitle }}</h2>
<p>{{ myResponseText }}</h2>
</div>
</template>
<script setup>
const { data: response } = await useFetch('http://localhost:5000/api/endpoint', {
method: 'POST',
body: JSON.stringify({ tz: Intl.DateTimeFormat().resolvedOptions().timeZone })
})
const myResponseTitle = response.value.title
const myResponseText = response.value.text
</script>
index.vue
<template>
<div>
<client-only>
<div>
<my-component/>
</div>
</client-only>
</div>
</template>
This produces an error like:
Uncaught (in promise) TypeError: response.value is null
setup my-component.vue:12
Ideally I'd like the page to load and then for that component to load when the request returns, but even having it block while waiting for the request would be fine.
Related
I'm currently making an app for Shopify and I'm stuck with one problem that I can't seem to solve or find any helpful answer from Google.
I need a FrontEnd button to run a script written in JavaScript. This script is located on the server locally in a different folder.
The page is written entirely in JavaScript React and there is no HTML in there.
I tried to import this js file, but it does not allow importing due to some error. Trying to fix this error, an error occurs with the code itself and it stops working adequately. This is why I gave up trying to import the file.
Then I tried to use fetch, but I just can't achieve the result that the page would at least see my file on the server.
FrontEnd button
onClick = {() => {
fetchText ()
}}
At the bottom of the pages / index.js file is this function, which the button calls. The readme.txt file is located in this path: pages / readme.txt
async function fetchText () {
var a = fetch ("/ readme.txt")
.then (promiseResult => {
console.log (promiseResult)
return promiseResult.text ()
})
.then (responseResult => {console.log (responseResult)})
}
Everything that displays in the browser console:
Response {type: "basic", url: "https://ooo.example.com/readme.txt", redirected: false, status: 404, ok: false,…}
All the data about the page is also written at the bottom, but the bottom line is that no matter how I try to write the code itself, it always gives the same 404 error, that is, Not Found
I'm trying to parse data from a node.js/ express server which I wish to use on the client-side as a variable (although I understand this could most likely all be done server-side, I'm trying to learn about how handlebars handles data). At this stage I wish to have it as an object I can print so I can use it at a later stage. My current code is as follows:
Handler for request
exports.getList = (req,res) => {
console.log("Request for list sent");
var MyDataObject = {
days: 75,
people: 12
};
return res.status(200).render("home", {MyDataObject});
};
Client-Side
<script>
handleServerData = (ServerDataObject) => {
console.log(ServerDataObject);
};
</script>
{{#if MyDataObject}}
<script>handleServerData({{MyDataObject}})</script>
{{/if}}
When the page is requested through the shown handler this simply gives the error Uncaught SyntaxError: Unexpected identifier Which I assume is from it setting {{MyDataObject}} to [object Object] inside the sources view however I don't know how to fix this although I assume it does it because of it running the script before the handlebars parse the data.
Any help fixing this is greatly appreciated.
When I try to show an image with dynamic URL, that is coming from an API call initially I get an error in the console. After a few moments the image is loaded. Is there a way to prevent that error? I use beforeCreate hook for the API call. Any help will be appreciated.
HTML
<img :src="userAvatarURL" class="img-fluid avatar">
Javascript
export default {
beforeCreate() {
this.$store.dispatch('getUser');
},
computed: {
...mapState({
user: 'user',
}),
userAvatarURL: {
get: function () {
return window.axios.defaults.baseURL+'/storage/user_avatars/'+this.user.avatar;
}
}
}
Error in network tab of the console
GET http://api.aaa/storage/user_avatars/undefined 404 (Not Found)
You should simply display this image when user.avatar is defined, e.g. :
<img v-if="user.avatar" :src="userAvatarURL" class="img-fluid avatar">
I'm loading an image from a S3 bucket in my Ionic view like this:
<ion-avatar>
<img class="circle" src="https://s3-sa-east-1.amazonaws.com/mybucket/cp{{client?.id}}.jpg">
</ion-avatar>
The image name I want to load is "cp1.jpg", and the client?.id value 1 is taken from the component script:
ionViewDidLoad() {
let email = this.storage.getLocalUser().email;
this.clientService.findByEmail(email)
.subscribe(resp => {
this.client = resp;
},
error => {
console.log(error);
});
}
I'm also using the "?" operator in client?.id because if I don't, I get an "id undefined" error and the page doesn't even load.
However, I'm getting a canceled request on my Network inspector, which is trying to retrieve the image before the "1" value is concatenated in the image name:
Right after that error, the "1" value is provided to the view and the image is loaded. But I'd like to not get that undesired retrieving try.
How can I properly load and bind the client id to get the image name right, and also to avoid getting that canceled request error?
In your html:
<ion-avatar>
<img class="circle" [src]="avatar_for_client()">
</ion-avatar>
In your .ts:
avatar_for_client(){
if (this.client){
return `https://s3-sa-east-1.amazonaws.com/mybucket/cp${this.client.id}.jpg`
}else{
return <some placeholder image url>
}
}
I am writing a django app where the user wants to click a button and have a partial page change. Data needs passed from the server to the web page without a needing a complete page refresh. That task sounded like a job for ajax. However, I can't make Ajax work in my app.
I cannot get the call into my server-side function. Below is the code the subject matter is regarding missed calls. My intent is to get the server side to return a list of missed calls and display it to the user without having to refresh the page.
When I click the button, I get a popup that says "Something goes wrong" using firebug, I traced this to a DAJAXICE_EXCEPTION but I don't know anything else about it.
What's going on here? How do I make this work? Also if there's an easier way to do this that doesn't require the Dajax library please advise. And any step-by-step examples would be very helpful.
Server side function
-------- /jim/ajax.py---------
#dajaxice_register
def missedCalls(request, user):
print "Ajax:missedCalls" #never prints...
missedCalls = ScheduledCall.objects.filter(status__exact='Missed')
render = render_to_string('examples/pagination_page.html', { 'missedCalls': missedCalls })
dajax = Dajax()
dajax.assign('#calls','innerHTML', render)
return dajax.json()
-------page.html---------
<script type='text/javascript'>
function missed_calls_callback(data){
# The dajax library wants a function as a return call.
# Have no idea what I'm supposed to do with this part of the function.
# what is supposed to go here?
alert(data.message);
}
</script>
<!-- Button -->
<input type="button" name="calltest" value="JQuery Test"
id="calltest" onclick="Dajaxice.jim.missedCalls(missed_calls_callback, {'user':{{ user }}})">
<div id="calls">
{% include "calls.html" %}
</div>
--------calls.html--------
<h2> Missed Calls</h2>
<ul>
{% for i in missedCalls.object_list %}
<li>{{ i }}</li>
{% endfor %}
</ul>
Before you start using a library, if might be helpful to do manually (to see what's going on).
An ajax request is a HTTP request like any other except that it happens asynchronously (i.e. outside the normal request/response cycle) and it usually returns json or xml (although you can return html if you like).
This means that to accept an AJAX request you just create an url and view as you would normally.
urls.py
...
url(r"^/my/ajax/path/$", myapp.views.ajax_view, name="do-something-ajaxy"),
...
views.py
def ajax_view(self, request):
# Django's Request objects have a method is_ajax()*
# which checks the header to see if it's an 'ajax' request
if request.is_ajax():
raise Http404
missedCalls = ScheduledCall.objects.filter(status__exact='Missed')
# You can return a dictionary-like json object which can be manipulated by the javascript when it receives it
return HttpResponse(simplejson.dumps(missedCalls), mimetype='application/javascript')
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.is_ajax
And using jquery to carry out the ajax request:
(function($){
$.ajax({
type: 'GET',
url: '/my/ajax/path/',
success: function(data){
for call in data:
/* Do something with each missed call */
},
});
});