How can I get the href value from a list? - list

I am trying to get the href value after I click on it, so I can use then the <?php include 'list'; ?> to load the content of the php page I'd clicked before. I was trying something like this:
$(document).ready(function() {
$('list').click(function)
var page=$(href);
<ul id="list">
<li>Mypage </li>
<li>Mypage2 </li>
So I can load a paragraph in my page using the content of the link I clicked before?

You can get the href value, then load the content of the linked page using the proper selectors and any appropriate jQuery ajax function, like ajax() or load().
$(document).ready(function() {
$('#list > li a').click(function(event) {
var page = this.attr("href");
// Here should go your ajax code or what-have-you to load the content.
// If you use an ajax function, the url will be equal to the var page.
event.preventDefault();
$.ajax({
type: "POST", // or "GET" may be better for your needs
url: page,
data: "",
success: function(content) {
console.log("ajax success");
$("#divID").html(content);
},
error: function() {
alert("ajax error");
},
complete: function() {
console.log("ajax complete");
}
});
});
});
<ul id="list">
<li>Mypage </li>
<li>Mypage2 </li>
</ul>
The code was missing the hash telling jQuery to find the id 'list'. The '#list > li a' tells jQuery to apply the code block to all 'li a' children of #list.

//thanks a lot for your response, i real apreciate it
//i finally used this and works fine
$(function() {
$("#team-tabs a").click(function() {
var page= this.hash.substr(1);
$.get(page+".php",function(gotHtml) {
$("#cv-content").html(gotHtml);
});
return false;
});
});
//for this:
<ul id="team-tabs">
<li>name 1</li>
<li>name 2</li>

Related

Accessing Objects Attributes Within Ajax

I am adding ajax to my website. I originally had this button:
{% for item in notifications %}
<a class='delete' href="{% url 'delete' item.slug %}">
But changed it to Ajax.
{% for item in notifications %}
<a class='delete'>
$(document).on('click', '.delete', function (e) {
$.ajax({
url: '/users/ajax/delete/',
data: {
// here I was to call the 'delete' function in the 'django.notifications' package
// something like 'notifications.delete(slug)'
},
dataType: 'json',
success: function (data) {
alert("Working");
}
});
});
This Ajax fires correctly, but I don't know how to get item.slug in Ajax. I guess I could do this <a class='delete' slug="{{ item.slug }}"> and access the slug, but it seems really sloppy.
Is there a way to pass an object's attributes to Ajax without setting it as a value within the html code itself?
Thank you.
You can store the value of the notification in a variable while rendering the HTML as shown below in the HTML section. Once you have notifications value in your script code. You can check the index of the clicked anchor and retrieve the item associated with that index.
$(document).on('click', '.delete', function(e) {
let elem = $(this);
$.ajax({
url: '/users/ajax/delete/',
data: {
// here I was to call the 'delete' function in the 'django.notifications' package
// something like 'notifications.delete(slug)'
},
dataType: 'json',
success: function(data) {
alert("Working");
//new code below
let index = $("a.delete").index(elem);
let item = notifications[index];
//You can access slug and other attributes of item now.
}
});
});
<script>
const notifications = {% notifications %}
</script>

Nuxt JS Apollo data only available after page refresh

I am fetching some data using Apollo inside of Nuxt. Somehow, when navigating to that page I get an error of
Cannot read property 'image' of undefined
When I refresh the page, everything works as expected.
I have a found a few threads of people having similar issues but no solution seems to work for me :/
This is my template file right now:
/products/_slug.vue
<template>
<section class="container">
<div class="top">
<img :src="product.image.url"/>
<h1>{{ product.name }}</h1>
</div>
</section>
</template>
<script>
import gql from 'graphql-tag'
export default {
apollo: {
product: {
query: gql`
query Product($slug: String!) {
product(filter: { slug: { eq: $slug } }) {
slug
name
image {
url
}
}
}
`,
prefetch({ route }) {
return {
slug: route.params.slug
}
},
variables() {
return {
slug: this.$route.params.slug
}
}
}
}
}
</script>
Basically the $apolloData stays empty unless I refresh the page. Any ideas would be much appreciated
EDIT
Got one step closer (I think). Before, everything (image.url and name) would be undefined when navigating to the page for the first time.
I added:
data() {
return {
product: []
};
}
at the top of my export and now at least the name is always defined so if I remove the image, everything works as expected. Just the image.url keeps being undefined.
One thing I noticed (not sure how relevant) is that this issue only occurs using the , if I use a normal a tag it works but of course takes away the vue magic.
EDIT-2
So somehow if I downgrade Nuxt to version 1.0.0 everything works fine
I stumbled on this issue as well, and found it hidden in the Vue Apollo documents.
Although quite similar to the OP's reply, it appears the official way is to use the "$loadingKey" property.
It's quite confusing in the documents because there are so many things going on.
https://vue-apollo.netlify.com/guide/apollo/queries.html#loading-state
<template>
<main
v-if="!loading"
class="my-8 mb-4"
>
<div class="w-3/4 mx-auto mb-16">
<h2 class="mx-auto text-4xl text-center heading-underline">
{{ page.title }}
</h2>
<div
class="content"
v-html="page.content.html"
></div>
</div>
</main>
</template>
<script>
import { page } from "~/graphql/page";
export default {
name: 'AboutPage',
data: () => ({
loading: 0
}),
apollo: {
$loadingKey: 'loading',
page: {
query: page,
variables: {
slug: "about"
}
},
}
}
</script>
If you need to use a reactive property within vue such as a slug, you can do so with the following.
<template>
<main
v-if="!loading"
class="my-8 mb-4"
>
<div class="w-3/4 mx-auto mb-16">
<h2 class="mx-auto text-4xl text-center heading-underline">
{{ page.title }}
</h2>
<div
class="content"
v-html="page.content.html"
></div>
</div>
</main>
</template>
<script>
import { page } from "~/graphql/page";
export default {
name: 'AboutPage',
data: () => ({
loading: 0
}),
apollo: {
$loadingKey: 'loading',
page: {
query: page,
variables() {
return {
slug: this.$route.params.slug
}
}
},
}
}
</script>
I think it's only a problem of timing on page load.
You should either iterate on products, if you have more than one, or have a v-if="product != null" on a product container, that will render only once the data is fetched from GraphQL.
In that way you'll use the object in your HTML only when it's really fetched and avoid reading properties from undefined.
To fix this, you add v-if="!$apollo.loading" to the HTML container in which you're taying to use a reactive prop.

Metamorph error when trying to save record

I'm getting a strange error when I'm trying to save some data.
Uncaught Error: Cannot perform operations on a Metamorph that is not in the DOM.
I've noticed something weird in the actual DOM
<h1>Posts page</h1>
<script id="metamorph-2-start" type="text/x-placeholder"></script>
<script id="metamorph-2-start" type="text/x-placeholder"></script>
<p>...</p>
...
<button data-ember-action="5" class="btn btn-warning">Cancel</button>
<script id="metamorph-2-end" type="text/x-placeholder"></script>
<table class="table table-striped table-hover>
There are two of the same metamorph tags and only one end tag. I've also tried not using the partial (ie having the code sit in the dom). While the duplicate metamorph start tag disappears, when trying to save, the metamorph tag its trying to reference doesn't exist.
Here is a JSBin of my code. the JSBin works, which is promising. The only difference between the jsbin and my code is that I'm using Ember App Kit. My guess is I'm doing something wrong with the ES6 setup. I've posted my controller code here
var IndexController = Ember.ArrayController.extend({
addingNew: false,
actions: {
createAccount: function() {
var account = this.store.createRecord('account', {
name: 'howdy',
});
account.save();
},
showNew: function() {
this.set('addingNew', true);
},
cancelNew: function() {
this.set('name', '');
this.set('addingNew', false);
}
}
});
export default IndexController;
What am I doing wrong to get this error?
I've run into this before when I have html comments enclosing ember tags. Something like:
<!-- {{#if something}}X{{else}}Y{{/if}} -->

What is the correct way to add new object to an Array of Ember Models (ember-model)

I am creating a new Ember.Model with a return response from an ajax call.
This is the ajax method i have in the controller
createImageResource: function() {
var self = this,
fd = new FormData(),
newResource = {},
resources = self.get('controllers.resources.model'),
fileName = this.get('resource_image').name,
fileSize = this.get('resource_image').size,
fileType = this.get('resource_image').type;
fd.append('resource[resource_type]', 'image');
fd.append('resource[resource_name]', this.get('resource_name'));
fd.append('resource[source_id]', this.get('source_id'));
fd.append('resource_image[resource_image]', this.get('resource_image'));
fd.append('resource[resource_file_name]', fileName);
fd.append('resource[resource_file_type]', fileType);
fd.append('resource[resource_file_size]', fileSize);
this.set('isProcessingResource', true);
$.ajax({
url: '/resources',
method: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: fd,
}).then(function(newResourceData) {
newResource = Msmapp.Resource.create(newResourceData.resource);
resources.pushObject(newResource);
self.set('isProcessingResource', false);
self.transitionToRoute('resource', newResource);
});
},
This adds the new resource into the array of objects used by the resources controller. It puts it into the DOM like it should. The issue im having is each object is a link to the individual resource. All of the objects that existed on page load work fine. The object added to the list has the correct url and everything, it just doesnt do anything when you try to navigate.
Im not sure if there is something else i need to do in the .then() ?
This is the template
<section class="column_list">
<ul>
{{#each resource in controller }}
<li class="item">
{{#if resource.isLoading }}
{{spinner}}
{{else}}
{{#linkTo 'resource' resource }}
<img {{bindAttr src='resource.listAvatar'}} />
<div class='title'>{{ resource.resource_name }}</div>
{{/linkTo}}
{{/if}}
</li>
{{/each}}
</ul>
</section>
Since you're adding to resources, that's what you should be looping over too - {{#each resource in resources }}.
Either that or push onto your ArrayController instance directly - this. resources.pushObject(newResource);.

how to change button tag's text on ajax's success

Actually i know how to do this. But something is different here. There are many posts in index page. and every post located in <li> tags. And i have voting system for each posts.
<ul>
<li class="class_li" data-id="this_posts_id">
Vote Up <button class="btn dropdown-toggle"
data-toggle="dropdown">
<span class="vote"> CURRENT VOTE </span>
<span class="caret"></span> </button>
</li>
<li class="class_li" data-id="this_posts_id">
<!-- another <li> for other posts with same tags and class names -->
</li>
<li class="class_li" data-id="this_posts_id">
<!-- another <li> for other posts with same tags and class names -->
</li>
</ul>
And my jquery code:
$('a.btn').click( function(){
var post_id = $(this).closest('li').data('id');
var vote = 1;
var ajaxOpt = {
type: 'post',
url: '/content/vote/',
data: {
'vote': vote,
'post_id': post_id,
},
success: function(data){
$(this).find('.vote').text(data.vote_new); // this does not work!
},
error: function(){
console.log('error :[');
}
};
$.ajax(ajaxOpt);
})
I tried closest() parent() and find(). All the same. Once i make it work. but that time all the post's vote values changed. Not ONLY in <li> tag's borders one.
I am stuck. Everything looks true. But something is wrong.
Thank you.
The problem is in the use of $(this) in the success callback. It is not the button, which is what your code is expecting. So you need to alter the code capture the reference outside of the success callback.
So below is the modified code:
create a local variable for the button ($this)
use sibling() and find() to get to the correct vote element
$('a.btn').click( function(){
//This will be the button - maybe call it $button if that's clearer
var $this = $(this);
var post_id = $(this).closest('li').data('id');
var vote = 1;
var ajaxOpt = {
type: 'post',
url: '/content/vote/',
data: {
'vote': vote,
'post_id': post_id,
},
success: function(data){
//This now works! :)
$this.siblings('button').find('.vote').text(data.vote_new);
},
error: function(){
console.log('error :[');
}
};
$.ajax(ajaxOpt);
});
Here's a JSFiddle showing the concept using your scenario.