I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)
Related
i have a ajax and php as follows but it is not changing the value of html attribute with id #respo
is there any modification require?
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
dataType: "json",
data: {reccount: reccount},
success: function(response) {
var response = ($response);
$("#respo").text(response);
},
})
and php as
<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT response from paper WHERE ID=$id";
$result=mysqli_query($link, $sql);
while ($row = mysql_fetch_row($result)) {
$response => $row['response'];
}
echo json_encode($response);
// Close connection
mysqli_close($link);
?>
i want to assign a value of response to html element with id respo
Your code must look like
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
success:function(data){
var obj = jQuery.parseJSON(data);
document.getElementById('elementName').value = obj.varaibleName;
}
});
I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});
I thought this will be very simple but i think there is a bug when posting a variable from .ajax to a query. Is there any other way I ca get my result?
here is my jquery:
jQuery_1_4_2(document).ready(function()
{
jQuery_1_4_2('.mainfolder').live("click",function()
{
event.preventDefault();
var ID = jQuery_1_4_2(this).attr("id");
var dataString = 'folder_id='+ ID;
if(ID=='')
{
alert("Serious Error Occured");
}
else
{
jQuery_1_4_2.ajax({
type: "POST",
url: "display_folder.php",
data: dataString,
cache: false,
success: function(html){
jQuery_1_4_2(".right_file").prepend(html);
}
});
}
});
});
here is my display_folder.php
<?php
$folder_id = $_POST['folder_id'];
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
Can anybody explain why this not work? i tried to echo $folder_id and it is working, but when you put it inside the query it is not working.
Note: This is not a dumb question where i forgot my connection of db. Thanks
I agree with both you and here I am providing (just for clean display) the same with some little formatting.
var dataString = 'folder_id=1';
$.ajax({
url: "folder.php",
type:'post',
async: false,
data:dataString,
success: function(data){
alert(data);
}
});
and php part where I am getting folder_id properly.
<?php
$postid = $_POST['folder_id'];
//echo $postid;
$link = mysql_connect("localhost","root","");
mysql_select_db("test", $link);
$query = mysql_query("select * from post where id='$postid'");
while($row=mysql_fetch_array($query))
{
echo $row['text'] . "<br>"; //a, b etc in each row
}
?>
So it should work.
Try this in your php code
<?php
$folder_id = addslashes($_POST['folder_id']);
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.
I would like to ask, is there a better way to run this code. I have a form with a select of #BA_customer which when selected populates a second menu with the address of the selected client. I also need to display a dept dropdown based on the customer selecetion. I think the code I have is causing a conflict where the customer is being passed twice in 2 seperate statements. What is the correct way to do this? Many thanks
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data); });
});
});
</script>
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data); });
});
});
</script>
+++++++ dept.php Code +++++++++++++++++++++
$customer = mysql_real_escape_string( $_GET["BA_customer"] ); // not used here, it's the customer choosen
$con = mysql_connect("localhost","root","");
$db = "sample";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query_rs_select_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_select_dept = mysql_query($query_rs_select_dept, $con) or die(mysql_error());
$row_rs_select_dept = mysql_fetch_assoc($rs_select_dept);
$totalRows_rs_select_dept = mysql_num_rows($rs_select_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_select_dept = mysql_fetch_assoc($rs_select_dept))
{
$dept=$row_rs_select_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
++++ SOLUTION +++++++++++++
mysql_select_db($db, $con);
$query_rs_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_dept = mysql_query($query_rs_dept, $con) or die(mysql_error());
$totalRows_rs_dept = mysql_num_rows($rs_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_dept = mysql_fetch_assoc($rs_dept))
{
$dept=$row_rs_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
Remove the first $row_rs_select_dept = mysql_fetch_assoc($rs_select_dept); from the script and it works. Just posted solution in case some other soul needs help with problem like this.
Maybe you could send the two requests together?
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data);
});
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data);
});
});
});