I want to update a field in db as 1 or 0 when i click on yes or no button..
<td> <input type="button" onClick="save();" value="Yes">
<input type="button" onClick="save();" value="No">
</td>
This code displays the button in view page as yes and no. Now what should i do to save in db while clicking on yes button?
<div class="bit-4 pad-small" style="float:none;">
<br>
<br>
<?php echo $this->Form->input('approve', array(
'type'=>'checkbox',
'style' => 'float:left;',)
) ); ?>
<span>required</span>
</div>
in your cakephp file you can get the value and update it to database. Hope you can get any way to update it now. Even you can do that in save() method.
/please change input to any unique selecter give any id or class to button/
$("input").click(function(){
var val = $(this).val();
$.ajax({url: "path_to_your_cake_php_file.php",
type: 'post', // performing a POST request
data : {
inputValue : val // will be accessible in $_POST['inputValue']
},
dataType: 'json',
success: function(result){
alert('value has been updated');
}});
})
onclick function should have parameter that indicates which answer was submitted.
function save(id)
{
var id = id;
switch(id)
{
case 1:
var buttonValue = "Yes";
break;
case 2:
var buttonValue = "No";
break;
}
var formData = new FormData();
formData.append("ButtonValue", buttonValue);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var array = xmlHttp.responseText;
//in array you store results echoed from php script
}
}
xmlHttp.open("POST", "file.php");
xmlHttp.send(formData);
}
file.php
<?php
$buttonValue = $_POST["ButtonValue"];
$con = mysqli_connect("host", "name", "pass", "db");
$res = mysqli_query($con, "Insert goes here");
mysqli_close($con);
?>
PS Consider that pure JavaScript is nearly 30 times faster than JQuery
Use jQuery and jquery-ajax for this.
HTML:
<td> <input type="button" onClick="save(this);" value="Yes">
<input type="button" onClick="save(this);" value="No">
</td>
JS:
function save(elem){
val = $(elem).val() == 'Yes' ? 1 : 0;
$.ajax({
type: "POST",
url: Your_php_file_path,
data: {button: val },
success: function(data){
//added
},
dataType: json
});
}
In the server side you can get submitted value by $_REQUEST['button']
Related
I'm trying to detect which was button was pressed with jQuery and then server-side do different things depending on the outcome.
The jQuery works fine (although I may have gone about it in a long- handed way) but I can't figure out why in my code whichever button I press I get the same response from php: "Add button detected". I hope someone can tell me what I've got wrong?
The jQuery
$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
The Php
<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity
if($btn="btn_add"){
echo "<h1>Add button detected</h1>";
//Do stuff
}
elseif($btn="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
The html Form
<td>
<form id=\ "myForm\" class=\ "myForm\" action=\ "\" method=\ "post\" enctype=\ "multipart/form-data\">
<input type=\ "hidden\" name=\ "user_id\" value=". $collab_userid." />
<input type=\ "hidden\" name=\ "id\" value=".$upload_id." />
<button type=\ "submit\" id=\ "btn_remove\" class=\ "btn_remove\" name=\ "btn_remove\">Remove</button>
<button type=\ "submit\" id=\ "btn_add\" class=\ "btn_add\" name=\ "btn_add\">Approve</button>
</form>
</td>
You should add the pressed button to your formdata, otherwise the click couldn't be detected.
$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_add"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_remove"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
Change php code as follows
<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity
if ($btn=="btn_add") {
echo "<h1>Add button detected</h1>";
//Do stuff
} elseif ($btn=="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
You need not have two separate function for jquery button handling. Also you can remove the button type="submit" from your code since you are detecting the click event
$(document).ready(function() {
$("button").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
console.log(url);
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
<form id="myForm" class="myForm" action="\" method= "post" enctype="multipart/form-data">
<input type="hidden" name="user_id" value=". $collab_userid." />
<input type="hidden" name="id" value=".$upload_id." />
<button type="submit" id="btn_remove" class="btn_remove" name= "btn_remove">Remove</button>
<button id="btn_add" class= "btn_add" name="btn_add">Approve</button>
</form>
</td>
You can use the parse_url() and parse_str() for getting the query string in php. In order to use $btn=$_POST["btn"]; tbn attribute must be passed as a form data, query parameters wont will be available through this method
<?php
$parts = parse_url($url);
parse_str($parts['query'], $query);
$btn = $query['btn'];
if($btn=="btn_add"){
echo "<h1>Add button detected</h1>";
//Do stuff
}
elseif($btn=="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
Your code works just make var url = process_ajax4.php that will fix your problem.in PHP use == instead of =, also add e.preventDefault() to your button clicks to prevent the form from being submitted with action='url'
$(document).ready(function() {
$(".btn_add").on("click", function(e) { //If add btn pressed
e.preventDefault();
var id = this.id;
var url = "process_ajax4.php";
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_add"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function(e) { //If remove btn pressed
e.preventDefault();
var id = this.id;
var url = "process_ajax4.php";
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_remove"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
i think your code looks ok.
i think in php you cannot compare string by =
you may need to change it to strcmp(strA,strB)==0 in order to ensure the input parameter is add button or remove button.
You don't actually need the jQuery code at all. Since both btn_remove and btn_add are submit buttons, you can check which of the buttons where used to submit the form by using:
if(isset($_POST["btn_remove"])) {
//Remove button was pressed.
}
i am newbie in jquery and ajax programming. I have searched the answer about getting value from checkbox and pass it to PHP Page with AJAX, but it didn't work for me. Maybe someone can help me to get value from checkbox and pass to PHP Page so i can insert it to database.
This is my checkbox code in HTML
<fieldset data-role="controlgroup" id="pilihtambahan" style="margin-top: 5px;">
</fieldset>
$.ajax({
url: host+'/skripsi3/phpmobile/kategori.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
$("#pilihkategori").append('<input type="radio" name="radiokategori" class="required" id="'+item.kategori+'" value="'+item.kategori+'" required><label for="'+item.kategori+'">'+item.kategori+'</label>').trigger("create");
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
and this my html code to pass checkbox and other value to PHP Page
$("#simpansewa").click(function() {
var checkValues = $('input[name=cektambah]:checked').map(function()
{
return $(this).val();
}).get();
var k = $("input[name=radiokategori]:checked").val();
var u = user;
var g = getacara;
var b = $('#brandorder').val();
var d = $('#deskorder').val();
var s = $('#sosmedorder').val();
var t = $('#tambahcat').val();
dt = {user:u,acara:g,brand:b,desk:d,sosmed:s,kat:k,tambah:t,barangsewa:checkValues};
$.ajax({
type: "GET",
url: host+'/skripsi3/phpmobile/preorder.php',
data: dt,
success: function (data){
alert('Data Pemesanan Anda Telah Masuk');
window.location="statustransaksi.html";
},
error: function (e) {
alert('Fail');
}
});
});
this is my preorder.php
<?php
session_start();
include "config.php";
$idtenant = $_GET["user"];
$idacara = $_GET["acara"];
$namabrand = $_GET["brand"];
$deskbrand = $_GET["desk"];
$sosmed = $_GET["sosmed"];
$tambahcat = $_GET["tambah"];
$kategori = $_GET["kat"];
date_default_timezone_set('Asia/Jakarta');
$tanggal = date("d M Y G:i");
$statusbayar = "belumbayar";
$sewa=$_GET['barangsewa'];
$query="INSERT INTO `preorder`(`namaorder`, `sosorder`, `deskorder`, `catatan`, `kategori`, `id_tenant`, `id_acara`, `statuspesanan`, `tanggal`,`statusbayar`,`tambahanbarang`) VALUES ('$namabrand','$sosmed','$deskbrand','$tambahcat','$kategori','$idtenant','$idacara','Waiting','$tanggal','$statusbayar','$sewa')";
$result = mysql_query($query);
?>
Have a nice day!!
create one form and passed it with the use of jQuery serialize() function. This function is get all the data related with the form.
HTML Code
<form id="test">
<input type="radio" class="required" id="item1" name="item" value="1"> One
<input type="radio" class="required" id="item2" name="item" value="2"> Two
<button type="button" id="btn" > Click Me </button>
</button>
</button>
</form>
Javascript
$('#btn').click(function(){
var data = $( "#test" ).serialize()
});
All the data of the test form is assigned to the data variable. Now you can able to pass data variable to the php page with the ajax.
I have list with several inputs
<input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" />
<input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" />
<?php
if ($extraanpassning_hamta['atgard'] == true){
?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-red btn-sm" value="Ja">
<?php } else { ?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-green btn-sm" value="Nej">
<?php } ?>
The main problem is how to "catch" the value in the two latest inputs with:
id="knapp[<?php echo $amnets_id['amne_id']; ?>]"
If knapp[4] -> how do I get the 4?
The code above is a part of a button that changes value when the user presses it (without refreshing the page).
The JS
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var extraanpassningVal = $(this).attr("value");
var amne_id_ea = $(this).attr("id");
var elevens_id_ea = $("#elevens_id_ea").val(); //värdet av elev_id
var arskursen_ea = $("#arskursen_ea").val(); //värdet av elev_id
$.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
});
});
</script>
EDIT:
The main problem is how to get the key from a input with an id like knapp[4].
How do get the key within knapp[]?
Update (thanks to user:SpYk3HH)
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajax) this.ajax.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajax = $.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
})
});
</script>
I think I get it? You want the key when calling the button in JS? So like say: key = this.id.replace(/knapp|\[|\]/g, '')
Update, I didn't see the brackets before
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajx) this.ajx.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajx = $.ajax({/* options */});
})
Does that help?
FYI, $(this).attr("id") and this.id are the same thing
$('[name=test]').each(function(i) { $('#bob').text(this.id.replace(/knapp|\[|\]/g, '')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="knapp4" name="test" value='my id is "knapp[4]"' />
<hr />
key: <span id="bob"></span>
Try this.
var amne_id_ea = "knapp[4]",
value = amne_id_ea.substring(amne_id_ea.lastIndexOf("[")+1,amne_id_ea.lastIndexOf("]"));
alert(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hope you are expecting this.
I have two different buttons in my page. clicking on the first one must call a php file named derive_rules.php while cliking on the second one must call another file named derive_rules1.php using ajax. For same i tried following code. But it is not working,
<script>
$(document).ready(function() {
$(".deriver").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules.php',
data: 'kw='+val+'&agent='+agent,
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
if(data.success == 'true') {
$("#results_holder").show();
$("#results").html(data.msg);
$("#keyword").val('');
}
else {
alert(data.msg);
}
}
});
}
});
});
</script>
and those are mu buttons
<td><b>+ New Rule</b></td>
<td><input type = "text" name = "Keyword" id = "keyword" style = "width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type = "button" value = "Verify" class = "Buttons deriver" rel = "<?php echo $_GET['id']; ?>"/></td>
<td><input type = "button" value = "Add" class = "Buttons deriver" rel = "<?php echo $_GET['id']; ?>"/></td>
</tr></table>
what changes should i apply on my code to make it work???? as i want
Here is the quick solution.
HTML
<button class="same" data="derive_rules">Button One</button>
<br/>
<button class="same" data="derive_rules1">Button Two</button>
jQuery
$(".same").click(function(){
var url = $(this).attr("data");
//alert(url);
$.ajax ({
url: url+".php",//pass the url here or you can use whatever I used .php. And do the other stuff etc.
});
});
For more go to my JSFILLDE
If you need my help. Please find me any of social network by searching yeshansachithak.
Here Is Your Code - As You Want - For more explain
<table>
<tr>
<td><b>+ New Rule</b></td>
<td><input type="text" name="Keyword" id="keyword" style="width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type="button" data="your_file_name" value="Verify" class="Buttons deriver" rel="<?php echo $_GET['id']; ?>"/></td>
<td><input type="button" data="your_file_name" value="Add" class="Buttons deriver" rel="<?php echo $_GET['id']; ?>"/></td>
</tr>
</table>
Just pass another attribute in your <button data="your_file_name" ...... Then use your ajax call as like you did. Your button class is driver. Please see below.
<script>
$(document).ready(function() {
$(".deriver").click(function() {
//Edit by Yesh
var url = $(this).attr("data");
//To check
alert(url);
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
//url: 'derive_rules.php', //Edit by Yesh
url: url+'.php',//You can use whatever extension (.html ect..)
data: 'kw='+val+'&agent='+agent,
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
if(data.success == 'true') {
$("#results_holder").show();
$("#results").html(data.msg);
$("#keyword").val('');
}
else {
alert(data.msg);
}
}
});
}
});
});
</script>
Thanks dude.
If you need my help. Please find me any of social network by searching yeshansachithak.
look at classes on button , need to change selector
$(document).ready(function() {
$(".deriver0").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules.php',
data: {kw:val,agent:agent},
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
alert(data);
}
});
}
});
$(".deriver1").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules1.php',
data: {kw:val,agent:agent},
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
alert(data);
}
});
}
});
});
</script>
<td><b>+ New Rule</b></td>
<td><input type = "text" name = "Keyword" id = "keyword" style = "width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type = "button" value = "Verify" class = "Buttons deriver deriver0" rel = "<?php echo $_GET['id']; ?>"/></td>
<td><input type = "button" value = "Add" class = "Buttons deriver deriver1" rel = "<?php echo $_GET['id']; ?>"/></td>
</tr></table>
I can't figure it out how I can update the database with this textarea. Can somebody help?
The ajaxcall
$$('.btn').addEvent('click', function() {
var request = new Request( {
url: '<?php echo $baselink;?>',
method: 'post',
onSuccess:function(responseText) { alert(responseText);},
data: {
'name' : this.id,
'value' : this.value,
'tmpl':'component',
'format':'raw',
'ajax' : 1
}
}).send();});
**//Form//**
$s6=$item['Select6'];
$id=$item['items_id'];
print '<form method="post" class="formulier">
<input maxlength="250" NAME="name" class="name" id="'.$id.'" value="'.$s6.'" SIZE="50">
<input type="submit" value="Click me" class="btn"/></form>';
Query
if(JRequest::getVar('ajax') ) {
$state=JRequest::getInt('value','oeps');
$id=JRequest::getVar('name','');
if ( $id ) {
$state=(int)$state;
$query="UPDATE #__dataitems set `Select6`='".$state."' where `items_id`=".$id;
$db->query();
echo ' Bijgwerkt naar '.$state.' '.$id;
exit;}
You are currently listening on the radio button click and send the event when it does.
You need to add a button/href to your form and bind an click event to it, and then once it is clicked, just collect the data from the radio button and the textarea and send it:
HTML:
<input type="button" value="Click me" class="btn"/>
JS:
$$('.btn').addEvent('click', function(){
var radioId = ...//get radio id
var radioVal = ...//get val
var textarea = ... //get textarea val
var request = new Request( {
url: '<?php echo $baselink;?>',
method: 'post',
onSuccess:function(responseText) { alert(responseText);},
data: {
'volgorde' : radioId,
'check' : radioVal,
'textarea' : textarea ,
'tmpl':'component',
'format':'raw',
'ajax' : 1
}
}).send();});
I'm guessing you are using prototypejs (because of the $$), i don't know it very well so i can't help you with how to get the elements id and values, but this is the direction.