How do I delete multiple MySQL entries via check boxes? - php

In my application I display the database contents in a table. For each row displayed, I add a check box to the end of the row:
echo '<td><input type="checkbox" name="ticked[]"></td>';
When the user has checked off however many boxes they wish to delete the entries for, they click this delete button (front end is zurb foundation framework):
Delete URL
When this button is pressed the deleteUrl ajax function is triggered:
function deleteUrl(str)
{
document.getElementById("content01").innerHTML="";
if (str=="")
{
document.getElementById("content01").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("content01").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","deleteUrl.php?deleteUrl="+str,true);
xmlhttp.send();
document.getElementById("content02").innerHTML = 'Your URL was successfully deleted!<br/><br/>';
xmlhttp.onreadystatechange = urlRefresh;
return;
}
The ajax function directs the process to my deleteUrl.php file:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<?php
$deleteUrl = $_GET ['$deleteUrl'];
if(isset($_GET['delete'])) {
if(is_array($_GET['url'])) {
foreach($_GET['url'] as $id) {
$query = "DELETE FROM contact WHERE url=". $url;
mysql_query($query)or die(mysql_error());
}
}
}
mysql_close();
?>
So far the process runs through, without error. However, the entries that are checked are not deleted during the process.
QUESTION: What do I need to do to make the delete process work using check boxes?
EDITED CODE:
function runDelete(str, id)
xmlhttp.open("GET","deleteUrl.php?deleteUrl="+str+"&ticked="+id,true);
Delete URL
echo '<td><input type="checkbox" name="ticked[]" value="'.$row['id'].'"></td>';

Can you please try this,
1 Step - Include jquery url in head tag
2 Step - include this code after jquery url,
<script type="text/javascript">
$(function(){
$("#deleteUrl").click(function(){
$('#content02').html('');
var tickedItems = $('input:checkbox[name="ticked[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "deleteUrl.php",
data: "ids=" + tickedItems,
success: function(msg) {
$('#content02').html('Your URL was successfully deleted!');
}
});
return false;
});
});
</script>
3 Step - Replace this code in deleteUrl.php,
<!--Include Database connections info-->
<?php include('config.php'); ?>
<?php
$deleteUrl = $_GET ['$deleteUrl'];
if(isset($_POST['ids'])) {
$idsArray = #explode(',', $_POST['ids']);
foreach($idsArray as $id) {
$query = "DELETE FROM contact WHERE url='".$id."' ";
mysql_query($query)or die(mysql_error());
}
}
mysql_close();
?>
4 Step - assign id/property row value into checkbox
<?php
echo '<td><input type="checkbox" name="ticked[]" value="'.$row['id'].'" ></td>';
?>
5 Step - Add this button for delete action
<button class="button radius expand" id="deleteUrl" name="deleteUrl" >Delete URL</button>

Corey, it's just suggestion not the exact answer of your query. you should try to make few correction in your code like the steps below.
very first you need to assign the value to checkbox like
echo '<td><input type="checkbox" name="ticked[]" value="'.$id.'"></td>';// $id it would different in your case
than pass the checkbox values through function call
onClick="deleteUrl('deleteUrl',checkboxvalue);
and modify function accordingly
function deleteUrl(str,checkboxvalue)
than pass the checkbox value to delete url
xmlhttp.open("GET","deleteUrl.php?deleteUrl="+str+"&ticked="+checkboxvalue,true);
than modify delete page to delete the records as per your checkboxvalue not the url and make sure that you are passing correct value from ajax and getting correct value on delete page.

Related

How to pass value of a selected row in a popup div(which contains php include another file) on click of a button?

I have a form in which all the contacts are listed with fields like first name last name etc. Every row has view edit delete anchor tags on which I am calling a popup div. This popup div contains the php include(external file). I want to access the selected rows unique database primary key in that external file.
The link of the code is
https://www.dropbox.com/s/88qpmkwmaepa5s4/New%20Text%20Document%20%283%29.txt
Any help is appreciated.
Thank you
As a simple example to call Ajax by javascript and send the clicked row id to the php file, check this
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//returned response from ajax to the php page will be in xmlhttp.responseText
alert(xmlhttp.responseText); // Do whatever you need with the respones
}
}
var selected_row = document.getElementById('selected_row').innerText; // we assume this is the value of the selected row
xmlhttp.open("GET","path_to_your_phpfile&row_id=" + encodeURIComponent(selected_row), true);
xmlhttp.send();
}
Now the selected row id is passed by GET and in your php file you can get by $row_id = $_GET['row_id'];
If you are using jQuery, you go for a quick kill with AJAX.
Javascript:
<script>
function show_div(id) {
function show_lightbox(){
// your code
}
$.ajax({
type: "POST",
url: "get_detail.php",
data: "id=" + id,
dataType: "html",
success: function(html){
$("#show_detail").html(html);
}
});
}
</script>
Html:
<div id="lightbox">
<div id="show_detail"></div>
</div>
In your anchors:
<a onClick="show_div(uniqe_primarykey)">Click to fetch details</a>
In get_details.php
<?php
$id = $_POST[id];
//your queries
?>
<html>
Data from queries
</html>

Filter by links and order by dropdowns on the same page with ajax and php

I'm new to this site, php and ajax. I've tried searching for the solution but can only find partial of it. Here's what I'm trying to do, I have a page with 2 links (Make, and Model) and 2 dropdowns (Sort By, and ASC/DESC). When user click on the Make link, the page with refresh and display all cars by Make (i.e. all Toyotas). If click on the Models, it will refresh the page showing all cars by Model (i.e. all Camrys). And if the user also click on the Sort By (i.e. Year), it needs to show either Make/Model and sort by year. And same goes with the ASC/DESC. I found some sample codes from this site to do the Sort By part, but don't know how to make the other drop down and links to work. Here's what i have so far... Please help!! Thanks!
inventory.php
<script type="text/javascript">
function changeContent(strOrderBy, strMake)
{
alert(strOrderBy + " " + strMake");
if (strOrderBy=="")
{
// if blank, we'll set our innerHTML to be blank.
document.getElementById("content").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
// create a new XML http Request that will go to our generator webpage.
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
// create an activeX object
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// on state change
xmlhttp.onreadystatechange=function()
{
// if we get a good response from the webpage, display the output
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
// use our XML HTTP Request object to send a get to our content php.
xmlhttp.open("GET","getinventory.php?orderby="+strOrderBy+"&make="+strMake, true);
xmlhttp.send();
}
</script>
<body>
<div class="colrecNav4">Sort By:
<select name="sort" id="sort" onchange="changeContent(this.value, ???)">
<option value="year">Year</option>
<option value="trim">Trim</option>
<option value="price">Price</option>
<option value="miles">Miles</option>
</select>
<select name="dir" id="dir" onchange="changeContent(this.value)">
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
</div>
<?php
//reading data from the database
echo '<div class="makemodel">' . $makeFromDb . '</div>';
echo '<div class="makemodel">' . $modelFromDb . '</div>';
?>
<script>
$(".makemodela").bind("click", function(event){
var div_id=$(this).attr("id");
$.ajax({
type:'POST',
url: 'getinventory.php',
success: function(data){
changeContent($('#sort').val(), div_id);
}
});
});
</script>
....
</body>
getinventory.php
<?php
...
$sql = "SELECT * FROM inventory ORDER BY " . $_REQUEST['orderby'];
$result = mysql_query($sql);
while (...) {
echo "results...."
}
?>
Experts: So i added another parameter to the changeContent function, updated the code, now I can see the values from the alert message in the changeContent function when I click on the Make or Model links. But I can only see it the first time. After that, it doesn't do anything. Could someone please help? Thanks!
EDIT:
So my inventory.php page after the sortby dropdown
<?php
$make_results = $db->get_results("SELECT * FROM tblmake ORDER BY Make");
foreach ($make_results as $make_result) {
echo '<div class="makemodel">' . $make_result->Make . '</div>
....
//similar for model link
?>
<script>
$(".makemodel a").bind("click", function(event){
var div_id=$(this).attr("id");
$.ajax({
type:'POST',
url: 'getinventory.php',
success: function(data){
changeContent($('#sort').val(), div_id);
}
});
});
</script>
and my getinventory.php page
$orderby = $_REQUEST['orderby'];
$make = $_REQUEST['make'];
$search_results = $db->get_results("SELECT qry WHERE MAKE=" . $make . " ORDER BY " . $orderby)
//display results
?>
At any onChange event, either sort by or sort column will be passed by your AJAX call. You need to pass both the parameters and on each change change, you need to check the value of other dropdown as well so that valid MySQL query can be built.
Like ORDER BY year DESC.
You can get the change of value from drop down using ".change" function in jquery and pass
that value to the your getinventory.php using ajax and create a html page in
getinventory.php as depend upon on the value and include that result after sucess
check the code below
$("#dir").change(function(){
var selectedValues = $("#sort").val();
$.post("http://localhost/getinventory.php/orderby/"+selectedValues,function(data){
$("#yourdiv").html(data); // Here data consits of the html page
});
});

Check if record exists in mySQL Database on blur

I am thinking on how to implement this scenario:
I have a table orders where there is a serialNumber field. Then I also a have a PHP page with a form. What I am thinking of doing is that, onBlur or on keypress enter/return of a <input type=text> field, I would like an ajax/jquery script to check the serial number from the text box input if it has an existing record in my mySQL database. Then the script will warn the user that the serial number exists already in the database and will not allow submission.
I know how to implement it with standard form submission but I was thinking is it can be done without the literal pressing of the submit button.
Is there a way to implement this?
for this you can use javascript. create on javascript that called on textbox on blur event.
here i created on function that called on textbox on blur event.
function CheckUserName(){
var UserName = document.getElementById('UserName');
if(UserName.value != "")
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var value = xmlhttp.responseText;
if(value.length > 1)
{
document.getElementById('ErrorSpan').innerHTML="User Name Already exist please choose Other User Name";
UserName.focus();
}
else
{
document.getElementById('ErrorSpan').innerHTML="";
}
}
}
xmlhttp.open("GET","checkUserName.php?q="+UserName.value,true);
xmlhttp.send();
}
}
and create one php file with the name checkusername.php and pass your value through query string.
php code as follow.
<?php
$q=$_GET["q"];
include("db_connect.php");
$sql="select * from usermaster where UserName='".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['UserName'];
}
mysql_close($con);
?>
here from php if username find it will return value and you can get value in your javascript function. i hope it will help you.
you can also use this method I checked it on keyup you can use it via onblur option.
<input type="text" value="" id="jform_domain_name" name="jform[domain_name]" onkeyup="checkAvailability();"/>
<div id="errormsg" class="no-display">Sorry, this name is not available!</div>
<div id="successmsg" class="no-display">Congratulations, this domain is available!</div>
<script>
function checkAvailability(){
jQuery('#ajaxloader').html('<img src="images/ajax-loader.gif" />');
var string = jQuery('#jform_domain_name').val();
if(string == ''){
jQuery('#ajaxloader').html('');
return false;
}
jQuery.ajax({
type : "POST"
,url : "YOUR_ACTION_URL"
,data :"string="+jQuery('#jform_domain_name').val()
,success : function(data){
if(data==0){
var errormsg = jQuery("#errormsg").html();
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html(errormsg);
}else{
var successmsg = jQuery("#successmsg").html();
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html(successmsg);
}
}
,complete : function(){
if( jQuery('#jform_domain_name').val() == "" ) {
jQuery("#ajaxloader").hide();
}
}
,beforeSend: function(html){
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html('<img style="padding-top:6px;" src="images/ajax-loader.gif" />');
return;
}
});
}
</script>
for reference I am providing my controller action and the model which I have used
//sample controller action
function checkdomain(){
$requestData = JRequest::get();
$return = $model->checkAvailabiLity($requestData['string']);
if($return === false){
echo 0;
}else{
echo 1;
}
die;
}
//sample model on which I created Query logic.
public function checkAvailabiLity($data){
$select = "SELECT id FROM #__jshopping_vendors WHERE domain_name = '".strtolower($data)."' AND user_id != ".$user->id."";
$db->setQuery($select);
$type = $db->loadObject();
if(isset($type->id) && $type->id >0){
return false;
}else{
return true;
}
}
hope this helps....

javascript validate form values from database

The below code is to create a campaign. Before creation, I have to validate the form. I have to validate the campaign name which is already existed in database or not. I don't know whether I can use PHP code inside javascript (like below).Anyway it's not working. How can I change my code? How can I validate values with database values?
$this->campaign is an array which contain all campaign details from database.
<script type="text/JavaScript">
function validate()
{
var name = document.getElementById('name').value;
var shape = document.getElementById('shape').value;
<?
foreach($this->campaign as $c)
{
$old_cname=$c['name'];
?>
if(name==<?=$old_cname;?>)
{
alert("same name exists in database. Try again!");
}
<?
}
?>
if(!name)
{
alert("Please enter a name!");
return false;
}
if(!shape)
{
alert("Please select shape!");
return false;
}
return true;
}
</script>
<form action="create.php" method="post" onsubmit="return(validate());">
Name:
<input type="text" name="name" id="name"/>
Shape:
<select name="shape" id="shape">
<option value="long">Long</option>
<option value="tall">Tall</option>
</select>
<input type="submit" value="Create" name="submit"/>
</form>
Thanks!
You can't mix php and javascript like that.. php is a server-side language, while javascript is client-side; php renders the page before the user sees it, while javascript modifies the page without refreshing. Any php values in your js will get rendered and output before the js even executes.
In order to do what you need, you need to use ajax, which is asynchronous javascript and xml, a method of client-server communication that allows for what you want to happen.
To do this, I would suggest jQuery, a javascript library which makes such requests very simple. As an example of how you would make such a request in jquery....
The jQuery.ajax() method:
$.ajax({
url: "validate.php",
type: "POST",
data: "username=" + username,
sucesss: function(data) {
if (data == 1)
$("#ajax_div").html("Username is taken, choose another!");
}
else {
$("#ajax_div").html("Username is free :)");
}
}
});
That would be how to do it in ajax, while your php file would either return a 1 or a 0 depending on the result of an sql query comparing usernames in the database.
To do this without jquery, it would be something like this:
function checkUsername() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == 1) {
document.getElementById('ajax_div').innerHTML = "Username is taken, please choose another!";
}
else {
document.getElementById('ajax_div').innerHTML = "Username is free :)";
}
}
}
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username=" + username);
}
}
You should use jquery to validate using a php script. The best way to do this is to disable the submit button until all fields are verified. This requires that you to listen to keystrokes then make a jquery call to validate the input field. A simple example below
script.js
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#myInput').keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#myInput').keydown(function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
$.ajax({
type: "POST",
url: 'ajax/validate.php',
data: 'cname='+$('#name').val(),
success: function(data) {
if(data == "original"))
//enable the submit button
else
//Update your div that contains the results
}
});
}
ajax/validate.php
<?PHP
//Run your validations here
?>

AJAX Help needed

I've recently stumbled upon a small issue. Basically I'm trying to give my users the ability to search thru a certain category on my site, but the search is done via AJAX and will not reload the page, simply the content that is being searched through.
The following codes is what I came up with so far, but the only time where it will change something is when there will be no value in the textbox, other than that the content isnt being updated (I checked the PHP file manually and there is no erros & with HTTP Direct addon for Firefox I made sure the call to my php file is made)
My code:
category.php:
<script type="text/javascript">
function showCat(str, cat)
{
if (str=="")
{
document.getElementById("showCategory").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showCategory").innerHTML=xmlhttp.responseText;
}
}
url="../cat_search.php?q="+str+"&cat="+cat
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
<input type="text" name="showCat" onkeyup="showCat(this.value, <?=$id?>)" style="width: 140px;" />
<div id="showCategory">
## Stuff is being listed here on the load of the page & then should be updated with Ajax
</div>
cat_search.php:
<?php
include("config.php");
include("global.php");
$q=$_GET["q"];
$cat=$_GET["cat"];
$search = $q;
$q = "%".$q."%";
$sql="SELECT * FROM games WHERE title like '$q' AND category = '$cat'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 0) {
echo "<center><div class=\"redbox\" style=\"width: 110px;\">No match</div></center>";
}
while($row = mysql_fetch_array($result)) {
echo '......';
} ?>
The $id is the actual category ID.
Let me know if you would have the slighest idea of what my problem could be, I use almost the same exact code for another type of search and it works like a charm.
Thanks you!
Use jQuery for AJAX. Seriously. It's very simple and painfulless. And WTH is that?
$q=$_GET["q"];
$search = $q;
$q = "%".$q."%";
Why not just?
$q = '%'.$_GET['q'].'%';
And, for example, a code in jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('input[name=showCat]').keyup(function(){
showCat($(this).val(),$(this).attr('id'));
});
});
function showCat(str,cat) {
if (str == '') {
$('#showCategory').html('');
return;
} else {
$.get('../cat_search.php',{q:str,cat:cat},function(data){
$('#showCategory').html(data);
});
}
}
</script>
<input type="text" name="showCat" id="<?=$id?>" style="width: 140px;" />
<div id="showCategory">
## Stuff is being listed here on the load of the page & then should be updated with Ajax
</div>

Categories