I'm going to get the checked radio button value using AJAX in PHP. I have done the following code, but i can't continue.
I need your help.
ajax_radio.php
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" name="radio1">Blue</input>
<input type="radio" name="radio2">White</input>
<input type="radio" name="radio3">Red</input>
<input type="button" name="btn" value="Click" onClick="hello('a')"></input><br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
ajax.js
var xmlHttp;
function GetXmlHttpObject(){
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
try{
xmlHttp = new ActiveXObject(Msxml2.XMLHTTP);
}
catch(e){
try{
xmlHttp = new ActiveXObject(Microsoft.XMLHTTP);
}
catch(e){
alert("doesn't support AJAX");
return false;
}
}
}
}
function hello(a){
GetXmlHttpObject();
xmlHttp.open("GET","ajax_radio.html?",true);
xmlHttp.onreadystatechange = response;
xmlHttp.send(null);
}
function response(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var radio_text = xmlHttp.responseText;
document.getElementById('btn_get').innerHTML = radio_text;
}
}
}
Do you know how to complete this? Thanks in advance. :)
Edit:
I can't post the code here right now, because of the low speed of network. I'm sorry.
I have shared it in rapidshare. Can you download it firstly, and help then? Thanks a lot.
I have to update it when i go back home. Too bad.
because I mostly use Jquery I wrote here a jquery snipped that checks radio button values because it is much easier and cleaner:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.0");
</script>
<script type="text/javascript">
$(function() {
$('#buttoncheck').click(function () {
var var_name = $("input[name='radio1']:checked").val();
$('#btn_get').val(var_name);
});
});
</script>
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" value="Blue" name="radio1">Blue</input>
<input type="radio" value="White" name="radio1">White</input>
<input type="radio" value="Red" name="radio1">Red</input>
<input id="buttoncheck" type="button" name="btn" value="Click"></input>
<br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
Take a look for jquery here: Jquery
Explanation:
This part selects the item with the ID #buttoncheck and checks if its ran: $('#buttoncheck').click(function () {
Then it will run the code in the function. This code gets the value of a input box with the name radio1. the ':checked' makes sure that it only selects the value of the checked radio button:
var var_name = $("input[name='radio1']:checked").val();
And last. This puts the value of the variable into the item with #btn_get as id:
$('#btn_get').val(var_name);
Related
I posted a smaller to this yesterday and was shown how to do this but it doesn't work and the user never got back to me and I have been working on the same problem for hours.
I am trying to post a checkbox array from jQuery to php, when I run my code nothing seems to happen and when I try var_dump($_POST) this is all I get
Using this question as a reference, it seems that jQuery doesn't handle arrays too well. You can use to snippet from the accepted answer and it should work just fine.
serialize().replace(/%5B%5D/g, '[]')
Change the submit to a button or better use the form's submit event
why data-type html?
Your php does not seem to react to the serialised data but returns a button...
try my code here: http://plungjan.name/SO/sport.php
I am not unravelling the check box array - that is up to you
<?PHP
if (isset($_POST['saved'])) {
echo "saved"; exit(0);
}
else if (isset($_POST['Submit'])) {
echo var_dump($_POST["sport"]); exit(0);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sports quiz</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('#myForm').on("submit", function(ev) {
ev.preventDefault(); // cancel submit
var $form = $(this);
if ($("[type=checkbox]:checked").length ==0) {
alert("Please check one or more");
return false;
}
var formData = $form.serializeArray();
formData.push({name:"Submit",value:"submit"}); // note I changed the name from submit to Submit
$.post('sport.php',formData, function(data) {
console.log("Data",data);
if (confirm('You want to save \n' + data + ' as your sport?')) {
formData = $form.serializeArray();
formData.push({name:"saved",value:"saved"});
$.post('sport.php',formData,function(data) {
console.log("Saved Data",data);
});
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="checkbox" name="sport[]" value="Football">Football<br>
<input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
<input type="checkbox" name="sport[]" value="Golf">Golf<br>
<input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
<br> <input type="submit" class="btn btn-info" name="Submit" value="submit">
</form>
</body>
</html>
I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>
I search through the net but didn't find much things on my problem. Hope someone here can help!
As i write in the title I want to upload mutliple files, one at a time, with only one input.
I tried to do this using JQuery as you can see below, but obviously it doesn't work!
Anyone can help, please?
<!doctype html>
<html>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<head>
<script>
$(document).ready(function() {
$(document).on('change', '.file',function(){
$('<input type="file" name="file[]" class="file" size="60" />').appendTo($("#divAjout"));
$("div input:first-child").remove();
return false;
});
});
</script>
<title>test input file unique pour plusieurs fichiers</title>
</head>
<body>
<form action="" method="post" enctype='multipart/form-data'>
<div id="divAjout">
<input type="file" name="file[]" class="file" id='file' size="60" />
</div>
<input name="submit" type="submit">
</form>
<?php if(isset($_POST['submit'])){echo'<pre>'; print_r($_FILES);echo'<pre>';} ?>
</body>
</html>
You can clone input file with incrementing name attribute, like file[0], file[1], file[2], etc.
function readURL(input) {
var index = ($(input).data('index'));
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(input).parent().children('.newImage')
.attr('src', e.target.result)
.height(120);
};
reader.readAsDataURL(input.files[0]);
$('.addPh').show();
$('.addPh').last().clone().insertBefore($('#addPhoto')).hide();
++index;
$('.addPh').last().children('.photo_new').data('index', index).attr('name', 'photo_new['+index+']');
}
}
$(document).ready(function () {
$('#addPhoto').click(function () {
$('.photo_new').last().click();
});
});
See this example: https://jsfiddle.net/w0cd3Ls4/3/
I have two fields in form and onsubmit() event I am calling function. When I click udpate button I could not get the values of "sent", all other values fetched correctly.
In case of insert button, sent is fetched correctly.
I am tracking the values using aler button. Can it be done using firebug too?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
**alert(id);
alert(sent);
alert(submit.name);
alert(submit.value);**
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" />
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label><input type="text" name="id"><br>
<label>Enter the sentence:<input type="text" name="sent"></label><br />
</pre>
<input type="submit" class="submit" value="submit" name="update"/>
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
You're always getting the first sent and id elements because you're using document.getElementsByName, so you need to grab the ones within the form that is submitted. By always getting the first, you will get the values from the insert form even when the update form is submitted.
var sent = form.elements['sent'].value;
var id = form.elements['id'].value;
The above will get the sent and id values from the form that was submitted, based on the form object that was passed as an argument.
You can use console.log(...) and console.debug() with firebug.
See the documentation for more info: https://getfirebug.com/wiki/index.php/Console_API
Not sure what you're trying to accomplish, but you should at least provide us with a copy of ajax_test.php if you want us to test your code. Do you get any error messages in to firebug console?
Also, why not use the ajax features of jQuery? That would make things far easier on yourself. Piao Yishi has a good tutorial on NetTuts+ on how to do that: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Doing so might just solve your problems.
I am a newbie in web base applications development and Im learning AJAX. Here is my problem, I'm trying to make an AJAX request with some variables (user inputs) and get the php file with the same variables. Below is my code, if there something I am missing or I am doing wrong please let me know, I will appreciated any help! Thank you.
Javascript code:
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
document.getElementById("Alert").innerHTML= "*Your browser broke!";
document.getElementById("Alert").style.color = '#E00000 ';
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('display');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
var input_building = document.getElementById('building').value;
var input_room = document.getElementById('room').value;
var queryString = "?building=" + input_building + "&room=" + input_room;
ajaxRequest.open("GET", "map.php" + queryString, true);
ajaxRequest.send();
}
</script>
HTML:
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" >
<input id="submit" type="button" value="submit" onclick="ajaxFunction()" >
<p id="display"></p>
PHP file:
<?php>
$building = $_GET['building'];
$room = $_GET['room'];
echo "<h1>".$room." ".$building."</h1>";
?>
You are setting a value property on a <p> element. You should be setting its innerHTML. Value is used for input fields.
document.getElementById('display').innerHTML = ajaxRequest.responseText;
As requested, I will post my comment
In your code you need to change ajaxDisplay.value to ajaxDisplay.innerHTML - as elaborated by Juan, form fields have values and container tags have innerHTML.
To defend the use of jQuery a little - I basically agree that for simple JavaScript, loading an external library can be overkill - in the case of Ajax, I trust jQuery to cover all browsers needs.
Your code with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>Get building</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() { // run onload
$("ajaxbutton").on("click",function() {
var input_building = $('building').val();
var input_room = $('room').val();
var queryString = "?building=" + input_building + "&room=" + input_room;
$("#display").load("map.php" + queryString); // get the room
});
});
</script>
</head>
<body>
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" />
<input id="ajaxbutton" type="button" value="Find Building" />
<p id="display"></p>
</body>
</html>
NOTE: for more control over the result you can change the load to
$.get("map.php" + queryString,function(data) {
// do something with data here - for example if you use JSON
$("#display").html(data);
});