How can I not open a link in jQuery UI - php

I use jquery-ui (v1.12.1).
https://jqueryui.com/tabs/#ajax (TABS LOAD AJAX)
$( function() {
$("#tabs").tabs({
beforeLoad: function (event, ui) {
$('#preloader').show();
if (ui.tab.data("loaded")) {
event.preventDefault();
$('#preloader').hide();
return;
}
ui.ajaxSettings.cache = false,
ui.panel.html('<img src="assets/ajax-loader.gif"> Loading...'),
ui.jqXHR.success(function() {ui.tab.data( "loaded", true ); $('#preloader').hide();
}),
ui.jqXHR.error(function () {ui.panel.html("Couldn't load Data. Plz Reload Page or Try Again Later."); });
}
});
});
I want to not open the tabs "herf" in the form of a link.
<div class="part" id="tabs">
<ul>
<li>Apple</li>
<li>Samsung</li>
<li>Sony</li>
<li>HTC</li>
</ul>
</div>
What's wrong with the code?

I modified this code.
I have extracted the following code from this site:
http://demo.webslesson.info/jquery-ui-tooltip-with-ajax-php/
But I want to write as the tab of Ajax.
index.php
<?php
include('database_connection.php');
$query = "SELECT * FROM tbl_student ORDER BY student_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="part" id="tabs">
<ul>
<?php
foreach($result as $row)
{
echo '<li><a id="'.$row["student_id"].'" href="#">'.$row["student_name"].'</a></li>';
}
?>
</ul>
</div>
<script>
$(document).ready(function(){
$("#tabs").tabs({
beforeLoad: function (event, ui) {
$('#preloader').show();
$.post('fetch.php', { id:$(this).attr('id') }, function(data){ result(data); });
if (ui.tab.data("loaded")) {
event.preventDefault();
$('#preloader').hide();
return;
}
ui.ajaxSettings.cache = false,
ui.panel.html('<img src="assets/ajax-loader.gif"> Loading...'),
ui.jqXHR.success(function() {ui.tab.data( "loaded", true ); $('#preloader').hide();}),
ui.jqXHR.error(function () {ui.panel.html("Couldn't load Data. Plz Reload Page or Try Again Later."); });
}
});
});
</script>
fetch.php
<?php
if(isset($_POST["id"]))
{
$query = "SELECT * FROM tbl_student WHERE student_id = '".$_POST["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<img src="images/'.$row["image"].'" class="img-thumbnail" />
<h4>Name - '.$row["student_name"].'</h4>
<h4>Phone No. - '.$row["student_phone"].'</h4>
';
}
echo $output;
}
?>
When I click that tab, That text doesn't show.
Is jQueryUI code loaded incorrectly?

Related

How to post and update jQuery Serialize using AJAX

Please note, I have gone through the below StackOverflow question which is exactly what i need but unfortunately, it isn't posting
Question similar to
My Code -
Test.php
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
<ul id="sortable">
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
</ul>
Span 1: <span id="span"></span>
Span2: <span id="span2"></span>
<script>
$(document).ready(function () {
$('ul').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
$('#span2').text(data);
$.ajax({
data: data,
type: 'POST',
url: 'test2.php',
success: function(data){
$("#span").text(data);
}
});
}
});
});
</script>
Test2.php
<?php
include('../db.php');
$date = $_POST["data"];
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table SET something = '$something'
WHERE id = '$id'";
if(mysqli_query($conn, $sql)){
echo $date;
}
$conn->close();
?>
Can anyone help me out why the data is not posting to test2.php page
and
how can i sort the table using the data posted to test2.php
Thanks in advance.
For those who came across the same problem here's the solution :
Test.php
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
<ul id="sortable">
<?php
$q = ' SELECT * FROM temp';
$result = mysqli_query($conn, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<li id='sort_<?php echo $items['id'] ?>'>
<ul style="display:inline-block;"><?php echo $items['name'] ?></ul>
<ul style="display:inline-block;"><?php echo $items['name'] ?></ul>
</li>
<?php
}
}
?>
</ul>
<script>
$(document).ready(function () {
$('#sortable').sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'test2.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
});
$('#sortable').disableSelection();
</script>
Test2.php
<?php
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $conn->prepare(" UPDATE temp SET o_id = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$conn->close();
}
?>
Hope it helps the one in need.

Deleted rows removed from page but not from mysql database (PHP/jQuery)

I'm a complete beginner and have built a basic To-Do List application using PHP/jQuery. The application allows the user to add and remove tasks from a list (stored in a MySQL database).
I'm having issues with the delete function. When the delete button is clicked, it removes the task from the list but it must be remaining in the database, as it reappears once the page is refreshed.
I have no idea where I'm going wrong! Any help appreciated. See below code:
index.php :
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="list">
<ul>
<?php
require("db_connect.php");
$query = mysql_query("SELECT * FROM tasks ORDER BY date ASC, time ASC");
$numrows = mysql_num_rows($query);
if($numrows>0) {
while ( $row = mysql_fetch_assoc( $query ) ){
$task_id = $row['task_id'];
$task_desc = $row['task_desc'];
echo '<li><span>'.$task_desc.'</span><img id="'.$task_id.'" class="delete" width="10px" src="images/delete.png" /></li>';
}
}
?>
</ul>
</div>
<form class="new" autocomplete="off">
<input type="text" name="new-task" placeholder="Add a new task..." />
</form>
</div>
</body>
<script>
add_task();
delete_task();
function add_task() {
$('.new').submit(function() {
var new_task = $('.new input[name=new-task]').val();
if(new_task !== '') {
$.post('add_task.php', { task: new_task }, function ( data ) {
$('.new input[name=new-task]').val('');
$(data).appendTo('.list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete').click(function() {
var current_element = $(this);
var task_id = $(this).attr('task_id');
$.post('delete_task.php', { task_id: task_id }, function() {
current_element.parent().hide().fadeOut("fast", function() {
$(this).remove();
});
});
});
}
</script>
delete_task.php :
<?php
$task_id = strip_tags( $_POST['task_id'] );
require("db_connect.php");
mysql_query("DELETE FROM tasks WHERE task_id='$task_id'");
?>
You have an error in your delete_task function. There is no such attr as 'task_id'. Try to replace
var task_id = $(this).attr('task_id');
With
var task_id = $(this).attr('id');
Besides #IvanGajic answer is correct, also write your delete query like this:
mysql_query('DELETE FROM tasks WHERE task_id="' . $task_id . '"');

Ajax request to the same PHP page gives no errors but doesn't work

I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.

Print an array of variables from droppable area on a new page using ajax

I have drag and drop jquery. Accordion that allows user to drag and drop names into a droppable area. So what i want to do is to display dropped names on a new page after user click submit. But I cant get how to do it. I thought maybe its can be done using ajax but not sure how. Thanks in advance. Here is my code:
<link href="jquery-ui/jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui/jquery.js"></script>
<script src="jquery-ui/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#myAccordion"). accordion({heightStyle:"content", active: false, collapsible:true});
$(".source li").draggable({helper:"clone"});
$("#project ol").droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function(event, ui)
{
$(this).find(".placeholder").remove();
$("<li></li>").text(ui.draggable.text())
.addClass("project-item")
.addClass('dropClass')
.appendTo(this);
}
}).sortable({
items: "li:not(.placeholder)",
sort: function() {
$(this).removeClass("ui-state-default");
}
});
$("#myAccordion ul").droppable({
drop: function(event, ui) {
$(ui.draggable).remove();
},
hoverClass: "ui-state-hover",
accept: '.project-item'
});
$('#box').keyup(function(){
var valThis = $(this).val().toLowerCase();
if(valThis == ""){
$('.source > li').show();
} else {
$('.source > li').each(function(){
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).show() : $(this).hide();
});
};
});
});
</script>
<div id="myAccordion" style="width:20%; float:left; margin-right:30px;">
<?php for($i=321; $i<347; $i++)
{
echo "<h3>".chr($i)."</h3>";
echo '<ul class="source">';
$sql = "SELECT username FROM user WHERE username LIKE '".chr($i+32)."%' ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$name= $row["username"];
echo"<li class='ui-state-highlight'>". $name ."</li>";
}
} else
{
echo "0 results";
}
echo '</ul>';
}
?>
</div>
<form class="formcss" method="POST" action="create3.php">
<fieldset style="background-color:white;">
<div id="project" style="margin-left:10%;">
<label>Leader:</label>
<ol>
<li class="placeholder" name="leader[]" <?php if (isset($leader[$i])) echo 'value="'.$leader[$i].'"' ?>>Add leaders and checkers here</li>
</ol>
<br><br>
<div class="row">
<input type = "submit" name ="submit" class="button" value = "Create Project" onclick="userSubmitted = true;"/>
</div>
</div>
</fieldset>
</form>

AJAX and jQuery search CodeIgniter

I'm trying to do AJAX search for my application but I have some problems.
I have table posts with fields id, title, summary, content. I want to make posts search by title.
In my controller I load model posts and my index function look like this
function index()
{
$search= $this->input->post('search');
$query = $this->posts->search_posts($search);
echo json_encode ($query);
}
in my model posts.php I put this function
function search_posts($search){
$this->db->select("id,title,summary,content");
$whereCondition = array('title' =>$search);
$this->db->where($whereCondition);
$this->db->from('posts');
$query = $this->db->get();
return $query->result();
}
and my view look like this
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('css/style.css');?>">
<script type="text/javascript" language="javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/json2.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
if($("#search").val().length>3){
$.ajax({
type: "post",
url: "http://localhost/blogFinal/index.php/blog",
cache: false,
dataType: 'json';
data:'search='+$("#search").val(),
success: function(response){
$('#finalResult').html("");
var obj = JSON.parse(response);
if(obj.length>0){
try{
var items=[];
$.each(obj, function(i,val){
items.push($('<li/>').text(val.title + " " + val.summary));
});
$('#finalResult').append.apply($('#finalResult'), items);
}catch(e) {
alert('Exception while request..');
}
}else{
$('#finalResult').html($('<li/>').text("No Data Found"));
}
},
error: function(){
alert('Error while request..');
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="wrap">
<header>
<h1><?php echo anchor('','My Blog'); ?></h1>
</header>
<div id="container">
<div id="loginDiv"><?php echo anchor('admin/logout','Logout'); ?></div>
<hr/>
<input type="text" name="search" id="search" />
<ul id="finalResult"></ul>
</div>
<div style="clear: both;"> </div>
I make this by following tutorial but it doesn't work for me.
Can somebody help me please? Thanks!

Categories