How to update db instantly based on checkbox using php and jquery - php

jquery:
$("input[name='flag']").on('change', function() {
event.preventDefault();
var tablerow = $(this).closest('tr');
var id = $(this).attr('id');
var flagvalue;
if($(this).prop('checked') == true) {
tablerow.css({'background-color':'rgba(175,0,0,0.2)'});
flagvalue = 1;
}
else {
tablerow.css({'background-color':'rgba(175,0,0,0)'});
flagvalue = 0;
}
alert(flagvalue);
$.ajax({
url: "../php/insert.php",
method: "get",
data: {"flagvalue":flagvalue,"id":id},
dataType: "text"
success:function(data)
{
$('#ohmygod').html(data); //it doesnt echo anything from here :(
}
});
});
php:
$insertMessage = "";
$bendera = filter_input(INPUT_POST, 'flagvalue', FILTER_SANITIZE_SPECIAL_CHARS);
$id = $_POST['id'];
if(!empty($bendera)) { //also doesn't work if change it to isset
$insertMessage = "Reached the php part";
$updateflag = "UPDATE sintok SET flag='$bendera' WHERE id='$id'";
mysqli_query($connection, $updateflag);
}
echo $insertMessage;
html:
<div id="ohmygod"></div>
include another php into html file:
<input value='.$row['id'].' type=checkbox name=flag id=flag '.$tick.'>
I have one checkbox which consist of two values, 0(unchecked) and 1(checked). From above code I don't see any changes except for the background-color of the row once the user has checked the checkbox button. But it didnt update the database.
My question is, what is the correct syntax to update the data instantly from checkbox selection.

Related

load json data from database into slideToggle

I'm trying to load applicants info that i get from database (fisrt name, lasta name, ID number) in a slidetoggle that appears after clicking "Display applicants" button.
My code keeps showing ERROR DETECTED message, after I click the button "display applicants" an slidetoggle should appear and the json data be shown on the slide. can someone give me some directions about what i'm doing wrong here.
Query:
if(isset($_GET['id'])){
$id_oferta = $_GET['id'];
$sql ="SELECT postulacion.* FROM postulacion WHERE id_oferta = '". $id_oferta ."'";
$listapostulantes = mysql_query($sql) or die(mysql_error());
$return_arr= array();
$num = mysql_num_rows($listapostulantes);
if($num > 0){
while($row = mysql_fetch_array($listapostulantes, MYSQL_ASSOC)){
$return_arr[] = $row;
}
echo json_encode($return_arr);
}
}
Script:
$(document).ready(function(){
$('.myslide').hide();
$(".postulantes").on('click', function(e){
e.preventDefault();
if($(this).parent().next().css('display') == 'none'){
$('.myslide').hide('fast');
$(this).parent().next().slideToggle('slow');
var link = $(this).attr('href').split('&');
var idd= link[1].match(/id=([0-9]+)/)[1];
$.ajax({
url: link[0],
type: 'GET',
dataType:'json',
data:{'id': idd},
success:function(data){
// console.log();
var htmlStr = '';
$.each(data, function(key, value){
htmlStr += '<p>' + value.rut_usuario + '</p>';
});
$(".myslide").html(htmlStr);
},
error: function(){
$("#listaofertas").html("ERROR DETECTED");
//console.log();
}
});
}
});
});
json
Your response, as shown under the Respuesta tab, includes not only JSON, but some HTML as well. Get rid of the html, and make sure only JSON is returned, and then jquery should execute your success callback
Use this to split the response and "cut out" the html part.
$splitted = explode("<!DOCTYPE HTML>",json_encode($return_arr));
echo $splitted[0];

Trigger combo box events using jquery

I have this code:
$show_location = mysql_query("SELECT * FROM location ORDER BY location_code");
while($row_location = mysql_fetch_array($show_location))
{
$location_code = $row_location['location_code'];
$show_store = mysql_query("SELECT * FROM store_list WHERE location LIKE '%$location_code%'");
$count_store = mysql_num_rows($show_store);
while($row_store = mysql_fetch_array($show_store))
{
$store_name = $row_store['store_name'];
}
if($count_store==0)
{
$status = "Inactive";
echo '<option value="'.$location_code.'">'.$location_code.'</option>';
$sql1 = "SELECT description FROM location WHERE location_code=$location_code";
$result1 = mysql_query("$sql1");
$row1 = mysql_fetch_assoc($result1);
$description=$row1['description'];
}
else
{
$status = "Active";
}
//echo '<option value="'.$location_code.'">'.$location_code.'</option>';
}
What I want to do is to display the $description somewhere in the form. I have the kind of combobox where you can select as many as you can. I want to display each $description once a location is selected. But I dont know where to put the trigger. Can sombody help me? Thanks!
correct me if i am wrong, but will every location_code have one description right?
well there are two ways:
1) Easy but not so efficient way
Make an ajax call for every selected value.
$("#myDropDown").change(function (event) {
//alert("You have Selected :: "+$(this).val());
$.ajax({
type: "POST",
url: "ajax.php",
data: { type: "1", location: $(this).val() }
}).done(function( msg ) {
("#mydata").html(msg)
});
});
You can check for type == 1 on php side, get the description and print it
The above method will cause a ajax request for every selection
2) A bit complex, but efficient
First of all json_encode your location_code and description. It will become something like {code:"AU", description:"blah blah"}
Then use something like this
$("#sel").change(function(e){
//alert($(this).val());
var array = $(this).val();
for(key in array){
var json = JSON.parse(array[key]);
$("#desiptions").html(json.description);
}
});

jQuery.ajax File Delete

I have a jquery delete statement and it's only deleting the NEWEST upload on my files (using mysql) Say I had "file uploaded first", "file uploaded second", "file uploaded last(newest file)". If I click "file uploaded first or second", it deletes the newest (file uploaded third).
$(document).on('click', '.del', function(){
var sid = $(this).next('.hiddenVid').val();
$.ajax({
type: "GET",
url: "delete.php",
data: {id:sid}
});
return false;
});
this is your error ->
var sid = "$vid";.
It will only produce the ID for the latest item that you put in.
Add an item to your echo statement so you can reference it later in the click function.
Add a reference to the vid in a hidden input.
Change this
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button></form></td>";
To this:
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button><input type='hidden' class='hiddenVid' value='".$vid."'/></td>";
Change your click function to reference the real sid now.
$(function(){
$(".del").click(function(){
var row = $(this).parent();
var sid = $(this).next('.hiddenVid').val();
alert(sid);
$.ajax({
type: "GET",
url: "delete.php",
data: {id:sid}
});
return false;
});
});
If you want to return the rows after the update, you'll need to spit the data back to be printed, based on the above method you use to retrieve the rows and return them, you could reuse it.
$id = mysql_real_escape_string($_REQUEST['id']);
$DB->Query("DELETE FROM `files` WHERE `id`='$id'");
if(TRUE == (unlink("uploads/$id")):
$DB->Query("SELECT * FROM `files` WHERE `author`='$username'");
$file = $DB->Get();
$obj = new stdClass();
$i = 0;
foreach($file as $key => $value){
$n = $value['name'];
$vid = $value['id'];
$date = "<td>".$value['date']."</td>";
$fname = "<td><a id='$vid' href='download.php?id=$vid'>$n</a></td>";
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button></form></td>";
$size = "<td>".filesize("uploads/".$vid."/".$value['name'])." bytes</td>";
$obj->$i = $files = "<tr>".$fname.$size.$date.$option."</tr>";
$i++;
}
echo json_encode($obj);
endif;
Now we need to change the click handler to expect a dataType and replace the existing data in the table.
$(function(){
$(".del").click(function(){
var row = $(this).parent();
var sid = $(this).next('.hiddenVid').val();
alert(sid);
$.ajax({
type: "GET",
url: "delete.php",
dataType: 'json',
data: {id:sid},
success: function(data){
$('table').empty();
$.each(data, function(i,obj){
$('table').append(obj);
}
}
});
return false;
});
});

ajax json response array using in php

I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />​​​​​​​​​​​​​​​​​
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories