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).
Related
i have implemented live search with jquery typeahead library, it is working fine for the case of data being received from database i have the issue on front end
right now the typeahead is working fine for displaying data what i want to do is add url in the href attribute of the li'sbeing generated from the dropdown but i havent still been able to even attach an onclick method with the li's here's my code so far.
HTML
<input autocomplete="off" id="type" placeholder="Search for product / category"/>
JAVASCRIPT
$('#type').typeahead({
source: function (query, result) {
$.ajax({
url: "<?php echo base_url()?>ajax_search/search2",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
PHP CI Model Function
public function search($query){
$keyword = strval($query);
$search_param = "{$keyword}%";
$conn =new mysqli($this->db->hostname, $this->db->username, $this->db->password , $this->db->database);
$countryResult[]=array();
$sql = $conn->prepare("SELECT * FROM category WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["name"];
}
echo json_encode($countryResult);
}
}
this is the html structure that is being generated when typeahead is called
this is what i have tried so far!
$(".typeahead").on( "click", "li", function() {
alert("1");
});
$(".typeahead .dropdown-item").delegate("click", function(){
alert("12");
});
$(".typeahead .dropdown-item").on("click", function(){
alert("123");
});
i copied one of the code from this thread stackoverflow thread but it is still not working for my case i have not idea why it is not working any help?
Since the element you are attaching the click event to will have been added to the DOM dynamically by typehead, you'll want to do so like this:
$('body').on('click', '.typeahead .dropdown-item', function() {
// do something
});
I have a page using Jquery Mobile list view. I'm trying to find a way to keep the listview look, but have a button that executes a command, without redirecting like normal do.
Here is how the Ahrefs are generated.
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
if ($row['photoLink'] == NULL)
{
$row['photoLink'] = "endofgroup";
$row['lastName'] = "End Of Group " ;
$ID = "&ID=".$row['ID'];
}
if ($row[leftGym] == "1") { $flash = "style='color:#B22222;font-size:140%'";} else {$flash ="";}
$row['firstName'] = strtoupper($row['firstName']);
$row['lastName'] = strtoupper($row['lastName']);
echo "<li><a href='WPSelect.php?sid=${row['sID']}' $flash style='font-size:140%;' width='25px' data-ajax='false'> {$row["lastName"]}, {$row["firstName"]}</a><div class='split-custom-wrapper'>
<a href='WDData.php?sID={$row['sID']}&lane=1{$ID}' data-role='button' class='split-custom-button' data-icon='delete' data-rel='dialog' data-theme='c' data-ajax='false' data-iconpos='notext'></a>
</div></li>";
}
/* free result set */
mysqli_free_result($result);
}
and here is the code I tried
<script>
$(function() {
//Attache the click event and perform this function
$("a").on('click', function(e) {
e.preventDefault(); //preven the page from navigating, the default behaviour for a link
$.ajax({
url: this.href, //perform a ajax request witht the link
/* type: POST, */
beforeSend: function() {
$("#status").text('Working..')
}
}).done(function(data) {
console.log(data); //do something with the data if any
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("ERROR"); //report in console for errors
console.info(jqXHR);
console.info(textStatus);
console.info(errorThrown);
}).always(function() {
$("#status").text('completed..')
console.info("completed"); //do this step everytime irrespective of result
});
})
})
</script>
Can anyone see what I could be doing wrong? Or is my idea even possible? Is there a better way to go about this? All I want is the user to be able to click the link, stay on the same page, but process the script on the referenced page.
Thanks in advance!
return false; at the end of your click function. If that doesn't do it, your database response is returning something that redirects.
Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );
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
I'm trying to get it so when a button is pressed it runs a PHP function without reloading the page.
I have this button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button>Reserve Book</button>
</div>
Which I want to run:
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reserbook.php', 'book_id');
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
</script>
The PHP file is, reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES
('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
The js runs fine and makes the modal box fade then out displaying the variable passed to it, I just don't know how to get the post working.
I've been trying to udnerstand looking at other answers on questions such as calling php function from jquery? and How to pass jQuery variables to PHP variable?
I'm also not sure if I need a ajax specific script to be called at the start as right now all I have is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
for my jquery.
It is probably something very simply, a rookie mistake, so all help is appreciated.
<script>
//called when button is clicked
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
//set parameter which you want to pass, url to be requested
$.ajax({ url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function(result) {
//after success it will be here and server have to send some data to be handled
alert(result);
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
What are you posting to reservebook.php? book_id is a string.You should send data in json or xml format to the server or using a query like key1=value1&key2=value2. $.post is a shortcut function i think it's better to use $.ajax and specify the type attribute POST.
You have to add a parameter to the post function to get the postdata in your php
{ jqbookID: book_id }
Try this :
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reservebook.php', { jqbookID: book_id }, function() {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
});