How can I display the value using ajax - php

Hi. I need help with this section of code.
What I want to do is; when I click (for example) a radio button 1, that button value display on the browser. I have a three radio buttons.
Here's my ajax query:
function updatepayment(this.value)()
var ajaxResponse = new Object();
$(document).ready(function () {
$('.rmr').click(function () {
var rbVal = $(this).val();
var myContent;
if (ajaxResponse[rbVal]) { //in cache
myContent = ajaxResponse[rbVal];
$("#contentcontainer").html(myContent);
}
else { // not in cache
var urlForAjaxCall = "include/function.php" + rbVal + ".html";
$.post(urlForAjaxCall, function (myContent) {
ajaxResponse[rbVal] = myContent;
$("#contentcontainer").html(myContent);
});
}
});
});

Your cache check will always be false since you always re-declare ajaxResponse in the function. ajaxResponse should be declared globally.
And you dont really need the post function (as your not posting any data) you could just use the .load function.
You dont need a function to wrap the $(document).ready function
var ajaxResponse = new Object();
$(document).ready(function(){
$('.rmr').click(function (){
var rbVal = $(this).val();
var myContent;
if (ajaxResponse[rbVal])
{ //in cache
$("#contentcontainer").html( ajaxResponse[rbVal] );
}
else
{ // not in cache
var urlForAjaxCall = "include/function.php" + rbVal + ".html";
$("#contentcontainer").load(urlForAjaxCall, function (myContent)
{
//Extra processing can be done here, like your cache
ajaxResponse[rbVal] = myContent;
});
}
});
});
EDIT:
After seeing your comments on your OP
You are trying to select the radio buttons by class name "rmr" but do not have it set on the tags
you need:
<input class="rmr" type="radio" name="rmr" id="payment1" value="3" onclick="updatepayment(this.value)" /> <br>
<input class="rmr" type="radio" name="rmr" id="payment2" value="5.5" onclick="updatepayment(this.value)" /><br>
<input class="rmr" type="radio" name="rmr" id="payment4" value="10" onclick="updatepayment(this.value)" /><br>
or you could use
$("input[name=rmr]")
to select them by their input name attribute

Related

Checkbox not returning the right value jquery/php

I am trying to get the value (true or false) of a checkbox and update the database of a row in a while function. However, the checkboxes only seem to register a change of value depending on the first row. For example, if row 1 checkbox is checked, value = true. I can then click on the following rows and get checkbox value of true. However, when I click rows beyond the first row to get false, it will only register if the first row checkbox was unchecked first. I think it's something to do with the row id but tried for ages to fixed this but can't fix it. Please help.
HTML/PHP
while($row = $result->fetch_assoc()) {
echo
'
<input type="checkbox" name="home['.$row["id"].']" id="'.$row["id"].'" '.($row["home"]>0 ? 'checked="checked"' : '').'>
<label for="'. $row["id"].'"></label>
JQUERY
$(document).ready(function(){
$('input[type="checkbox"]').on("click", function(){
var on = $('input[type="checkbox"]').prop("checked");
$.post("work/updateaddress.php",{home:on,id:this.id});
});
});
PHP/MYSQL
if ($home == 'true') {
$check = date("Ymd");
} else {
$check = '';
}
if(isset($_POST["home"])) {
$sql = "UPDATE addresses SET home='$check' WHERE id='$id'";
if($mysqli->query($sql) === TRUE){
} else {
echo "error" . $sql . "<br>".$mysqli->error;
}
}
The issue is because you're selecting all the checkboxes in the click handler and then accessing prop() on that collection, which will only return the value from the first one.
Instead, use the this keyword to reference the checkbox which raised the event. You should also use the change event instead of click for accessibility reasons:
$('input[type="checkbox"]').on('change', function(){
var on = $(this).prop("checked"); // or just this.checked
$.post("work/updateaddress.php", {
home: on,
id: this.id
});
});
//Use this to refer to the box being clicked:
$(document).ready(function(){
$('input[type="checkbox"]').on("click", function(){
var on = $(this).prop("checked");
$.post("work/updateaddress.php",{home:on,id:this.id});
});
});
You should be using change event instead of click event for the checkbox.
$('input[type="checkbox"]').on('change', function(){
var on = this.checked
console.log(on)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="a">
Alternatively to change you could use input
$('input[type="checkbox"]').on('input', function(e){
let thisCheckbox = e.target.checked
alert(thisCheckbox)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="row1" id="row1" checked="checked">
<label for="row1">row1</label>

Post Input Attribute (Not Value) to Thank You Page

Is there a way to post attributes other than the value to another page?
For eg: If i have <option value="Bulgaria" data-key="BG" data-geo="EMEA">Bulgaria</option>
I know i can post the value and get it on the thank you page with $_POST,
but what if i wanted to get the data-key instead of the value?
$( "#myselect option:selected" ).data("key") or
$( "#myselect option:selected" ).attr("data-key")
But you need to send values via js insted of html form send
You can only post the value (unless you use AJAX and a bit of manipulation). If you go for the JavaScript route, this would be achieved with something like this:
$('form').submit(function(e) {
data = {};
url = '';
e.preventDefault();
$('input', this).each(function() {
var pcs = $(this).data();
var datakey = $(this).attr('data-key');
if (undefined == data[datakey]) {
data[datakey] = {};
data[datakey]['_'] = $(this).val();
}
$.each(pcs, function(k, v) {
data[datakey][k] = v;
});
});
$.ajax({
url: url,
data: data,
type: "POST"
}).done(function() {
// data-key successfully POSTed
});
});
The better question is why are you attempting to do this? If you only want an output of BG, use that as the value. If you want both Bulgaria and BG, you can make use of a hidden input to additionally send the secondary data (as a value):
<input type="hidden" name="shortcode" value="BG" />
Simple, you can try it:
HTML:
<form ... method="post" onsubmit="return form_check()">
<input type="hidden" name="data_key" id="data_key">
<input type="hidden" name="data_geo" id="data_geo">
...
<button type="submit">Submit</button>
</form>
jQuery:
function form_check() {
$('#data_key').val($('#myselect option:selected').data('key'));
$('#data_geo').val($('#myselect option:selected').data('geo'));
return true;
}
then in your PHP you'll receive them in $_POST['data_key'] and $_POST['data_geo'].

php handler not responding when using mutliple form with same handler

I use the following code to output a table with FAQ.
// get faq
global $wpdb;
$faq = $wpdb->get_results("SELECT ID, q, a, cat, quality, active FROM ce_faq");
foreach ($faq as $i) {
echo
'<div>
<a id="'.$i->ID.'" class="question" href="#">'.$i->q.'</a>
</div>
<div id="a'.$i->ID.'" class="answer">
<p>'.$i->a.'</p>
<form method="POST" id="form'.$i->ID.'">
<input type="hidden" value="'.$i->ID.'" name="faq_id"></input>
<input type="hidden" name="action" value="ce_faq_quality"/>'
.wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ).
'<p><b> Was this answer usefull? <input type="radio" name="quality" value="1" class="quality_radio"> yes </input><input type="radio" name="quality" value="-1" class="quality_radio"> No </input> </b></p>
</form>
</div>';
}
echo '<div id="feedback">feedback</div>';
I use jQuery().slidetoggle to toggle the answers when somebody clicks on the question. I want to enable end-users to give feedback on the questions with a simple yes or no question. The form should be submitted when one of the radio buttons is selected. the trigger jQuery('.quality_radio').click is working and also the formid is correctly fetched.
problem: The function ce_faq_quality(); is unfortunately not responding, when i use console.log(qu) i get for example 'faq_id=1&action=ce_faq_quality&name_of_nonce_field=7dd1d930af&_wp_http_referer=%2Ffaq%2F&quality=1', which seems to be correct to me. I also get the alert 'this is working'. The php handler doesn't seem to work however. the div feedback turns 0 (instead of 'success php function') and also the query isn't performed (while I know it works for 120%). I am at a loss here...
solved: the handler wasn't accessible from the page i was working on...
jQuery('.question').click(
function(){
var id = this.id;
jQuery('#a'+id).slideToggle(350);
});
jQuery('.quality_radio').click(
function(){
var formid = jQuery(this).closest('form').attr('id');
var formid = '#'+formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formid){
var qu = jQuery(formid).serialize();
console.log(qu);
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success:function(data){
jQuery("#feedback").html(data);
alert('this is working');
}
});
return false;
}
This is the php function i use to process the form.
add_action('wp_ajax_ce_faq_quality', 'ce_faq_quality');
add_action('wp_ajax_nopriv_ce_faq_quality', 'ce_faq_quality');
function ce_faq_quality(){
$quality = 1; //$_POST['quality'];
$faq_id = 1; //$_POST['faq_id'];
global $wpdb;
$wpdb->query($wpdb->prepare("UPDATE `ce_faq` SET `quality`= `quality` + $quality WHERE id = $faq_id"));
echo 'succes php function ';
die();
}
Your formid variable falls out of scope in the ajaxSubmit function. You should instead try:
jQuery('.quality_radio').click(
function() {
var formid = jQuery(this).closest('form').attr('id')
var formid = '#' + formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formId) {
var qu = jQuery(formid).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
So that you pass the formid to the ajaxSubmit function.

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

checkbox state should retain state to hide/unhide text on pageload

as a follow up to this question, while the checkbox value is stored on pageload, the text is displayed on pageload, even if the checkbox is unchecked. the text should hide/display only if the user has unchecked/checked the checkbox, throughout the session or till he closes the browser.
js code which stores the checkbox state:
function getStorage(key_prefix) {
// this function will return us an object with a "set" and "get" method
// using either localStorage if available, or defaulting to document.cookie
if (window.localStorage) {
// use localStorage:
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
// use document.cookie:
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = decodeURIComponent(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
// a key prefix is used for the cookie/storage
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
$('#ab_'+this.id).toggle($(this).is(':checked'));
// save the data on change
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
// on load, set the value to what we read from storage:
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val) $(this).trigger('change');
});
});
this ^code should work, but it while it retains the state of the checkbox, it doesn't for the text. is it because the text is being called from a php page?
html:
$(document).ready(function() {
$("#bquote").load("quotes_in.php");
});
.. ...
<div class="check">
<p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>
<p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
</div>
.. ...
<blockquote id="bquote">
</blockquote>
php:
public function formatQuotes($row)
{
return "<p id=\"ab_name\">" . $this->h($row['cName']) . "</p><br />"
. "<p id=\"ab_reference\">" . $this->h($row['vReference']) . "</p>";
}
You need to trigger the change() event on document ready after the p elements are generated.
Edit:
If placing the change trigger after the .load() call does not work, then that is probably due to the ajax request not being completed yet at the point of triggering. This can be solved by using callback parameter of .load(). Therefore, the code should look something like:
$(document).ready(function() {
$("#bquote").load("quotes_in.php", function() {
// create the P elements
// trigger the change() event
});
});

Categories