With jQuery v3.2, I want to extract and remove "H1" from AJAX data :
$('.version-modal-show').click(function() {
var url = $(this).attr('href');
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success:function(d) {
console.log(d);
modal.setBody(d);
modal.open();
}
});
return false;
});
console.log(d) return html brut :
<h1>
<i class="fa fa-list" aria-hidden="true"></i>
Centre d'intérêt « TESTb »
</h1>
<p class="text-center">
<a href="/app_dev.php/administration/hobbies" class="btn btn-secondary">
<i class="fa fa-backward" aria-hidden="true"></i>
Retour aux centres d'intérêts
</a>
</p>
I want to remove the h1 from the modal.setBody() but put it in the modal.setTitle()
You can set the .filter()ed content
modal.setTitle($(d).filter('h1').prop('outerHTML'));
modal.setBody($(d).filter('p.text-center').prop('outerHTML'));
Related
I am trying to send ajax request and remove the parent of popover after success
the request is success
but I can't access the parent of popover to remove it that is the bottom of problem
// delete work form portfolio
$(document).on("click", "#delete-work", function(){
var id_val= $(this).attr("data-id");
$.ajax({
url: "ajax/portfoliojx.php",
type: "POST",
data: {
name : "delete_work",
id : id_val,
},
dataType: "JSON"
}).done(function(data){
// check if responed email error
$(this).parents(".work").remove();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="work">
<div class="col-md-3">
<div class="thumbnail">
<a href="">
<img src="uploads/portfolio/251442-7.jpg" title="hello" alt="hello">
</a>
<div class="caption">
<h4 class="tite">hello</h4>
</div>
<hr>
edit <i class="fa fa-edit"></i>
<a tabindex="0" class="btn btn-danger pull-left" role="button" data-toggle="popover" data-trigger="focus" data-placement="top" title="" data-content="<button class='btn btn-defualt'>no</button><span class='pull-left'><button id= 'delete-work' data-id= '23' class='btn btn-danger'>yah</button></span>" data-original-title="are you sure from this ?"> delete <i class="fa fa-trash"></i></a>
</div>
</div>
</div>
Inside Ajax callback the scope should be Ajax so this won't be works. the below codes works for your case
$(document).on("click", "#delete-work", function(){
var _self = this;
var id_val= $(this).attr("data-id");
$.ajax({
url: "ajax/portfoliojx.php",
type: "POST",
data: {
name : "delete_work",
id : id_val,
},
dataType: "JSON"
}).done(function(data){
// check if responed email error
$(_self).parents(".work").remove();
});
})
I have three functions:
function atualizarPublicacoes(){
$.ajax({
url: "{{ path('publicacoes') }}",
type: 'post',
dataType: 'json',
success: function(publicacao){
$.each(publicacao, function(key, value){
$('#mural').append('<div class="border border-light post card my-3"><div id="cabecalho'+value['id']+'" class="px-4 card-header d-flex align-items-center justify-content-between"><div class="d-flex align-items-center"><img class="rounded-circle avatar" style="height:55px ; width:55px" alt="image" src="'+value['userAvatar']+'"></img><div class="mx-3"><div class="text-sm">'+value['userNomeSobrenome']+'<small class="text-muted d-block">'+moment(value['data']).fromNow()+'</small></div></div></div></div><div class="card-body">'+value['post']+'</div><div class="card-footer px-4" style="background-color: #B7BBE0"><div id="acoes'+value['id']+'"></div><div></div></div><div class="card-footer" style="background-color: #CACDE7"><ul class="list-unstyled" id="comentarios'+value['id']+'"></ul></div>');
if(value['titulo']){
$('#cabecalho'+value['id']).append('<h3 class="mb-0" style="font-family: Nunito Sans, sans-serif">'+value['titulo']+'</h3>');
}
if(value['userId'] == "{{app.user.id}}"){
$('#cabecalho'+value['id']).append('<div><button id="editar'+value['id']+'" class="btn btn-gradient-info btn-sm" data-toggle="tooltip" data-placement="top" title="Editar"><i class="mdi mdi-lead-pencil"></i></button><button id="deletar'+value['id']+'" class="ml-2 btn btn-gradient-danger btn-sm" data-toggle="tooltip" data-placement="top" title="Excluir"><i class="mdi mdi-delete-forever"></i></button></div>');
}
});
}
});
};
function atualizarCurtidas(id){
$.ajax({
url: "{{ path('publicacoes_footer')}}",
type: 'post',
datatype: 'json',
success: function(footer){
if(!id){
var footers = footer; //atualiza todos os footers - utilizado quando abre a pagina ou publica um novo post
}else{
var footers = [footer.find(e => e.id == id)]; //atualiza só o footer clicado
}
$.each(footers, function(key, value){
var acoes = $('#acoes'+value['id']);
if( value['curtidas'] != null && "{{ app.user.id }}" in value['curtidas']){
acoes.find('a[title="Comentarios').before('<a title="Curtido" class="ml-2 mr-1" style="cursor:pointer"><i class="icon-md mdi mdi mdi-heart" style="color: #FF4747"></i><small class="mx-1" style="color: #FF4747">'+value['countCurtidas']+'</small></a>');
}else{
acoes.find('a[title="Comentarios').before('{{ form_start(curtir) }}{{ form_widget(curtir._token) }}{{ form_end(curtir, {"render_rest": false}) }}<a title="Curtir" id="'+value['id']+'" class="ml-2 mr-1" style="cursor:pointer"><i class="icon-md mdi mdi mdi-heart-outline" style="color: #FF4747"></i><small class="mx-1" style="color: #FF4747">'+value['countCurtidas']+'</small></a>');
}
});
}
});
};
function atualizarComentarios(id){
$.ajax({
url: "{{ path('publicacoes_footer')}}",
type: 'post',
datatype: 'json',
success: function(footer){
if(!id){
var footers = footer; //atualiza todos os footers - utilizado quando abre a pagina ou publica um novo post
}else{
var footers = [footer.find(e => e.id == id)]; //atualiza só o footer clicado
$('#acoes'+footers[0]['id']).parent().next().find('ul').empty();
}
$.each(footers, function(key, value){
if(value['countComentarios'] > 0){
$('#acoes'+value['id']).append('<a title="Comentarios" class="ml-2 mr-1"><i class="icon-md mdi mdi-comment-processing text-primary"></i><small class="mx-1 text-primary">'+value['countComentarios']+'</small></a>');
$(value['comentarios']).each(function(key, comm){
$('#comentarios'+value['id']).append('<li class="p-2 media rounded mb-2" style="background-color: #E5E6EA ; box-shadow: 0 0 6px gray"><img class="align-self-center mx-2 rounded-circle avatar" style="height:45px ; width:45px" alt="image" src="'+comm['userAvatar']+'"></img><div class="media-body"><h6 class="m-0 text-info">'+comm['userNome']+'<small class="text-muted float-right">'+moment(comm['data']).fromNow()+'</small></h6><small class="mx-2">'+comm['texto']+'</small></div></li>');
$('#comentarios'+value['id']).addClass(value['countComentarios'] > 2 ? '3mais' : '');
})
}else{
$('#acoes'+value['id']).append('<a title="Comentarios" class="ml-2 mr-1"><i class="icon-md mdi mdi-comment-processing-outline text-primary"></i><small class="mx-1 text-primary">0</small></a>');
}
if(!id){
$('#comentarios'+value['id']).after('<div tabindex="-1" class="d-flex justify-content-between align-items-center mx-2 mb-2"><img class="rounded-circle avatar" style="height:45px ; width:45px" alt="avatar" src="{{asset(app.user.avatar)}}"></img><textarea placeholder="'+ (value["countComentarios"] > 0 ?'Escreva seu comentário...' : 'Seja o primeiro a comentar...') +'" class="p-2 mx-1 col-11" maxlength="250"></textarea><a title="Comentar" data-pub="'+value['id']+'" style="cursor:pointer">{{ form_start(comentar) }}{{ form_widget(comentar._token) }}{{ form_end(comentar, {"render_rest": false}) }}<i class="icon-lg mdi mdi-comment-check text-primary"></i></a></div>');
}
});
if(!id){
$('ul.list-unstyled li:nth-child(n+3)').hide();
$('ul.3mais li:nth-last-child(1)').after('<a name="carregar" class="ml-3 text-info" style="cursor:pointer">Carregar mais comentários<i class="mdi mdi-menu-down"></i></a>');
}
}
});
};
and then i call them:
$(document).ready(function(){
moment.locale('pt-BR');
atualizarPublicacoes();
atualizarComentarios();
atualizarCurtidas();
Notiflix.Notify.Init({
position: 'center-top'
});
Notiflix.Confirm.Init({
titleColor: '#ff5549',
okButtonBackground: '#ff5549'
});
});
When I load the page the first one executes but I think that it's finishing after the other 2 finishes because it loads more content (takes more time) so it's like the last two ones didn't executed as they use elements of the previous function to work.
How can I make the second one (AtualizarComentarios) initiate after the first (AtualizarPublicacoes) is completed and the third one after the second?
I call them on other events as well so I can't put them all togheter in one function.
Thanks!
jQuery ajax methods return promise compatible objects, so you could use that. For instance, change the first function to the following -- the key is to use then instead of success and to return the result of the then call:
function atualizarPublicacoes(){
return $.ajax({
//^^^^^^
url: "{{ path('publicacoes') }}",
type: 'post',
dataType: 'json'
}).then(function(publicacao){
// ^^^^^^
$.each(publicacao, function(key, value){
// ... etc ...
});
});
};
Do the same with the other two functions.
In the calling code, either chain then calls, or (simpler) use the async/await syntax:
$(document).ready(async function(){
// ^^^^^
moment.locale('pt-BR');
await atualizarPublicacoes();
//^^^^^
await atualizarComentarios();
await atualizarCurtidas();
Notiflix.Notify.Init({
position: 'center-top'
});
Notiflix.Confirm.Init({
titleColor: '#ff5549',
okButtonBackground: '#ff5549'
});
});
I am currently working on ajax, jquery and javascript. I have slight problems with it.
I can use this code to send the data and they are stored in the database.
But the data will not be displayed directly after sending in the view, until I have reloaded the page.
How can I output the data directly in the view without reloading the page?
How can I output errors and success messages as flashmessage (toastr) message?
how can I rewrite this code that works? I get the error message that it is a duplicate of the selectors.
$('#todolist-create-modal').modal('hide');
$('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
Code
<script type="application/javascript">
$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#add-todo-list').click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val(); // get csrf field.
var title = $("input[name='title']").val();
var description = $("textarea[name='description']").val();
var privacy = $("select[name='privacy']").val();
var listid = $("select[name='privcy']").val();
$.ajax({
url:'{{ route('todolists.store') }}',
type: 'POST',
data: {_token:_token, title:title, description:description, privacy:privacy},
success: function (data) {
console.log(data);
if (privacy = 0) {
//go to the left side
} else {
//go to the right side
}
},
error: function(data){
console.log(data);
}
});
$('#todolist-create-modal').modal('hide');
$('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
});
});
</script>
view
<div id="content" class="dashboard padding-10">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<a data-toggle="modal" data-target=".todolist-create-modal" class="btn btn-success btn-block btn-sm margin-bottom-10">Neue Liste erstellen</a>
</div>
<div class="col-md-6">
<div id="panel-misc-portlet-l3" class="panel panel-default text-center">
<div class="panel-heading nohover">
<span class="elipsis">
<strong>Öffentliche Tasks</strong>
</span>
</div>
</div>
<div class="alert alert-danger margin-bottom-30 {{ $todolistpublic->count() ? 'hidden' : '' }}">
Es wurden keine <strong>Einträge</strong> gefunden.
</div>
#foreach ($todolistpublic as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden">
<i class="fa fa-plus"></i> Erstellen
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-info btn-xs white hover-hidden">
<i class="fa fa-edit"></i> Bearbeiten
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-delete-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-danger btn-xs white hover-hidden">
<i class="fa fa-times"></i> Löschen
</a>
</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
<div class="panel-footer mtm-10">
<span id="todo-list-counter-public">{{ $todolistpublic->count() }}</span> <span>{{ $todolistpublic->count() > 1? 'Listen' : 'Liste' }}</span>
</div>
</div>
<div class="col-md-6">
<div id="panel-misc-portlet-l3" class="panel panel-default text-center">
<div class="panel-heading nohover">
<span class="elipsis">
<strong>Private Tasks</strong>
</span>
</div>
</div>
<div class="alert alert-danger margin-bottom-30 {{ $todolistprivate->count() ? 'hidden' : '' }}">
Es wurden keine <strong>Einträge</strong> gefunden.
</div>
#foreach ($todolistprivate as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden"><i class="fa fa-plus"></i> Erstellen</a></li>
<li><a data-toggle="modal" data-target=".todolist-modal" class="btn btn-info btn-xs white hover-hidden"><i class="fa fa-edit"></i> Bearbeiten</a></li>
<li><i class="fa fa-times"></i> Löschen</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
<div class="panel-footer mtm-10">
<span id="todo-list-counter-private">{{ $todolistprivate->count() }}</span> <span>{{ $todolistprivate->count() > 1? 'Listen' : 'Liste' }}</span>
</div>
</div>
#include('elements.addTodoList')
#include('elements.createTodoList')
#include('elements.addTask')
</div>
</div>
Controller
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|min:5',
'description' => 'required|min:10',
'privacy' => 'required|integer'
]);
$attributeNames = array(
'title' => 'Title',
'description' => 'Description',
);
$validator->setAttributeNames($attributeNames);
//Redirect back if validation fails
if($validator->fails()) {
return response()->json(['error'=>$validator->errors()->all()]);
}
else{
$todolists = new Todolists();
$todolists->admin_id = Auth::id();
$todolists->title = $request->title;
$todolists->description = $request->description;
$todolists->privacy = $request->privacy;
$todolists->save();
return response()->json(['Your enquiry has been successfully submitted!']);
}
}
EDIT
I have revised and adapted the code. Currently I have two more problems:
The flashmessage is only output as 'empty'. Without text content. Where is the problem?
The div is also reloaded. But after it was loaded I can not send the same request again. Do I have to reset something or what is the error?
When I issue the errors in the console with console.log(data); I get the following error messages:
{error: Array(2)}
error
:
(2) ["The Title ist erforderlich.", "The Description ist erforderlich."]
<script type="application/javascript">
$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#add-todo-list').click(function(e) {
e.preventDefault();
$('.todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
var _token = $("input[name='_token']").val(); // get csrf field.
var title = $("input[name='title']").val();
var description = $("textarea[name='description']").val();
var privacy = $("select[name='privacy']").val();
$.ajax({
url:'{{ route('todolists.store') }}',
type: 'POST',
data: {_token:_token, title:title, description:description, privacy:privacy},
success: function (response) {
if (response.error) {
_toastr((response),"top-full-width","error",false);
}
else{
$('.todolist-create-modal').modal('hide');
$("#content").load(location.href+" #content>*","");
_toastr((response),"top-full-width","success",false);
}
}
});
});
});
</script>
Q: How can I output the data directly in the view without reloading the page?
One way with jQuery was loading partial content, this will request again the page, get the contents of #content div and replace the HTML, fast and without reload the page:
$("#content").load("/url-of-page > #content > *");
Q: How can I output errors and success messages as flashmessage (toastr) message?
Just write the message on a HTML element:
success: function(data){
$(".alert-danger").addClass("hidden");
$(".alert-success").html(data.msg).removeClass("hidden");
},
error: function(data){
$(".alert-success").addClass("hidden");
$(".alert-danger").html(data.error).removeClass("hidden");
}
I have this function that returns when an an ajax has been called, however the function returns only the id of the first div in the post and repeats the same id number for the next elements or div tags. However, when the function is used on click with specified $(this) it returns the unique div of the other elements. Please help. Here's the code.
$(document).on("click", ".likeTypeAction", function () {
var reaction_id = $('.likeTypeAction');
var reactionType = $(this).attr("data-reaction");
var reactionName = $(this).attr("original-title");
var rel = $(this).parent().parent().attr("rel");
var x = $(this).parent().parent().attr("id");
var sid = x.split("reaction");
var id_post = sid[1];
var htmlData = '<i class="' + reactionName.toLowerCase() + 'IconSmall likeTypeSmall" ></i>' + reactionName;
var dataString = 'id_post=' + id_post + '&rid=' + reactionType;
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {"done": 1, "id_post": id_post, "rid": reactionType},
beforeSend: function () {
alert(id_post);
},
success: function (data) {
displayReaction();
},
});
});
function displayReaction() {
a = $("#reactionEmoji");
var cls = $(this.a).parent().attr('class');
var n = cls.split("reaction");
var reactionNew = n[1];
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {
"getReaction": 1, "reactionNew": reactionNew
},
beforeSend: function () {
alert(reactionNew);
},
success: function (data) {
}
})
}
myInstance = new displayReaction();
echo '<div id="reaction" class="reaction' . $id_post . '">
<div id="reactionEmoji">nothing</div>
</div>';
echo'<div class="reaction-action">';
echo '<div rel="unlike" c="undefined" id="reaction' . $id_post . '" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType"></i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType"></i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);"></span>
<span style="border-color:rgb(255, 255, 255);"></span>
</div>
</div>';
There are a couple issues with your code.
I suppose the PHP code you provided is in some kind of loop : $id_post suggests your looping through some data and printing this HTML for each post.
If it is inside a loop, you are going to have, in your document, for each loop :
<div id="reaction" class="reaction' . $id_post . '">
<div id="reactionEmoji">nothing</div>
</div>
You can't have several HTML elements with the same id.
And since you are using the reactionEmoji id in your displayReaction function, you may want to fix that :
function displayReaction() {
a = $("#reactionEmoji");
var cls = $(this.a).parent().attr('class');
var n = cls.split("reaction");
var reactionNew = n[1];
/* .... */
alert(reactionNew);
}
In the snippet below :
I replaced your PHP code with 3 HTML generated codes
I added some labels to replace your icon (we didn't have your CSS)
I made both divs ids unique
I corrected your displayReaction function so that it takes the id of the reaction you want to display as a parameter.
I'm not sure it does what you want it to do, but it should help you solve your issues.
$(document).on("click",".likeTypeAction",function()
{
var reaction_id = $('.likeTypeAction');
var reactionType=$(this).attr("data-reaction");
var reactionName=$(this).attr("original-title");
var rel=$(this).parent().parent().attr("rel");
var x=$(this).parent().parent().attr("id");
var sid=x.split("reaction");
var id_post =sid[1];
var htmlData='<i class="'+reactionName.toLowerCase()+'IconSmall likeTypeSmall" ></i>'+reactionName;
var dataString = 'id_post='+ id_post +'&rid='+reactionType;
displayReaction(id_post);
/*
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {"done":1, "id_post":id_post, "rid":reactionType},
beforeSend: function(){alert(id_post);},
success: function(data){
},
});*/
});
function displayReaction(id_post){
a = $("#reactionEmoji" + id_post);
var cls = $(this.a).parent().attr('class');
var n = cls.split("reaction");
var reactionNew = n[1];
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {
"getReaction":1,"reactionNew":reactionNew
},
beforeSend: function(){
alert(reactionNew);
},
success: function(data){
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reaction" class="reaction1">
<div id="reactionEmoji1">nothing</div>
<div class="reaction-action">
<div rel="unlike" c="undefined" id="reaction1" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType">like</i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType">Amei</i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType">Haha</i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType">Uau</i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType">Triste</i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType">Grr</i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);;"/>
<span style="border-color:rgb(255, 255, 255);"/>
</div>
</div>
</div>
</div>
<div id="reaction" class="reaction2">
<div id="reactionEmoji2">nothing</div>
<div class="reaction-action">
<div rel="unlike" c="undefined" id="reaction2" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType">like</i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType">Amei</i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType">Haha</i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType">Uau</i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType">Triste</i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType">Grr</i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);;"/>
<span style="border-color:rgb(255, 255, 255);"/>
</div>
</div>
</div>
</div>
<div id="reaction" class="reaction3">
<div id="reactionEmoji3">nothing</div>
<div class="reaction-action">
<div rel="unlike" c="undefined" id="reaction3" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType">like</i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType">Amei</i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType">Haha</i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType">Uau</i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType">Triste</i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType">Grr</i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);;"/>
<span style="border-color:rgb(255, 255, 255);"/>
</div>
</div>
</div>
</div>
Thanks to Turnip below I was able to grab a chunk of HTML.
I would like to add the sections of this chunk to an object like so:
[{"quote":"xxx","author":"yyy"},{"quote":"xxx","author":"yyy"}]
The quote is in the tags:
...
$(document).ready(function() {
var origPage = "";
$.get("https://crossorigin.me/http://www.brainyquote.com/quotes/keywords/websites.html", {}, function(content){
origPage = content;
}, "html");
$("#myLink").on('click', function() {
var kill = origPage;
var oPage = $(kill);
var me = $('.bqQt', oPage);
$("div").html(me);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<a class ="clicker" id= "myLink" href="#" >click me</a>
And the autor is between the tags:
...
Right now the html structure for the items is as follows:
<div class="masonryitem boxy bqQt bqShare">
<div class="boxyPaddingBig">
<span class="bqQuoteLink">I'm on a strict gossip diet. No gossip websites, no gossip magazines. Otherwise, I find it paralyzing to exist.
</span><br>
<div class="bq-aut">Julie Bowen</div>
</div>
<div class="bq_q_nav boxyBottom boxyPaddingSmall" style="overflow:hidden;">
<div class="body bq_boxyRelatedLeft bqBlackLink">
Diet,
Gossip,
Magazines
</div>
</div>
<div class="bq_q_nav bq_q_btns boxyPaddingSmall" style="overflow:hidden;">
<div class="bq20">
<div ng-show="showMemberButtons()" class="bqAddQuote bqAddQuoteLg" style="float:right">
<span data-ng-click="onFavoriteClicked(455734)" data-ng-class="favCssClass(455734)" class="fa favHeart pointerCursor" onclick="hCl('/quotes/keywords/websites','/quotes/quotes/j/juliebowen455734','1')"></span><span data-ng-click="onAddToCollectionClicked(455734)" data-ng-class="collectionCssClass(455734)" class="fa favAddToCol pointerCursor" onclick="pCl('/quotes/keywords/websites','/quotes/quotes/j/juliebowen455734','1')"></span>
</div>
<table class="bq_tbl_nospc">
<tbody><tr>
<td valign="top">
<div class="nonJsIcons">
<a href="/share/fb/455734?sr=ql&from=%2Fquotes%2Fkeywords%2Fwebsites.html" class="fa-stack fa-lg fbShare" rel="nofollow" target="_blank">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</a>
<a href="/share/tw/455734?sr=ql&from=%2Fquotes%2Fkeywords%2Fwebsites.html&ti=Websites+Quotes" class="fa-stack fa-lg twShare" rel="nofollow" target="_blank">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</a>
</div>
</td>
</tr>
</tbody></table>
</div>
</div>
</div>
I am getting the html using:
<script>
$(document).ready(function() {
var origPage = "";
$.get("https://crossorigin.me/http://www.brainyquote.com/quotes/keywords/websites.html", {}, function(content){
origPage = content;
}, "html");
$("#myLink").on('click', function() {
var kill = origPage;
var oPage = $(kill);
var me = $('.bqQt', oPage);
$("div").html(me);
});
});
</script>
You already had the dom elements, you just needed to loop them and get the author and quote. Hope this helps.
$(document).ready(function() {
var apiCall = (function(){
return $.ajax({
method: "GET",
url: "https://crossorigin.me/http://www.brainyquote.com/quotes/keywords/websites.html",
cache: true
});
})();
var getAuthQuotes = function(elems){
var quoteArray = [];
$.each(elems, function(index, elem){
var obj = {};
var $elem = $(elem);
obj.quote = $elem.find('span.bqQuoteLink').text();
obj.author = $elem.find('div.bq-aut').text();
quoteArray.push(obj);
});
return quoteArray;
}
$("#myLink").on('click', function(e) {
e.preventDefault();
apiCall.then(function(origPage){
var kill = origPage;
var oPage = $(kill);
var me = $('.bqQt', oPage);
var authQuoteObj = getAuthQuotes(me);
//here is the array of objects
console.log(authQuoteObj);
});
});
});