How to pass database id in jquery - php

i want to delete a record that are showing in while loop from the database but before deleting i want to display a confirmation box.The code i have written is below.it is working fine but to delete record i need to pass an id that i haave described in the code
------index.php starts
<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
<div class="item">
<div class="delete"></div>
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
----index.php ends
----jquery.confirm.js file starts
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
----jquery.confirm.js file ends
-----script.js file starts
$(document).ready(function(){
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
elem.slideUp();
//sql delete query will be written here... in where condition i need to pass the fetched record id from index.php file in where condtion
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
});
-----script.js ends

You can use the html data attribute and retrieve it with .data jQuery method
In your HTML:
<div class="delete" data-id="{$id}"></div>
In your Javascript
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
var id = elem.data('id'); /* this is your db id */
});

Are you sure you want to send a query from Javascript? The usual way to do this is to send a request (via jQuery) with that specific id, to a script which runs the query (server side), and returns a response.
Now, since you add the item divs, using a while, why not add an id property to the divs, which contain the id from the database, something like
<div id="item<?php echo $row['id'];?>" class="item">
<div class="delete">
</div>
This way, the $('.item .delete').click handler has access to the item's id, by parsing the target's id property, and you don't need to pass it explicitly to jQuery.

Here you can use hidden field to save value for id and then use jquery to retrieve it from hidden field..
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<input type="hidden" id="hid_id" value="<?php echo 'fetched id';?>" />
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
And then in jquery when using confirm box you can get value by id hid_id .

Related

How to get value FROM Ajax in index.php

I would like to get the value sent from php via AJAX in php. But i can not get value. Where is my mistake?
It is my functions.js
$(document).ready(function(){
$(".yeni_problem").click(function(){
var uid = 1;
$.ajax({
url: 'admin.php',
type: "post",
data: {'uid': uid},
success: function(data){
// $("#cvb").text(data);
},
statusCode: {
404: function(){
alert("admin.php not found");
}
}
});
});
});
and it is my php page that, i control sending value in here. The Codes is large but i write small form. Which that when i run the small codes on other folders as other site it does't work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HELPDESK</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/css.css">
<link rel="stylesheet" href="css/default.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/icon.css">
</head>
<body>
<button class="yeni_problem">Yeni Problem</button>
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "<hr>Value not found<br/>";
}
var_dump($_POST);
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
<?php
echo "</body>
</html>";
?>
When i click to ".yeni_problem" class i can not get value.
1st- check you include Jquery
2nd- Be sure admin.php page in the same directory with file you called functions.js in if not check its path
3rd- you pass uid not data so in php use
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "Value not found";
}
?>
4th: and if you dynamically generate the element with class="yeni_problem" .. so use
$('body').on('click',".yeni_problem", function(){
instead of
$(".yeni_problem").click(function(){
5th: if yeni_problem is a submit button or anchor so you need to use e.preventDefault(); to prevent page from reloading
$(".yeni_problem").click(function(e){
e.preventDefault();
// rest of code here
6th: if yeni_problem is a form use .submit()
$(".yeni_problem").submit(function(e){
e.preventDefault();
// rest of code here
Pay attention to your code: in the JS snippet, the parameter passed to the server is "uid", which means your server will be getting a $_POST array with a position labeled "UID".
<?php
if(isset($_POST["uid"])){
echo "Value:".$_POST["uid"];
}else{
echo "Value not found";
}
?>
You should also check what is in the $_POST variable, insert var_dump($_POST) and comment out the rest of the code.

Setting innerHTML with PHP?

So basically I have this program that sets a header (id="infoHeader") at the top of the page to some text retrieved from another site. I need this however to change when a button is pressed. As you can see it currently uses a PHP script to fetch the text from a given URL but I need to fetch from a different URL when a button is pressed. So basically
Button1 press -> infoHeader = Site 1 text
Button2 press -> infoHeader = Site 2 text
Is there a way to use a button to change the innerHTML of [id="infoHeader"] so that it runs the PHP script to get the text.
It is kind of difficult for me to explain, if you need I can try and give more info.
<!DOCTYPE HTML>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
</head>
<body>
<div id=page>
<div id=leftPanel>
<p id=missionsHeader>Active Missions</p>
<p><?php include("getList.php")?></P>
</div>
<div id=info>
<p id=infoHeader><?php include("getData.php"); getTitle("http://www.blade-edge.com/images/KSA/Flights/craft.asp?r=true&db=dunai"); ?></p>
</div>
</div>
</body>
You need to use JavaScript + AJAX. JavaScript is needed to change the content of the div after the page is loaded/rendered and AJAX for loading a PHP file without the need to refresh the web page.
I recommend you to use jQuery and it's ajax function.
<!DOCTYPE html>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
<!-- include jQuery -->
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function() { // wait for the DOM to finish loading
// button1
$("#someID").click(function() { // element with id "someID" (your button)
$.ajax({
url: "getData.php", // the content of the page which you want to load
cache: false
}).done(function(dataFromServer) {
$("#infoHeader").html(dataFromServer); // set the data from the server (getData.php) as the content of the element with the id "infoHeader"
});
}):
// button2
// the same as above for the other button
});
</script>
</head>
<body>
<div id="page">
<div id="leftPanel">
<p id="missionsHeader">Active Missions</p>
<p> <?php include("getList.php"); ?> </p>
</div>
<div id="info">
<p id="infoHeader"> <?php include("getData.php"); getTitle("http://www.blade-edge.com/images/KSA/Flights/craft.asp?r=true&db=dunai"); ?> </p>
</div>
</div>
</body>
</html>
For your problem:
Change content of div - jQuery
http://api.jquery.com/jquery.ajax/
Here are some good resources for JavaScript, jQuery and AJAX:
JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript
jQuery: http://en.wikipedia.org/wiki/JQuery
jQuery: http://www.w3schools.com/jquery/
jQuery: http://www.codecademy.com/en/tracks/jquery
jQuery + AJAX: http://www.w3schools.com/jquery/jquery_ajax_intro.asp

jQuery Mobile loads content only after I hit refresh

My jQuery Mobile page does not load content via $.get which is bind into pageinit event, but does so when I hit refresh (F5), why is that so?
My HTML page igra.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- stili za custom temo, jquery, jquery mobile, phonegap-->
<link rel="stylesheet" href="themes/what.min.css" />
<link rel="stylesheet" href="jquerymobile.css" />
<script src="jquery191.js"></script>
<script src="jquerymobile.js"></script>
<script src="phonegap.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="stil.css" />
</head>
<body>
<div data-role="page" id="igra">
<div data-theme="a" data-role="header">
347 coins
<h3>WHAT?</h3>
Home
</div>
<div data-role="content" class="igracontent"> </div>
</div>
</body>
</html>
My main.js with jQuery Mobile code:
$( document ).delegate("#igra", "pageinit", function() {
var par = qs["battlefield"];
$.get('igra.php?battlefield='+par, function(data2) {
$('div.igracontent').append(data2).trigger('create');
});
});
//parse url parameter
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
In igra.php I make SQL query and retrieve some data which I format in jQuery Mobile style and echo it back.
I know jQuery Mobile does not load head into DOM in subsequent pages, so main.js is also included in index.html head which is landing page of my app. All transitions to new pages are by normal ajax querying (I do not prevent default behaviour).
So what happens? When I navigate to igra.html?battlefield=3 the pageinit event does happen but content which I load via $.get from php page does not get inserted! If I hit F5(refresh) the content does get loaded into page. Can anybody explain and help? :) Thank you!

jQuery click event not working from php listing

I have a story uploading system on my webpage, which uploads stories in a specified folder, and from that it lists their content to the webpage. I made a split, so only 300 chars are shown of the text, when the user clicks it, the rest of it is shown.
Here is my code:
This one lists it:
<?php foreach($dataArray as $data) { ?>
<div class="visible">
<?php echo $data[0]; ?>
</div>
<div class="hidden">
<?php echo $data[1]; ?>
</div>
<?php } ?>
This is my jQuery:
$('.hidden').css('display', 'none');
$('.visible').click(function () {
$('.hidden').css('display', 'inline');
});
This page('tortenetek.php') is ajaxed to the main page ('blog.php'). I included Jquery in blog.php like this:
<link href='http://fonts.googleapis.com/css?family=Niconne&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="../css/stilus.css"/>
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../js/tinybox.js"></script>
<script type="text/javascript" src="../js/ajax.js"></script>
<link href="../css/lightbox.css" rel="stylesheet" />
<script src="../js/lightbox.js"></script>
<script src="../js/story.js"></script>
Story.js is the script file i'm using.
Thanks folks!
Use .on method to attach event to dynamically added elements.
Change it to
$('.visible').on('click',function () {
$('.hidden').css('display', 'inline');
});

Saving Changes in SlickGrid with php

I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:
Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');
$data = '';
$i = 0;
$query = "
SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$data .= '
data['.$i.'] = {
id: "'.$row['id'].'",
title: "'.$row['title'].'",
duration: "'.$row['duration'].'",
percentComplete: "'.$row['percentComplete'].'",
start: "'.$row['start'].'",
finish: "'.$row['finish'].'",
effortDriven: "'.$row['effortDriven'].'"
};
';
$i++;
echo $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<?php // include("includes/cms_head_scripts.php"); ?>
<link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" src="js/jquery.json.js"></script>
</head>
<body>
<div id="content_cont">
<div id="main">
<div style="position:relative">
<div style="width:600px;">
<div id="myGrid" style="width:100%;height:500px;"></div>
</div>
</div>
pricing
</div><!-- #main -->
</div><!-- #content_cont -->
<script src="lib/firebugx.js"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js"></script>
<script src="lib/jquery.event.drag-2.0.min.js"></script>
<script src="slick.core.js"></script>
<script src="plugins/slick.cellrangeselector.js"></script>
<script src="plugins/slick.cellselectionmodel.js"></script>
<script src="slick.editors.js"></script>
<script src="slick.grid.js"></script>
<script type="text/javascript">
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title", editor:TextCellEditor},
{id:"duration", name:"Duration", field:"duration", editor:TextCellEditor},
{id:"%", name:"% Complete", field:"percentComplete", editor:TextCellEditor},
{id:"start", name:"Start", field:"start", editor:TextCellEditor},
{id:"finish", name:"Finish", field:"finish", editor:TextCellEditor},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven", editor:TextCellEditor}
];
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true
};
$(function() {
<?php echo $data ?>
grid = new Slick.Grid($("#myGrid"), data, columns, options);
})
</script>
<form method="POST" action="save_price.php">
<input type="submit" value="Save">
<input type="hidden" name="data" value="">
</form>
<script type="text/javascript">
$(function() {
$("form").submit(
function() {
$("input[name='data']").val($.JSON.encode(data));
}
);
});
</script>
</body>
</html>

Categories