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>
Related
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"
I have a div like below in HTML page:
When I click on any div I am saving the span text in DB and when again come back to the same page I am getting the response as saved text. on the basis of the text I need repopulate the clicked view.
I am adding all the code I have used, not able to populate the data.
<div class="panel-body">
<div class='score score-exel'>
<div class='arrow'></div><span class='scoreText'> 750-850 Excellent</span>
</div>
<div class='score score-good'>
<div class='arrow'></div><span class='scoreText'> 700-749 Good</span>
</div>
<div class='score score-ok'>
<div class='arrow'></div><span class='scoreText'> 650-699 OK</span>
</div>
<div class='score score-fair'>
<div class='arrow'></div><span class='scoreText'> 600-649 Fair</span>
</div>
<div class='score score-poor'>
<div class='arrow'></div><span class='scoreText'> 300-599 Poor</span>
</div>
<div class='btnHold'>
<button class='btn btn-success idkBtn'>I Don't Know</button>
<button class='btn btn-success submitBtn'>Submit</button>
</div>
</div>
In the below code for variable I am adding the selected value when the user clicks the div.
$('.score').bind('click', function(){
$('.arrow').hide();
$(this).find('.arrow').fadeIn();
userCreditScore = $(this).find('span').text().toString();
});
In below code I am getting response and trying to repopulate the data but not possible.
function fillData(){
var response = nav.scorm.getResponse('CREDIT_SCORE');
if(response != ''){
var jsonData = jQuery.parseJSON(response);
*** used many codes like below but not useful
//$('.score').find('span.scoreText:contains('+jsonData.CREDIT_SCORE+')').parent().css('display', 'block');
//$('.score').find('span.scoreText:contains('+jsonData.CREDIT_SCORE+')').parent().click();
}
I assume that you're missing the callback in your nav.scorm.getResponse method - if it's a AJAX call. Check the commented code you have:
//here we do the request
var response = nav.scorm.getResponse('CREDIT_SCORE');
//this line and is executed immediately, while 'response' var is still undefined
if(response != ''){
So depending on code you have in nav.scorm.getResponse you might have smth like
nav.scorm.getResponse('CREDIT_SCORE', function(response){
if(response != ''){
//put it to DOM
console.log(response);
}
});
UPD
The problem was with the spaces in your scores texts,
' 600-649 Fair' won't work, while '600-649 Fair' will do.
Check this fiddle - https://jsfiddle.net/shershen08/v3gxy8rL/
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>
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
}