Gallery load with ajax in cakephp - javascript

I use Cakephp 2.8.0. My problem is ajax. I don't know how realize ajax in my application. I have li links with categories and after click i need delete some html code and find in my controller necessary category and get this array in response html and print it.
my PhotosController action:
public function getPhotoByCategory($category = null)
{
$category=$_GET['category'];
debug($category);
$this->render('getPhotoByCategory', 'ajax');
}
My html code:
<div class="lol">
<ul>
<?php foreach($categories as $category):?>
<li>
<?php echo $category['Category']['cat_name'];?>
</li>
<?php endforeach;?>
</ul>
</div>
My JS code:
$(".lol").click(function (e) {
e.preventDefault();
var category = $(this).attr("href");
$.ajax({
type: 'get',category,
data: {catyegory:
url: '<?php echo $this->Html->url(array('controller' => 'Photos', 'action' => 'getPhotoByCategory')); ?>',
success: function(response) {
if (response.error) {
alert(response.error);
console.log(response.error);
}
if (response.content) {
$('#target').html(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});
Please, help me with right ajax in cakephp for this situation.

I find the best way to handle AJAX for fetching items is to create an element of the items you want to insert (in your case photos from a category).
PhotosController.php
public function getPhotoByCategory($category = null)
{
$this->set('photos', $this->Photo->find('all', ['conditions' => ['category_id' => $category]]);
$this->render('Elements/getPhotoByCategory');
}
The element in the above example contains a for loop that loops through $photos and outputs them. This is then loaded into the div "lol" using the JS code down below:
Views/Photos/get_photo_by_category.ctp
<button class="loadphoto">Load Photos</button>
<div class="lol">
</div>
JS Code (top of view?)
$('.loadphotos').click(function(e) {
$('.lol').load('/Photos/getPhotoByCategory/1')
.fail(alert("error"));
});
Dereuromark has done some decent documentation on AJAX and CakePHP

Related

Two target for one <a> tag and display two results in two different div

Student.php -here i am getting list of students from a specific Institution in a tag
<?php
if(isset($_POST['c_id'])) { //input field value which contain Institution name
$val=$_POST['c_id'];
$sql="select RegistrationId from `students` where `Institution`='$val' ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$number=$row['RegistrationId'];
?>
<a href='<?php echo "index.php?StudentID=$number"; ?>' target="index" id="link">
//getting student id in the dynamic link
<?php echo "$number";
echo "<br/>";
}}
?>
<div id="index" name="index"> </div>
<div id="Documents"> </div>
<script>
$(document).on('change', 'a#link', function()
{
$.ajax({
url: 'Documents.php',
type: 'get',
success: function(html)
{
$('div#Documents').append(html);
}
});
});
</script>
In index.php - I am Getting students details based on $_GET['StudentID'] ('a' tag value)
<?php
$link=$_GET['StudentID'];
$sql = "select StudentName,Course,Age,Address from `students` where `RegistrationId`="."'".$link."'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['StudentName']."<br/>";
echo $row['Course']."<br/>";
echo $row['Age']."<br/>";
echo $row['Address']."<br/>";
}
?>
In Documents.php -I am getting documents related to the speific student selected in 'a' tag
$link=$_GET['StudentID'];
$qry = "select Image,Marksheet from `documents` where `RegistrationId`='$link'";
$result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$image = $row["Image"];
$image1 = $row["Marksheet"];
echo '<embed src='. $image.'>';
echo ' <object data='. $image1.'width="750" height="600">';
echo ' </object>';
}
On click of student id i am trying to get result from index.php to div()
and result from Documents.php to div()
(i.e)two target for one click in tag
My code only take me to the index.php file result in a new Window
Please Help me to solve this problem
(sorry if my question seems silly i am new to php)
Update:
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
});
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
From your question, it seems that you want to load the two results, one from index.php and one from Documents.php in two separate divs on the same page when the link is clicked.
But you're using a change event on the link, not a click event. The change event is not fired when the link is clicked, so JavaScript does not get executed and the page loads to the URL specified in the href attribute of the link. So first you need to change $(document).on('change') to $(document).on('click').
Furthermore, since you want two results to load - one from index.php and one from Documents.php, you'll need to create two ajax requests, one to index.php and the other for Documents.php. In the success function of each of the ajax requests, you can get the response and put it in the corresponding divs.
In addition to this, you'll also need to prevent the page from loading to the new page specified in href attribute when the link is clicked, otherwise the ajax requests fired on clicking the link will get lost in the page load. Thus, you need to add a e.preventDefault(); to your onclick event handler like this:
$(document).on('click', 'a#link', function(e) {
// Stop new page from loading
e.preventDefault();
// Two ajax requests for index.php and Documents.php
});
Update: You don't need to add two click handlers for each ajax request. Inside one click handler, you can put both the ajax requests.
Also your event handlers won't register if you're adding them before jQuery, or if you're adding them before the DOM has loaded. So move your code to bottom of the HTML page, just before the closing </body> tag.
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link
You can change your <a> tag like below :
..
Then , in your jquery code do below changes :
$(document).on('click', 'a.link', function(e) {
var StudentID = $(this).attr("data-id") //get id
console.log(StudentID)
e.preventDefault();
$.ajax({
url: "details.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
call_next_page(StudentID);//next ajax call
}
});
});
function call_next_page(StudentID) {
$.ajax({
url: "index.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
}
});
}
And then at your backend page use $_POST['StudentID'] to get value of student id instead of $_GET['StudentID'];

Change wordpress shortcode with Javascript

let's say I have a wordpress shortcode, in a page (not post), like [display id="144,145,146"] and I want to add a link in the page like "click here to sort by views", so I can click the link and a javascript function can change the shortcode, putting different ids. Is it possible?
This is not possible without using AJAX unless you load you load all of the different short code options beforehand.
Preloading Shortcodes:
$('#change-shortcode').on('click', function() {
$('.shortcode-container').toggleClass('hidden');
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shortcode-container">[display id="144,145,146"]</div>
<div class="shortcode-container hidden">[display id="147,148,149"]</div>
<br/><br/>
<a id="change-shortcode">Click Here</a>
Fetching Shortcodes with AJAX:
// Add the "fetch_shortcode" AJAX action.
add_action('wp_ajax_nopriv_fetch_shortcode', 'fetch_shortcode');
add_action('wp_ajax_fetch_shortcode', 'fetch_shortcode');
function fetch_shortcode() {
if (isset($_POST['ids'])) {
$ids = implode(',', $_POST['ids']);
// ob_start and ob_get_clean will prevent the shortcode from displaying and instead will return the value to the $html variable.
ob_start();
do_shortcode('[display id="' . $ids . '"]');
$html = ob_get_clean();
wp_send_json_success($html);
}
}
On the front end, you would have this:
<div id="shortcode-container">[display id="144,145,146"]</div>
<br/><br/>
<a id="change-shortcode">Click Here</a>
<script>
$('#change-shortcode').on('click', function() {
// This is where you get to use the 'fetch_shortcode' action name that you created above.
data = {
ids: [147, 148, 149],
action: 'fetch_shortcode'
};
$.ajax({
url: "<?php echo admin_url('admin-ajax.php') ?>",
method: "POST",
data: data
}).done(function(response) {
$('#shortcode-container').html(response.data);
});
});
</script>

load() function won't allow scripts on page to execute

I have a php script which has a select box which allows user to filter some data.And I have used change event on select box to trigger jquery's load function to load a div of another page which will show that filtered data.Now the problem is I have a javascript function which is being called from that page upon some check in php , and this is resulting in that javascript function not getting called at all.Is there any work around in this scenario?I tried using $.get() but I'm not sure if it will allow me to load only part of page.
This is the load() function's call
$('document').ready(function() {
$('#topic-filter-select').on('change' , function(e) {
$.ajax({
type: 'GET',
url: templateUrl+"/ajax/custom_ajax_functions.php",
data : {
functionName : 'load_topic_filter',
topic_id : e.target.value
},
success: function(result) {
for(var i=0;i<result.length;i++)
result[i] = parseInt(result[i]);
result = JSON.stringify(result);
$('#activity-container').empty();
$('#activity-container').load("/topic-filter-template?result="+result+" #topic-page");
},
error: function(error) {
$('#post-0').empty();
$('#post-0').append("<div id='filtered-activities'><h4>Something went wrong , please try again.</h4></div>");
}
});
});
});
And the php check which gives call to javascript function is
<?php $result = has_user_voted($poll_id , $current_user_id);?>
<?php if($result[0] == true) :?>
<?php echo '<script type="text/javascript">animatePollEffect('.json_encode($result).','.$poll->ID.')</script>';?>
<?php endif; ?>
there your question and code snippet creating a lots of confusion. Please, correct it properly to understand what you want exactly.

Ajax test (wordpress)

So, I have been struggling with making ajax work.
Here is my previous question: AJAX (admin_url('admin-ajax.php');?action=) Not Found
Anyway, I decided to narrow down and only have necessary files.
Here is the set up.
test.php
<div class="test">
Items
</div>
<div id="test_demo"> </div>
<script>
jQuery(document).ready(function() {
jQuery('.test a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: 'html',
data: ({ action: 'test_tab', id: tab_id}),
success: function(data){
jQuery('#test_' + tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
function.php
function test_tab_callback() {
$template_part_path = 'page-parts/test_' . $_GET['id'];
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_test_tab', 'test_tab_callback');
add_action('wp_ajax_nopriv_test_tab', 'test_tab_callback');
test_demo.php
<div id="test_demo_content">Demo Content</div>
Here is the my idea on how it should work.
test.php: When user clicks Items button, then the tab_idvariable in the jQuery saves the anchor id (in this case, it will be id="demo").
Then admin-ajax.php is called.
The saved id ("demo") is then passed onto the function.php and it is used in the variable $template_part_path = 'page-parts/test_' . $_GET['id']; which gives page-parts/test_demo for test_demo.php
Then the template part is called and calledback to the jQuery.
Then the data is "insert" into the jQuery('#test_' + tab_id).html(data); which is id="test_demo.
The test_demo.php content should be displayed in the #test_demo div.
But it is not working. I used console.log(data) but showed no result.
What am I doing wrong?
When your getting the jquery object of "this" you can't use the quotes. This was making tab_id as undefined and ruining the rest.
Here is what I mean:
http://jsfiddle.net/7r1dg7L4/2/
jQuery(document).ready(function() {
jQuery('.test a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
alert(tab_id);
});
});

Jquery Tab add remove

Tab 1 does not work. Tab 1 is drawn from MySQL table. I want show default tab and add or delete an extra tab and post mysql get inserted tab id append not count?. Can you help?
Visit jsfiddle jsfiddle.net/datakolay/33aM3/
Html
<ul id="tabul">
<li id="litab" class="ntabs add">+</li>
<li id="t21" class="ntabs"> Tab Mysql id 21
×
</li>
<li id="t22" class="ntabs"> Tab Mysql id 22
×
</li>
</ul>
<div id="tabcontent">
<p id="c21">Test</p>
<p id="c22">Test</p>
</div>
Javascript
$(function() {
var total_tabs = 0;
total_tabs++;
$("#addtab, #litab").click(function() {
total_tabs++;
$("#tabcontent p").hide();
addtab(total_tabs);
return false;
});
function addtab(count) {
var closetab = '×';
$("#tabul").append('<li id="t'+count+'" class="ntabs">Tab Extra '+closetab+'</li>');
$("#tabcontent").append('<p id="c'+count+'">Tab Content </p>');
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#t"+count).bind("click", function() {
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+count).fadeIn('slow');
});
$("#close"+count).bind("click", function() {
// activate the previous tab
$("#tabul li").removeClass("ctab");
$("#tabcontent p").hide();
$(this).parent().prev().addClass("ctab");
$("#c"+count).prev().fadeIn('slow');
$(this).parent().remove();
$("#c"+count).remove();
return false;
});
}
});
MY NEW EDİT
Visit jsfiddle jsfiddle.net/datakolay/33aM3/8/
$(function() {
$('#tabcontent p').hide().filter(':lt(1)').show();
$("#tabul li").removeClass("ctab");
$(".ntabs").filter(':lt(1)').addClass("ctab");
$("#addtab").click(function() {
$("#tabcontent p").hide();
var dataString = '';
$.ajax({
type: "POST",
url: "add_tab.php",
data: dataString,
cache: false,
success: function(html)
{
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+count).fadeIn('slow');
}
});
return false;
});
$(".ntabs").bind("click", function() {
var id = $(this).attr('id')
$("#tabul li").removeClass("ctab");
$(".ntabs").addClass("ctab");
$("#tabul li").removeClass("ctab");
$("#"+id).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+id).fadeIn('fast');
});
$(".close").bind("click", function() {
var id = $(this).attr('id')
$("#tabul li").removeClass("ctab");
$("#tabcontent p").hide();
$(this).parent().prev().addClass("ctab");
$("#c"+id).prev().fadeIn('fast');
$(this).parent().remove();
$("#c"+id).remove();
return false;
});
You're only adding the event listener to dynamically added tabs i.e.; tab 2, tab 3, tab 4... since tab 1 is hardcoded into the html opposed to being dynamically loaded in, it's never getting the listener added. Although there are a ton of optimizations I'd add to this, the quick fix is to add.
$("#t1").bind("click", function() {
$("#tabul li").removeClass("ctab");
$("#t1").addClass("ctab");
$("#tabcontent p").hide();
$("#c1").fadeIn('slow');
});
I believe your problem is in fact in your HTML not your JQuery. It appears to work properly (as far as I can tell) if you modify your html from this:
<ul id="tabul">
<li id="litab" class="ntabs add">+
<li id="t1" class="ntabs"> Tab 1×</li>
</li>
</ul>
<div id="tabcontent">
<p id="c1">Test</p>
</div>
To this:
<ul id="tabul">
<li id="litab" class="ntabs add">+</li>
</ul>
<div id="tabcontent">
</div>
Then, I'd make a small adjustment to your JQuery, change:
var total_tabs = 1;
to:
var total_tabs = 0;
Next, you'd need to work on the way your JQuery handles closing tabs. If the first tab is closed, the '+' tab is displayed. If a tab is closed that's not currently focused, it changes focus to the previous tab of the closed tab.
JSFiddle with my suggestions.
Edit: I also thought I'd present one more thing. My assumption is that you're going to have some way to dynamically add content to these tabs; given that, I'd dynamically add the first tab (like my suggestion would do) instead of hard coding it into the html simply due to the fact that your JQuery already works for tabs dynamically added (meaning you're doing something wrong with adding listeners to the static tab). Just my two cents.
Edit 2: To answer your question about how to access your MySQL data from JQuery, you should really google something like JQuery get data from MySQL database. That said, you've added PHP to the tags, so we'll assume that's what you want to use. You need to construct an AJAX call through JQuery to retrieve the information. Also, you need a PHP script to interact with the server.
PHP Script:
<?PHP
$db_address = 'localhost';
$db_user= 'root';
$db_pass= 'password';
$db_name= 'TabData';
$db;
function connect() {
global $db, $db_server, $db_user, $db_password, $db_dbname;
if (!$db) {
$db = mysql_connect($db_server, $db_user, $db_password);
}
if (!$db) {
die('Could Not Connect: ' . mysql_error());
} else {
mysql_select_db($db_dbname);
}
}
function disconnect() {
global $db;
if ($db) {
mysql_close($db);
}
}
function query($query) {
global $db;
if (!$db) {
connect();
if ($db) {
return query($query);
}
} else {
$result = mysql_query($query);
return $result;
}
}
function getTabData($id) {
$result = query("SELECT * FROM tabs WHERE id = \"".$id."\"");
}
$data = array();
$json = file_get_contents('php://input'); // read JSON from raw POST data
if (!empty($json)) {
$data = json_decode($json, true); // decode
if(isset($data["id"]) && !empty($data["id"])) {
connect();
getTabData($data["id"]);
disconnect();
}
?>
Basically, that code will connect to a database named TabData and return in JSON the information from the row in table tabs with an ID matching that passed in the AJAX query.
JQuery for creating an AJAX call to the above PHP code (contained in a file named myPHP.php):
function updateTab(tabID) {
$.ajax({
type: "POST",
url: "/myPHP.php",
contentType: "application/json",
data: JSON.stringify({id: tabID}),
success: function (data) {
var tabData = $.parseJSON(data);
$.each($.parseJSON(data), function() {
$("#c" + this.id).html("" + this.info);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + "\nXMLHttpRequest status: " + XMLHttpRequest.status + "\nXMLHttpRequest statusText: " + XMLHttpRequest.statusText + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
});
}
Basically, that code will connect to a php script named myPHP.php and send an AJAX query with the ID of the passed in ID. Upon successful return of the request, the success function will return, which parses the returned data from the PHP script and updated the content page of the appropriate id. I haven't tested this code (since I don't have a readily available environment); but it is code that I have slightly modified from some of my existing code (thus, it should work without too many adjustments).

Categories