I have a foreach() from database table, I want to show a popup/model to show its extra information.
I am showing just title and description and on click i want to open up a popup and show its extra information.
#foreach($myProjects as $project)
<div class="col-sm-4 col-md-4 notes notes--blue">
<a href="#edit-note" data-toggle="modal" style="background-color: #f9f9f9;border-bottom: 5px solid #42A5F5">
<div class="notes__title">{{$project->title}}</div>
<div class="notes__body">{{$project->description}}</div>
</a>
<div class="notes__actions" data-demo-action="delete-listing">
<i class="zmdi zmdi-delete"></i>
</div>
<div class="notes__actions1" data-demo-action="delete-listing">
<i class="zmdi zmdi-edit"></i>
</div>
<div class="notes__actions2" data-demo-action="delete-listing">
<i class="zmdi zmdi-eye"></i>
</div>
</div>
#endforeach
I am completely blank, Should i fetch post id to a hidden html tag and on model button click an ajax call will fetch the record info based on the id ?
I would add a data-id attribute to one of the elements, possibly the wrapper, then add something like
$(document.body).on('click', '.clickable_element', function(e){
if ($(this).data('id')) {
$.ajax({
url : 'your detail url',
data: { id: parseInt( $(this).data('id'), 10 ),
success : function(response){
// open popup and add response into it.
}
})
}
});
Update
I just noticed you already have bootstrap modal there.
you can add your data-id to data-toggle element then in javascript
$('[data-toggle=modal]').on('shown.bs.modal' , function(){
// do your ajax stuff
// add response in `.modal-body`
})
Related
I am trying to create a "quiz" page where a user can guess if an article is real or fake. I have data-info from my database that I am trying to compare with the data-info for a button clicked by the user to check if they are correct or not. For example, if the data-info of the article is true, and the user clicks the button with data-info true then alert " you're right" or whatever. Someone please help!!
function loadArticle(){
$.get("/api/article", function(response){
$(".header").html(response[0].Headline);
$("h1").attr("data-info", response[0].is_real);
$(".body" ).html('<a target="_blank" href="${response[0].web_address}"> ${response[0].web_address} </a>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "row" id="answers">
<button data-info="false" type = "button" class = "fa-bounce fas fa-times col-xs-4 col-xs-offset-2" id="fake">
FAKE
</button>
<div class="col-xs-4"></div>
<button data-info="true" type = "button" class = "fa-bounce fas fa-check col-xs-4 col-xs-offset-2" id="real">
REAL
</button>
</div>
You can compare data-* with the jQuery method .data()
here is an example when you get the data from the api request and compare its value when you click on the "real" button for example:
<button id="real" data-info="true">
real
</button>
<button id="real" data-info="false">
fake
</button>
var dataToCompare;
function loadArticle(){
$.get("/api/article", function(response){
dataToCompare = response[0].is_real;
}
}
$('#real').click(function() {
var data = $(this).data('info');
if(data === dataToCompare) {
alert('yes');
}
})
This is my Razor Page containing multiple divs with each div containing either follow or unfollow button with NeighbourhoodName and other stuff.
<p class="lead" style="display: none" data-bind="visible: profiles().length == 0">No neighbourhood found...</p>
<ul data-bind="visible: profiles().length > 0, foreach: profiles">
<li class="media" style="border-top: solid 1px lightgrey; padding-top: 15px;">
<div class="media-body">
<h4 class="media-heading">
<a class="btn pull-right" data-bind="visible: !IsFollowed, attr: { href: followAction }">Follow</a>
<a class="btn btn-danger pull-right" data-bind="visible: IsFollowed, attr: { href: unfollowAction }">Unfollow</a>
</h4>
<em data-bind="text: NeighbourhoodName"></em>
<em data-bind="text: NeighbourhoodId"></em>
//stuck at this line
</div>
</li>
I want to Generate a new page with click on any of the div. So,I want to send id of the neighbourhood to action method with click on respective div. Right now, i am able to get NeighbourhoodId with data-bind attribute but dont know how to send this id to action method with click on any area of div means how to mix this anchor tag. something like that.
This is my follow action url in a knockout code which send neighbourhoodId on follow button click:
self.followAction = location.protocol + "//" + location.host + '/Neighbourhood/Follow?uid=' + data.NeighbourhoodId;
But, i dont want any button. simple click on div should send id to action method.
how to achieve this. please suggest me something.
You simply have to use the click binding on the div, and bind it to a function in your viewmodel.
The function in your viewmodel receives as parameter the knockout context available in the bound element. So, you can directly access the desired data from that function.
<div class="media-body" data-bind="click: yourViewModelFunction">
In your viewmodel, your function should be implemented like this:
yourViewModelFunction = function(data) {
// here you can use data.NeighbourhoodId
}
Im trying to make a item editor.
For example:
I have a product and I want to remove the Serial number of it.(It's all stored in a database)
So I press the minus icon I 'borrowed' thats located next to the product's name:
<i class="icon-minus"></i>
This opens a modal named 'RemoveSerialNumberModal' with a 'Are you sure' button.
This works all fine, but there are multiple products underneath each other and how can I tell the modal on what product it needs to remove the serial number? (All product have there own pair of icons).
The modal it's code is in the same file as the product list. But not in the same foreach loop.
I prefer to not use JS, but if there is no other way. It has to do.
---------------EDIT---------------
The products do have there own id ofcourse.
---------------EDIT---------------
Here is the modal:
<!-- Modal -->
<div id="RemoveSerialNumberModal" class="modal hide fade">
<div class="modal-header">
×
<h3>Update serienummers</h3>
</div>
<div class="modal-body">
<p>Selecteer het serienummer dat je wilt verwijderen.</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Sluiten</button>
<button id="RemoveSerialNumber" class="btn btn-danger eerste" type="submit">Verwijderen</button>
</div>
</div>
Use data-id attribute.
I guess in your modal you have the below html :
<input type="text" name="yourid" id="yourid" value=""/>
//triggered when modal is about to be shown
$('#RemoveSerialNumberModal').on('show.bs.modal', function(e) {
//get data-id attribute of the clicked element
var yourid = $(e.relatedTarget).data('id');
//populate the textbox
$(e.currentTarget).find('input[name="yourid"]').val(yourid);
});
Use data attribute and class names to toogle while clicking:
<a class="click" href="#RemoveSerialNumberModal" data="2121" data-toggle="modal"><i class="icon-minus"></i></a>
$('.click').click(function(){
$('.click').removeClass('clicked');
$(this).addClass('clicked');
});
$('#RemoveSerialNumberModal').on('show.bs.modal', function(e) { // triggered when showing the modal
var data = $('.clicked').attr('data');
});
I am working on a bootsrap3 template, which is Ajax based.
My index file has a leftside menu and a conent block middle of the page, every time I click on a subelement of this left menu, an Ajax laod will put the page content in this block(ajax-content).*
Any time I call any page, my URL normally looks something like this /index.php#page-one.php, except when the page contains form submission.
The Problem happens when I add an action attribute (acion="page-one.php") to my form tag.
After the form submission my URL turns to /page-one.php ;
consequently I get a white page containing the page-one.php elements whitout any CSS styling and of course no index-file's elements.
What is the correct and best way to come a cross this issue?
index.php:
<body>
<!--Start Container-->
<div id="main" class="container-fluid">
<div class="row">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li class="dropdown">
<a id="configuration" href="#" class="dropdown-toggle">
<i class="fa fa-gears"></i>
<span class="hidden-xs">Menu-element</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="page-one.php">Menu-Subelement-one</a></li>
<li><a class="ajax-link" href="page-wo.php">Menu-Subelement-two</a></li>
</ul>
</li>
</ul> <!-- end of main-menu-->
</div>
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img.gif" class="loader" alt="preloader"/>
</div>
<!--inside this div a short description/introduction(simple text inside a <p> tag) about the Menu-element will be shown-->
<div id="content-header"></div>
<!--inside this div the page content of the Menu-subelement will be shown-->
<div id="ajax-content"></div>
</div>
<!--End Content-->
</div>
</div>
<!--End Container-->
<script src="plugins/jquery/jquery-2.1.0.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugin/jquery.form.js"></script>
<script src="js/script.js"></script>
And here is my script.js:
//
// Function for load content from url and put in $('.ajax-content') block
//
function LoadAjaxContent(url){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: url,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
//////////////////////////////////////////////////////
document.ready
//////////////////////////////////////////////////////
$(document).ready(function () {
var ajax_url = location.hash.replace(/^#/, '');
if (ajax_url.length < 1) {
ajax_url = 'home.php';
}
LoadAjaxContent(ajax_url);
$('.main-menu').on('click', 'a', function (e) {
var parents = $(this).parents('li');
var li = $(this).closest('li.dropdown');
var another_items = $('.main-menu li').not(parents);
another_items.find('a').removeClass('active');
another_items.find('a').removeClass('active-parent');
if ($(this).hasClass('dropdown-toggle') || $(this).closest('li').find('ul').length == 0) {
$(this).addClass('active-parent');
var current = $(this).next();
if (current.is(':visible')) {
li.find("ul.dropdown-menu").slideUp('fast');
li.find("ul.dropdown-menu a").removeClass('active')
}
else {
another_items.find("ul.dropdown-menu").slideUp('fast');
current.slideDown('fast');
}
}
else {
if (li.find('a.dropdown-toggle').hasClass('active-parent')) {
var pre = $(this).closest('ul.dropdown-menu');
pre.find("li.dropdown").not($(this).closest('li')).find('ul.dropdown-menu').slideUp('fast');
}
}
if ($(this).hasClass('active') == false) {
$(this).parents("ul.dropdown-menu").find('a').removeClass('active');
$(this).addClass('active')
}
if ($(this).hasClass('ajax-link')) {
e.preventDefault();
if ($(this).hasClass('add-full')) {
$('#content').addClass('full-content');
}
else {
$('#content').removeClass('full-content');
}
var url = $(this).attr('href');
window.location.hash = url;
LoadAjaxContent(url);
}
if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
$('#formSubmit').ajaxForm();
});
page-one.php:
<!--some php code here-->
<form class="validateForm" id="formSubmit" action="page-one.php" method="get">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" />
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="submit" class="btn btn-primary btn-label-left">
<span><i class="fa fa-save"></i> Save</span>
</button>
</div>
</div>
</form>
Thanks!
I had the same issue to solve for the intranet I work on.
For me, the good way to do this is to avoid using submit method and use instead an input button with a js function to send the form data.
In my case, I did this:
<!-- At the top of my webpage -->
<script language='Javascript'>
function loadingAjax(div_id,user,date1,date2)
{
$("#"+div_id).html('<br><center><img src="images/loading.gif"><br><br><font color="#006699" face="arial" size="4"><b>Loading data<br>VPlease wait ...</b></font></center>');
$.ajax({
type: "POST",
url: "activities.php?USER="+user+"&DATE1="+date1+"&DATE2="+date2,
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<!-- And here is my form -->
<form id='date_form'>
<input type='text' id='user'><input type='text' id='date1'><input type='text' id='date2'>
<input type='button' onclick="loadingAjax('myDiv',document.getElementById('user').value,document.getElementById('date1').value,document.getElementById('date2').value);">
</form>
This allow to send your form in a separate DIV without having to show to everyone your URL.
MORE: you can even use this function to manage your left side menu selection so that your URL would stay '/index.php' all the time.
Hope this help
Regards
Nico
How do you want to submit the form, using ajax?
If you want to use ajax, you should cancel the default action like you do with your links using e.preventDefault();. Post the javascript that handles the form submit if you need help with that.
If you want to post to page-one.php without using ajax, you could add a header() redirect after the php code that processes the form to redirect to the page that you would like to show after the form gets submitted.
As you are loading content by ajax,
You can post content to page-one.php and redirect user to it's previous page. But it will be difficult manage and show error, success, notification message like form validation errors etc.
Another and I think best solution is to use ajax form submission
I'm trying to submit a from which is located into a tabs. This tabs content is generated via AJAX.
My problem is that when I submit the form, the page refresh and the "default" tab is loaded so the php function generating the tab with the form never receive the post data.
Here the solutions I though about :
1) The easiest : Finding a way to insert a hash in the URL so that when the page refresh, a javascript code load the good tab.
2) The best (considering user experience) : Finding a way to submit the form with ajax and add the new entry to the list under the form in the tab. BUT I want to use php to check form values (is_empty(), etc.). I thought about sending data to the php controller, then, hide the form and replace it with the new form generated by the php controller (with error messages or empty fields if fields were ok and data added to the DB).
Here is my code :
The layout :
<ul class="nav nav-tabs" id="myTabs">
<li class="active">Profile</li>
<li>About</li>
<li>Wishlists <span class="badge"><?= $profile['wishlists'] ?></span></li>
<li>Following <span class="badge"><?= $profile['following'] ?></span></li>
<li>Followers <span class="badge"><?= $profile['followers'] ?></span></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="profile">Profile</div>
<div class="tab-pane" id="about">about</div>
<div class="tab-pane" id="wishlist">wl</div>
<div class="tab-pane" id="following">following</div>
<div class="tab-pane" id="followers">followers</div>
</div>
The tab :
<?php
if($owner)
{ ?>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<form class="form-horizontal" role="form" method="post">
<fieldset><legend>Add a wishlist</legend>
<?php echo $form; ?>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="addwishlist">Add</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<hr />
<?php
}
?>
<div class="row">
<?php
foreach($wishlists as $wishlist)
{ //Here we display whislists } ?>
The php controller that corresponding to the tabs view :
$manager = $this->managers->getManagerOf('Wishlist');
/**
* Adding a new wishlist
*/
if($owner)
{
//Creating object. Depends on form validation
if ($request->postExists('addwishlist'))
{
$wishlist = new \Lib\Entities\Wishlist(array(
'title' => $request->postData('title'),
'comment' => $request->postData('comment'),
'user' => $this->app->user()->getUser(),
));
}
else
{
$wishlist = new \Lib\Entities\Wishlist;
}
//generating form
$formBuilder = new \Lib\Forms\WishlistForm($wishlist);
$formBuilder->build();
$form = $formBuilder->form();
$formHandler = new \Lib\FormHandler($form, $manager, $request);
//if form has been validate : add the wishlist and set flash
if ($formHandler->process('add'))
{
$this->app->user()->setFlash('Your wish list has been created !');
$this->app->httpResponse()->redirect('/Shawili/'.$request->getData('user').'/wishlists/');
}
$this->page->addVar('form', $form->createView());
}
/**
* Displaying user's wishlists
*/
$wishlists = $manager->getWishlists($request->getData('user'), $this->app->user()->getUser());
$this->page->addVar('wishlists', $wishlists);
$this->page->addVar('owner', $owner);
$this->page->addVar('profile', $request->getData('user'));
$this->page->addVar('cuser', $this->managers->getManagerOf('User')->getUser($this->app->user()->getUser()));
The Jquery code :
<script type='text/javascript'>
$('#myTabs a').click(function (e) {
e.preventDefault();
var url = $(this).attr("data-url");
var href = this.hash;
var pane = $(this);
// ajax load from data-url
$(href).load(url,function(result){
pane.tab('show');
});
});
// load first tab content
$('#profile').load($('.active a').attr("data-url"),function(result){
$('.active a').tab('show');
});
</script>
Any suggestion of the best way to do that?
Second option is rather widely used practice and it always works well, so you can use it without concern.
Looking at your code I suppose, that you want to generate form code and send it via ajax to browser. It is not necessarily best way to do it. You don't have to hide and replace form. You can easyly modify existing one with jQuery.
The trick is to send to the browser only formated data containing info about errors etc. (for example using JSON) and then decode it (jQuery way) and localy modify content of web page.
To submit form via ajax you can just overwrite click event for the button and then collect data from fields and send it to the server, for example like this:
$("#submit_button_id").click(function(){
var formdata = $("#form_id").serializeArray();
$.ajax({
url: "/submit_url",
data: formdata,
success: function(RESPONSE){
//Your code to modify page content after geting RESPONSE.
}
})
return false; //To prevent page from reloading
}