Template won't append, but other things will - javascript

I am really stumped by this one. I have a template which contains data. I alert the variable containing this rendered template to prove it contains the data. I have tried using html() innerHTML() and others to then convert it before appending it. Using identical jquery syntax, I am able to append a div exactly as I desire, except with different contents.
success: function (data) {
if (data['success'] == 1) {
$.get('templates/PostReply.mustache', function(file){
var newPostArray={"reply_body":bodyText,
"replier_username": "<?php echo $sess_username; ?>",
"replier_profimg0": '<?php echo $sess_profimg0; ?>'
};
var html = Mustache.render(file, newPostArray);
$('#new-posts-container').append(html);
alert(html);
$(form).closest('#reply-divy').nextAll('#new-posts-container').append('<div>hello</div>');
//this works
$(form).closest('#reply-divy').nextAll('#new-posts-container').append(html);
// this does not work
e.preventDefault();
});
// You could also use the data['message'] that got sent back here.
}
},
So for some reason, the contents are unable to append. I am not receiving any errors.
This is what html looks like in an alert:
<div class="reply-div">
<div class="pull-left feed-entity-side-img">
<a href="profilepage.php?username=cb_snn">
<img src="photos/user_photos/public/2015/02/12/04/1ded2487680.jpg" alt="User" class="media-object no-padding reply-side-img"/>
</a>
</div>
<div class="media-body" style="padding-bottom:5px;">
<span class="pull-right" style=""> </span>
<span ><b>co_byrne</b></span>
<p> dgsadgasdgasdgasdgasdgasdgs
</p>
</div>
</div>

Related

Working JQuery Script not working after ajax post response

I'd really appreciate any help!
I have a working jquery script. When a div is clicked, it updates the css class to active and executes a working ajax response.
I also have a filter functionality that works too. When a checkbox is ticked it calls a new list of div's from mysql with all the same class properties. However, when any of these new div's are clicked the ajax response doesn't work. If anyone could help I would be incredibly grateful!
HTML:
<div id="result" class="results">
<div class="w-embed"><img src="images/loader.gif" id="loader" width="" "200px"="" style="display:none;">
<?php
$sql="SELECT * FROM `posts`";
$result=$con->query($sql);
while($row=$result->fetch_assoc()){
?>
<div class="c-card" data-id="<?=$row['id'];?>">
<h1 class="s-h2">
<?=$row['title'];?>
</h1>
<!-- <div class="s-para m-light m-small"><?=$row['description'];?></div> -->
<div class="c-stats">
<div class="s-stat">Pay:
<?=$row['pay'];?>
</div>
<div class="s-stat">Deadline:
<?=$row['deadline'];?>
</div>
<div class="s-stat">Location:
<?=$row['location'];?>
</div>
<div class="s-stat">Cat:
<?=$row['category'];?>
</div>
</div>
<p class="s-para">
<?=$row['description'];?>
</p>
Find Out More
</div>
<?php }?>
</div>
</div>
Javascript:
<script>
$('.c-card').on('click', function(event){
event.preventDefault();
$('.c-card').removeClass('active'); //Removes class to all
$(this).toggleClass('active'); //Applies class
var action = 'data';
var dataId = $(this).data("id");
$.ajax({
type:"POST",
url:"ajax/selected.php",
data:{action:action,id:dataId},
success: function(response){
$("#jobber").html(response);
$("#changeme").text("altered");
}
});
});
</script>
This is the outputted response from the filters:
'<div class="c-card" data-id="'.$row['id'].'">
<h1 class="s-h2">'.$row['title'].'</h1>
<div class="c-stats">
<div class="s-stat">Pay:'.$row['pay'].'</div>
<div class="s-stat">Deadline:'.$row['deadline'].'</div>
<div class="s-stat">Location: '.$row['location'].';</div>
<div class="s-stat">Cat: '.$row['category'].'</div>
</div>
<p class="s-para">'.$row['description'].'</p>
Find Out More
</div>';
So my question is how do i make the new divs (called from the filter) to continue to be triggered and change class + execute the ajax query.
Thanks so much in advance!
I have been thought your actual problem was the ajax response is getting null.
<div class="c-card" data-id="<?=$row['id'];?>">
You are using the data-id attribute in the HTML section. But the script handles the id attribute using for getting the id. So the id is getting null for ajax call, Please use the below code or change the data-id attribute to id in the HTML section as you like.
var action = 'data';
var dataId = $(this).data("data-id");
"id" and "data-id" are different attributes for HTML. Please use same attributes in HTML and script
maybe because there is no html(div|| p || span ||...) element that have id of id="jobber"

How can I use the input parameter value passed to a JavaScript function into the popup opened by this JS function?

I am not so into PHP and JavaScript and I have the following problem trying to pass a value from a main page to a popup page (defined into this main page).
I try to explain my situation in details:
I have an account.php page containing this link:
<a href="#" onclick="doRemoveBooking();">
<i class="fa fa-times"></i>
</a>
Clicking on this link it is performed the doRemoveBooking() JavaScript function that is defined in the same page into this block:
<script type="text/javascript">
//metodo richiamato al click del bottone "RIVENDI"
function doRemoveBooking(id){
console.info("Into doRemoveBooking");
$('.popUpRemoveBooking').magnificPopup({
items: {
src: '#remove-booking-popup'
}
// (optionally) other options
}).magnificPopup('open');
}
</script>
that opens a popup defined at the end of the dame account.php page by this div element:
<div class="popUpRemoveBooking">
<div id="remove-booking-popup" class=" white-popup-block mfp-hide">
<div class="fluid-container">
<div class="row">
<h2><?php echo $texts['CANCEL_BOOKING'] ?></h2>
<p>Sei veramente sicuro di voler cancellare la prenotazione?</p>
<?php echo $id_booking; ?>
</div>
</div>
</div>
</div>
This popup is correctly opened but I obtain an error message when it try to render this line:
<?php echo $id_booking; ?>
I know that it is wrong. As you can see my JavaScript function take an id as parameter:
doRemoveBooking(id)
How can I print this id received as input parameter from the JavaScript function used to open the popup in the popup body? (instead the wrong ). What is a smart and neat way to do it?
Replace <?php echo $id_booking; ?> with <span id="bookingID"></span>
Then replace the content of that <span> in your function:
function doRemoveBooking(id){
console.info("Into doRemoveBooking");
$('#bookingID').html(id); // <---------------- Add this line
$('.popUpRemoveBooking').magnificPopup({
items: {
src: '#remove-booking-popup'
}
// (optionally) other options
}).magnificPopup('open');
}
Don't forget to call doRemoveBooking(id) with the correct booking-id !

Unable to trigger popup box on click event

I'm wrapping up results of ajax request on div and appending to main div in a page. SO if the array of results returned empty, I would like to alert user, saying that no result found and also provide a link for them to click on. When they click a pop up box carrying products by category would popup. Important thing to notice here is,the products are derived via php and ajax scripts.
So When I use onclick event or directly, nothing happens!!!. But if I call empty or HTML pop up it would work. Also the same php scripts contained pop up would work if I trigger it on page load or in the ajax success function. SO I dont understand why only with on click it doesn't work?
This is the pop up I want to trigger on 'click' event
<section id="browse-search-popup" class="mfp-hide white-popup">
<h1>Browse Courses</h1>
Can't find what you're looking for? Tell us here!
<h2>First, pick a learning Zone:</h2>
<div class="row">
<div class="small-12 medium-8 large-8 medium-centered large-centered columns">
<ul class="small-block-grid-2 medium-block-grid-2 large-block-grid-2">
<?php
$tutor = new register();
$data = $tutor->get_maincat();
$i=0;
foreach($data as $k=>$v)
{
$i++;
?>
<li><div class="mainCat_<?php echo $i;?>" id="<?php echo $v['main_cat_id'];?>"><?php echo $v['main_cat_name'];?></div></li>
<?php
}
?>
</ul>
</div>
</div>
<h2>Then, pick a field:</h2>
<div class="row">
<div class="small-12 medium-12 large-12 columns" id="cat">
</div>
</div>
<h2>Finally, choose your Course:</h2>
<div class="row">
<div class="small-12 medium-12 large-12 columns" class="choosen_subjects">
</div>
</div>
<div class="row">
<div class="small-12 medium-12 large-12 columns" id="sub">
</div>
</div>
<input type="submit" id="done" value="Done">
</section>
Ajax request
$("#search_tutor").submit(function() {
var data = {
"action": "test"
};
var subject = $("#subject").val();
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "/fetch_tutor.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$("#contents img.loading").remove();
var sizy = data.length;
if(sizy ==0) {
console.log("sorry, cannot locate");
$(".simply-popup-link").trigger("click");
$("#simply-popup").empty();
//This is where I want to trigger the on click
$("#simply-popup").append("Unable to locate the subject you entered, please <a href='#' onclick='browse("+sizy+")' class='yellow'>Browse</a>");
}
console.log("size= "+data.length);
var j=0;
for (i = 0; i < data.length; i++) {
........................
......................
The browse function:
function browse(param) {
//this would work
/* $(".simply-popup-link").trigger("click");
$("#simply-popup").empty();
$("#simply-popup").append("test only"); */
// but not this
$(".browse-search-popup-link").trigger("click");
}
I tried loading the page into the an empty popup box ($("#simply-popup")) like this but doesn't work either:
$("#simply-popup").load('search/browse.php');
Change
$("#simply-popup").append("Unable to locate the subject you entered, please <a href='#' onclick='browse("+sizy+")' class='yellow'>Browse</a>");
to
$("#simply-popup").append("Unable to locate the subject you entered, please <a href='#' class='yellow browse'>Browse</a>");
write a separate code for this
$('body').on('click', '.browse', function() {
$('.browse-search-popup-link').click();
});
Can't you just call that function after append:
$("#simply-popup").append("Unable to locate the subject.....");
browse(sizy);// call it here.
or when you append it in the element then you can call the click:
$("#simply-popup").append("Unable to locate the subject.....");
$("#simply-popup a").click();
$(document.body).append('browse value is 1');
$(document.body).find('a').click();
function browse(num){ $(document.body).find('p').html("<pre>"+num+"</pre>");}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
log out here:
<p></p>

More effective way to append json data with jQuery & Laravel

I am building a twitter style feed with Laravel and jQuery.
My problem is that I'm sure I built this logic up badly.
So I have an included view what shows the tweet results.
Sending the data is just a basic ajax post with some DOM manipulation that's fine too.
After the form is submitted I display the fresh tweet with and append.
But the problem is no matter how i build my logic up, i always end up with duplication.
So what I do
Send the form, and the success function appends the data to the view
success: function(data) {
if(data.status === "success") {
$('#tweet-textarea').val("");
$('#tweets-wrapper').prepend(data.content);
}
},
And returning the goes the following way. After the tweet is saved, I return it in an array what I encode to json
$data = array('status' => 'success', 'content' =>
'<div class="tweet-box">
<div class="media">
<a class="pull-left" href="#">
<img src="http://placehold.it/60x60" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">
'. $this->tweet->user->metadata->full_name .'
<small>'. "#".$this->tweet->user->username .'</small>
<small>'. $this->tweet->created_at .'</small>
</h4>
'. $this->tweet->message .'
</div>
</div>
</div>');
I know not the best way, and my problem is actually in my controller I am duplicating code, because the returned result "content in array" is the same just like in my view, so if I make any modification I need to make both
So is there a more effective way to do this?
You can use jQuery jPut Plugin to append json easily
<div jput="template">
<div class="tweet-box">
<div class="media">
<a class="pull-left" href="#">
<img src="http://placehold.it/60x60" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">{{}}</h4>
</div>
</div>
</div>
</div>
<div id="main">
</div>
<script>
$(document).ready(function(){
//main is the div that you want to append
$('#main').jPut({
ajax_url:'domain.com/data.json', //your json data page
name:'template' //jPut template name
});
});
</script>
And in you json page no need to send all the div
$data = array('status' => 'success', 'content' => $this->tweet->user->metadata->full_name);
If you want to remove duplication of code, you are going to have to take all that logic out of your view and just pass it a nice long string for the entire section from your controller.
I'd start with making a function which can take a full name, username, timestamp, and message and create the tweet.
public function createTweet($fullName, $username, $created_at, $message)
{
return '<div class="tweet-box">
<div class="media">
<a class="pull-left" href="#">
<img src="http://placehold.it/60x60" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">
'. $full_name .'
<small>'. "#".$username .'</small>
<small>'. $created_at .'</small>
</h4>
'. $message .'
</div>
</div>
</div>';
}
Then when you are looping through your tweets, call this function each time through and keep concatenating the response in a string, then you can just pass the string to your view and echo it there.
On your function which is returning ajax, do the same...
return Respons::json(array(
'status' => 'success',
'content' => $this->createTweet($this->tweet->user->metadata->full_name, $this->tweet->user->username, $this->tweet->created_at, $this->tweet->message)
));
You could also take a lot at HTML::macro() as well if you find yourself needing this functionality across your entire app. http://laravel-recipes.com/recipes/181 for a nice and quick HTML::macro() tut.

Javascript + jquery issue

I am getting a bunch of "tasks" from a database and formatting this way with .each function.
$.getJSON('tarefas.php?acao=2', function(data) {
$.each(data,function(){
$('.task-item').parents('ul').prepend('
<li class="task-item nova">
<div class="status"></div>
<li id="'+(this).id+'">
<span class="id">ID: </span>
<span class="id" id="id_tarefa">'+(this).id+'</span>
<div class="task-comment">
<span class="helper-subtle">14/06/2011 14:32</span> database data
<div class="ico-delete"></div>
</div>
</li>'
});
});
And now I need to send this data to a php file and add more one log line when the bt-salvar is pressed.
<div class="task-log">
<span class="helper-subtle">14/06/2011 14:32</span> database data
<div class="ico-delete"></div>
</div>
I am using this code:
$('.bt-salvar').click(function() {$.ajax({type: 'POST',
url: 'tarefas.php?acao=3',
data: {'dados':'{"tarefa":"'+$('#id_tarefa').text()+'"}'},
success: function(){
$('#'+$('#id_tarefa').text()).prepend('
<div class="task-comment">
<span class="helper-subtle">data</span>
'+$('textarea').val()+
'<div class="ico-delete"></div>
</div>'
);
});
});
When I pressed the bt-salvar this line is added but just in 1 task. I should the problem is in way that I am referencing the id ($('#'+$('#data-group').text())).
I need to get the exact current task and put the log line just on this task. I donĀ“t know how can I reference the current tasks that was generated by the first.getJSON part of the page.
You have a <span class="id" id="id_tarefa">...</span> but it is being generated with $.each() so presumably you have several of them - identifiers must be unique.

Categories