On my page1.php I want to toggle the visibility of the page2.php.
I am using the following code:
<input type="radio" name="city" value="Barcelona" onclick="getPage2(this.value);"> Barcelona
<input type="radio" name="city" value="Manchester"> Manchester
I call the page2.php using this code:
function getPage2()
{
$.ajax({
type: "GET",
url: "page2.php",
success: function(result){
$("#show_results").html(result);
}
});
};
I want to show the page2.php only if the radio button is selected and show nothing (Hide it) if none of the radio buttons, or the 'Machester' radio button is selected.
UPDATE
I solved it. It was actually very easy.
<input type="radio" name="city" value="Barcelona" onclick="getPage2(this.value);"> Barcelona
<input type="radio" name="city" value="Manchester" onclick="getPage2(this.value);"> Manchester
I show and I hide the page2.php using this code:
function getPage2()
{
var var_name = $("input[name='city']:checked").val();
$.ajax({
type: "GET",
url: "page2.php",
success: function(result){
if(var_name == "Barcelona")
$("#show_results").html(result).show();
else
$("#show_results").html(result).hide();
}
});
};
Thank guys anyway.
You can use a JQuery selector for that :
$('input').click(function(){
$('input').show(); // Show all inputs
$(this).hide(); // Hide the clicked input
$.ajax({
type: "GET",
url: "page2.php",
success: function(result){
$("#show_results").html(result);
}
});
})
Of course, this works only for a page with those inputs only.
You should have classes or IDs to your radios to target them directly with the selector.
You will have something like this :
$('.radio-page').click(function(){ // ...
You could just load the hide-able content WITH the original page. That way you can avoid the ajax call.
<input class="radios" type="radio" name="city" value="Barcelona"> Barcelona
<input class="radios" type="radio" name="city" value="Manchester"> Manchester
<div id="content" style="display:none">Hide-able content</div>
And then just have the script make it appear when Barcelona is selected.
$("input[type='radio']").click(function()
{
if($(this).val() == "Barcelona") $("#content").show();
else $("#content").hide();
});
Related
I am struggling to have multiple AJAX submitted forms on the same php page. I can get it to work with one, but when I add more, it just uses the first form all the time.
I have tried to make it unique but not sure exactly how to do this.
My code is below, if someone could please assist that would be fantastic.
I have looked at similar questions and answers on this site but can't seem to fathom how to make it work for mine.
The form should submit when the checkbox is checked or unchecked.
Thanks very much in advance for all your help.
Martyn.
HTML form
<form id="search_form" method="post">
<input readonly type="text" name="id" value=<?php echo $row1[0];?>>
<input readonly type="text" name="student" value=<?php echo $row1[1];?>>
<input readonly type="text" name="addedby" value=<?php echo $_SESSION['username'];?>>
<input readonly type="text" name="register" value="monday_morning">
<input <?php if($row1[4] == "Yes"){echo "checked";}?> type="checkbox" name="box" value="Yes">
</form>
Script
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function () {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $("#search_form").serialize(),
success: function (data) {
}
});
return false;
});
</script>
Try this
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function (event) {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $($(event.target).parent()).serialize(),
success: function (data) {
}
});
return false;
});
</script>
event.target returns the clicked checkbox.
parent() function returns the form you need to submit. This way you don't need to have unique form id.
I'll start this by saying I've delved through copious amounts of other posts to try and find the solution however I've not been able get my code to work.
What I'm trying to do is send a variable from a radio button selection through AJAX to PHP. I don't want to have to add a submit button, I want the PHP code to process once a radio button is toggled.
My simple code is as follows, similar on.change code I've successfully used for dropdown menus but I'm struggling to get the same functionality for radio buttons.
Appreciate any assistance available.
HTML RADIO BUTTONS
<form>
<div class="label"><b>Include Points?</b></div>
<input type="radio" name="Pts" value="On" /> On
<input type="radio" name="Pts" value="Off" checked="checked" /> Off
</form>
JQUERY AJAX
jQuery(document).ready( function($) {
jQuery('#Pts').on( 'click', function () {
Pts = $('input:radio[name=Pts]:checked').val();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'call_radio_practice',
Pts: Pts,
},
success:function(output){
jQuery('#practice').html( output );
}
});
}).click();
});
PHP
$Pts = $_POST['Pts'];
print_r($Pts);
You don't have this selector jQuery('#Pts') (id Pts).
Change to listen to change event on input:radio[name=Pts]
jQuery(document).ready( function($) {
jQuery('input:radio[name=Pts]').on('change', function () {
Pts = $('input:radio[name=Pts]:checked').val();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'call_radio_practice',
Pts: Pts,
},
success:function(output){
jQuery('#practice').html( output );
}
});
});
});
In my code having two radio buttons in form like
<input type="radio" required="required" id="bt" name="bt" value="1" checked="checked" onclick="window.location='<?php echo $_SERVER['REQUEST_URI']; ?>';" /> <span>Test1</span>
<input type="radio" required="required" id="bt" name="bt" onclick="Clear()" value="2" /> <span>Test2</span>
when i click on Test2 radio button the form having value will clear, for that i wrote code its working fine
<script>
function Clear() {
document.getElementsByName("one")[0].value = "";
document.getElementsByName("two")[0].value = "";
document.getElementsByName("three")[0].value = "";
}
</script>
with this form with values cleared.But when i click on "Test1" radio button the form values will come automatically.right now iam sessions using
onclick="window.location='<?php echo $_SERVER['REQUEST_URI']; ?>';"
for this it is coming but page is refreshing how to take it this code to ajax, i mean need to get values when i click on radio button without refreshing the page
Yes you can use window.location.href in ajax as:
$.ajax({
type: 'POST',
async: false,
url: '/users',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(payload),
success: function(data, textStatus, jqXHR){
console.log(jqXHR.status);
window.location.href= "/someUrl.html";
}
});
Note that: window.location.href will not reload the page if there's an anchor (#) in the URL
Here i wrote code for getting values of radio button without page refresh:
html code:
<input type="radio" name="bt" id="bt" onclick = "MyAlert()" value="blue"/>Blue <br/>
<input type="radio" name="bt" id="bt" onclick = "MyAlert()" value="red"/>Red
ajax script:
function MyAlert() {
var radio =$('input[type="radio"]:checked').val();
var pass_data = {
'radio' : radio,
};
$.ajax({
url : "radio-value.php",
type : "POST",
data: pass_data,
success : function(data) {
// alert radio value here
alert(data);
}
});
return false;
}
radio-value.php file:
<?php echo $bt =$_POST['radio']; ?>
Hope this helps.
I have a product page with the following form:
<form id="ratingsForm" action='../resources/add_rating_to_product.php' method="POST">
<input type="hidden" name="productID" value="<?php echo $productID; ?>" />
<span class="rating">
<input type="radio" class="rating-input"
id="rating-input-1-5" name="rating" value="5">
<label for="rating-input-1-5" class="rating-star"></label>
...
<input type="radio" class="rating-input"
id="rating-input-1-1" name="rating" value="1">
<label for="rating-input-1-1" class="rating-star"></label>
</span>
</form>
This is just a simple star rating form which uses radio buttons.
I have a javascript file that will submit the form once a radio button is clicked
$(document).ready(function() {
$('input[name=rating]').change(function(){
$('form').submit();
});
});
I have another javascript file that will trigger when the form is submitted and use ajax to post it to the correct file.
$(document).ready( function() {
$("#ratingsForm").on("submit",function(e){
e.preventDefault();
$.ajax( {
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
alert('Thanks for rating');
}
});
})
});
Add_rating_to_product just takes the posted information and inserts it into the database.
The problem I'm having is that instead of preventing and redirection, e.preventDefault redirects me to my search page for apparently no reason. I have check all of my code in my product page and there's nothing that could redirect me there so what is the problem? Without the preventDefault(), it redirects to add_rating_to_product.php as expected.
Is there any chance you have another form on your page? If you do, the following code submits all the forms on the page:
$(document).ready(function() {
$('input[name=rating]').change(function(){
$('form').submit();
});
});
I think it would be safer to do the following:
$(document).ready(function() {
$('input[name=rating]').change(function(){
$(this).closest('form').submit();
});
});
After the success function call you can use
$(this).unbind('submit').submit()
, which will allow the execution to continue as if preventDefault was nt called
Try this:
$(document).ready(function() {
$('input[name=rating]').change(function(e){
e.preventDefault();
var prodID = $(this).find("input[name='productID']").val();
$.ajax( {
type: "POST",
url: $(form#ratingsForm).attr( 'action' ),
data: {$('form#ratingsForm').serialize(), prodID: prodID},
success: function( response ) {
alert('Thanks for rating');
}
});
});
});
Just do it in one function to initialize and send them in server side. I hope this works.
I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });