i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/submit/
Related
I have already submitted forms using ajax,
i have a query with my dynamic text fields I need to pass their value through ajax. i have done this trough PHP, but I need to use ajax function to do that.
Below is my PHP code how i did it.
<form>
<h3>Day 1 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 2 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 3 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 4 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<!------- button for adding more textfields for day deatils--->
<button name="" onclick="somefunctiontoaddmoretextfield">
</form>
this is my php code. i use foreach for my dynamic textfield as i have a button to add as many Day details i need.
but my conern is how can i pass this multiple textfield values in the ajax.
i have tried many thing and also search on stack but never found any answer.please help me with this how i can post this data using ajax.
<?php
foreach($_POST['b_destinations'] as $p_destination) {
$pdata[] = preg_replace("/[^A-Za-z0-9?! ]/","",$p_destination);
}
$pData[] = $pdata;
$b_destinations = json_encode($pData);
foreach($_POST['b_nights'] as $p_nights) {
$pdata1[] = filter_var($p_nights,FILTER_SANITIZE_NUMBER_INT);
}
$pData1[] = $pdata1;
$b_nights = json_encode($pData1);
?>
this is my ajax code. what needs to done here
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'destinations' : $('input[name=b_destinations]').val(),
'nights' : $('input[name=b_nights]').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
I have a form where one of the controls(inside a div) has a display of none. When a user checks a particular radio button the hidden div will display which contains an input element allowing him to enter some input.
When I tested it with PHP (using isset() function), I realized that the input variable is set, even if it's parent(div with id of details) is not shown.
What I want however is that serialize should only send the variable to the server when the div containing the input field is displayed. If I however gives display of none to the input element directly, it works as I want. But I want it to be on the div because some controls like labels and many other possible input fields need to also be hidden. One quick solution will be to give all the controls or elements in the div a class and toggles their display using the radio buttons, but I rather prefer the class to be on the div wrapping them all.
HTML:
<form id="form">
<div class="form-group">
<label for="firstname">First Name</label>
<input type="firstname" class="form-control" name="firstname" autofocus placeholder="First Name">
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="surname" class="form-control" name="surname" placeholder="Surname">
</div>
<label>1. Do you program?: </label>
<label class="radio-inline">
<input type="radio" name="one" value="Yes"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="one" value="No" checked> No
</label>
<div class="form-group" id="details" style="display:none;">
<label class="control-label">State your Languages</label>
<input type="text" name="language" class="form-control" autofocus>
</div>
<div class="form-group">
<button id="submit" class="btn btn-primary">Submit</button>
</div>
</form>
JavaScript
$(function(){
$('#form input[name=one]').change(function(event) {
$('#details').toggle();
});
$('#submit').on('click', function(event) {
event.preventDefault();
var form = $('#form');
$.ajax({
url: 'process.php',
type: 'POST',
dataType: 'html',
data: form.serialize()
})
.done(function(html) {
console.log(html);
})
.fail(function() {
console.log("error");
})
});
});
PHP
if(isset($_POST['language'])) {
echo 'Language is set';
} else {
echo 'Not set';
}
The PHP reports 'Language is set' even if the div containing the input with name of language is given display of none;
disabled input elements are ignored by $.serialize()
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
To Temporarily enable them.
var myform = $('#myform');
// Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');
// serialize the form
var serialized = myform.serialize();
// re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');
OR
You could insert input fields with no "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jquery):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
Instead going for complex workaround in JavaScript, you could accomplish it in PHP easy way. Check if the radio button Yes is selected and if it is selected, you can do other processing based on that.
if(isset($_POST['one']) && $_POST['one'] === 'Yes') {
if(!empty($_POST['language'])) {
echo $_POST['language'];
} else {
echo "Language is given empty!";
}
} else {
echo 'Language is not selected!';
}
The PHP code above is a simple workaround. You could go for that. If you're only looking to do that in JavaScript itself, I would direct you to the answer given by Bilal. He has some workaround with JavaScript.
EDIT
I've come up with my own simple workaround in JavaScript. Hope it could help you.
<script>
$(function() {
var details = $('#details');
$('#details').remove();
$('#form input[name=one]').click(function() {
if(this.value === 'Yes') {
details.insertBefore($('#form div.form-group:last-of-type'));
details.show();
} else {
$('#details').remove();
}
});
});
</script>
Storing the reference to div of id details in a variable before removing the details div from the DOM.
Based on the value selected in the radio button, the details div will be added to the DOM and displayed or removed from the DOM in case No is selected.
Hope it helps!
I am try to post a data from a from I have this code on my html.
<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
e.preventDefault();
var testData = $("#test").serialize();
$.ajax({
type: "POST",
url: "ajaxSurvey.php",
data: {survey:testData}
});
});
})
</javascript>
and my form
<form id="test" name="test" method="POST">
<input name="surveyperiod" id="surveyperiod" type="date">
<input name="deadline" id="deadline" type="date" >
<input type="submit" id="btnsubmit"name="btnsubmit" value=" Update ">
</form>
and my php page
if(isset($_POST['survey']){
$myDate = $_POST['survey'];
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES (????????)');
}
Now how can I deserialize $myDate which is look like below
surveyperiod=2014-02-25&deadline=2014-02-18
Tricky method is use parse_str()
// Access as Variable
if( isset($_POST['survey']) ){
// surveyperiod=2014-02-25&deadline=2014-02-18
parse_str($_POST['survey']);
$S_Period = $surveyperiod;
$S_Deadline = $deadline;
// do whatever you want
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ( "'.$S_Period.'", "'.$S_Deadline.'" )');
}
Explanation:
In you Ajax Request you send the data via POST method( data: {survey:testData} ) and assigned a POST variable that is survey and this POST variables contains the data string surveyperiod=2014-02-25&deadline=2014-02-18 as you assigned in your javascript testData. Now what we have to do is, Now we have to parse string into variables and parse_str() inbuilt function do it for you. That's it :)
You do not need to deserialize, you can do that in different way by putting hidden field like;
HTML:
<form id="test" name="test" method="POST">
<input name="survey" type="hidden" value="true"/>
<input name="surveyperiod" id="surveyperiod" type="date">
<input name="deadline" id="deadline" type="date" >
<input type="submit" id="btnsubmit"name="btnsubmit" value=" Update ">
</form>
PHP:
if(isset($_POST['survey']){
$myDate = $_POST['survey'];
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ($_POST["surveyperiod"], $_POST["deadline"])');
}
JS:
<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
e.preventDefault();
var testData = $("#test").serialize();
$.ajax({
type: "POST",
url: "ajaxSurvey.php",
data: testData
});
});
})
</javascript>
By doing this, you dont neede to post data like {survey:testData}. Simply add,
<input name="survey" type="hidden" value="true"/>
html and check hidden field on php side. If a field with name survey exists, then run your code
I want to do the search using ajax jquery js, for that I have taken this piece of code from here:-
Now i have some issues, I have this Javascript code:-
<script language="JavaScript" type="text/javascript">
<!--
function searchuser(cv) {
$("#SearchResult").html('<img src="loader.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#SearchResult").html(data).show();
});
}
//-->
</script>
My Form:-
<label>
<input onClick="generatenew();" type="radio" name="search_option" value="code" id="search_option_0">
Customer Code</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="company" id="search_option_1">
Customer Company</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="name" id="search_option_2">
Customer Name</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="email" id="search_option_3">
Customer Email</label>
This is my search textbox
<input type="text" name="searchuser_text" id="newInput" size="25" maxlength="25" class="inputbox MarginTop10">
This is my search button
<input onclick="javascript:searchuser('con1');" class="Button" name="search_user_submit" type="button" value="Search">
This is my Display Area :-
<div id="SearchResult">My default content for this page element when the page initially loads</div>
Now i want to know on click of button i am sending a data i.e. con1. I want to send two data to the searchuser function, one the selected option button value and the another one is the text in the textbox. After sending both the data to the function how will i get the data in the function? Do i need to change the function searchuser(cv) to function searchuser(cv, cvtwo).
Also while the $.post(url, {contentVar: cv} ,function(data) is sending only one data to the php file, how can i send both the data i.e. cv and cvtwo to the php file?
First of all you can modify the search function to something like this
$("input[name='search_user_submit']").click(function(){
var cv = $('#newInput').val();
var cvtwo = //similar to above
var data = 'cv='+ cv + '&cvtwo='+cvtwo; // sending two variables
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {contentVar: data} ,function(data) {
$("#SearchResult").html(data).show();
});
});
Don't use inline functions, you can do it easily with jQuery's native bind functionality:
// Search when you click on submit
$(document).on('click', '.submit_button', function(){
search('click_button');
});
// Search when you press enter
$(document).on('keypress', "#searchString", function(e){
var c = (e.keyCode ? e.keyCode : e.which);
if(c == 13) {
search('pressed_enter');
}
});
You can therefore collect the button value and pass it through to your search function:
function search(button_value) {
$("#myDiv").html('<img src="loader.gif"/>').show();
$.post("elements/search-user.php", { search_value: $('#newInput').val(), button_value: button_value} ,function(data) {
$("#SearchResult").html(data).show();
});
}
What you're doing is send off the form with two $_POST variables: one is the search string you've inputted in to the search box (called search_value) and the other is the button value.
Currently i have a form which has an image as a submit. It works fine as in the form variables get passed through and gets processed. However, the page gets refreshed every time click submit for the form since the processing page has a header back to the form page.
I need a way to send the form variables without the refreshing. I understand it can be done via ajax. However, i am facing a prob since my submit button is an image. Any help as to how i can rectify my code to submit the form without refresh would be great
<form name ="nominate" action="" id ="nominate" method="POST">
<input type="hidden" name="id" value="<?php echo $id;?>">
<input type="hidden" name="screenName" value="<?php echo $author;?>">
<input type="hidden" name="course" value="<?php echo $course;?>">
//this is the image submit button
<input type="image" style="float: left;" onMouseOver="this.src='images/nominated.png'"
onMouseOut="this.src='images/nominate.png'" value="Place Order" src="images/nominate.png" width="60" height="20">
</form>
<script>
$(function() {
$(".button").click(function() {
var id = $("#id").val();
var screenName = $("#screenName").val();
var dataString = 'id='+ id + '&screenName=' + screenName + '&course=' + course;
alert (dataString);
$.ajax({
type: "POST",
url: "nominate.php",
data: dataString,
success: function(){
alert(dataString);
}
});
});
});
</script>
The code you've done should work, if you add the class of "button" to the image.
<input type="image" class="button"....
Firstly you need to add the id attribute as in jquery $("#") is the id of the element.
<input type="hidden" name="id" id="id" value="<?php echo $id;?>">
<input type="hidden" name="screenName" id="screenName" value="<?php echo $author;?>">
<input type="hidden" name="course" id="course" value="<?php echo $course;?>">
Then as said by Andrew either add the class="button" or use $("#some_id") and then give the button input an id="some_id".
$(".button").click(function(){
var url = "nominate.php";
var id = $("#id").val();
var screenName = $("#screenName").val();
var course = $("#course").val();
$.post(url,{id:id, screenName:screenName , course:course }, function(data){
alert(data);
});
});
This will alert whatever you send back from "nominate.php". Make sure you remove the header() from the script and send back a success or error message possibly.
Add the class 'button' to your image.
Also, you don't seem to have course defined anywhere. You might want to fix that, too.