I have an html form displaying a series of checkboxes. The checkboxes (an array called "checkbox" is ) are created using a loop in php. I want to use this array for some background processing.
Trying to use AJAX as below, but I am not able to get it working.
Please help!
Here is test.php: containing html form:
<!DOCTYPE html>
<script language="javascript">
function activate(checkbox){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checkbox));
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate(checkbox)" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
Output: Don't get any response.
process.php: decode json data and display the array
<?php
$data = file_get_contents( "php://input" );
$checkbox = json_decode( $data, true );
echo "Hello!<br>";
var_dump($checkbox);
?>
NOTE: If, in the button element, I use this.checkbox, var_dump returns NULL.
<button type="button" name="button" onclick="activate(this.checkbox)" >Test</button>
Response:
ajaxState: 4
ajaxStatus: 200
ajaxResponse: Hello!
NULL
Check the below code...
<!DOCTYPE html>
<script language="javascript">
function activate(){
/*getting all inputs*/
var inputs = document.getElementsByTagName("input");
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
//then making a request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
console.log(xhttp);
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checked));//sending checked instead of checkbox
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate()" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
used this to get all checkboxes
Better use Query see jQuery - AJAX
Here realization "Click on button and show id current button in ajax, for use in second needed tasks". If I right anderstand you.
{{--include jQuery CDN Library--}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<button type="button" name="1" id="test" >Test</button>
<button type="button" name="2" id="test" >Test</button>
<button type="button" name="3" id="test" >Test</button>
...
<style>
$("button#test").change(function(){
var id = $(this).attr('name');
$.ajax({
method: 'POST',
url: 'process.php',
data: {id: id}
})
.done(function(msg){
console.log('button: ' + msg);
});
});
</style>
And php file
<?php
$data = $_POST['id']
$checkbox = json_encode($data);
echo "Hello!<br>";
echo $data; // show id checkbox
?>
It is simpler realization codes, from same javascript codes
Related
I'm kind fresh with Ajax and done some examples they worked, but then they stopped, I believe somewhere is error involved.
mainfile
<button class='chbt' title='Test' value=" . $i . " onclick='changer($(this).val())'></button>
changer function
function changer(val)
{
if (val == null)
{
document.getElementById("dataedit").innerHTML = "";
return;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("dataedit").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","testing.php?id="+val,true);
xmlhttp.send();
}
testing.php file
<?php
include_once 'dbconnect.php';
$ged = $_GET['id'];
$query = $DBcon->query("SELECT * FROM review WHERE RID=".$ged);
$RRow=$query->fetch_array();
?>
<html>
<head>
<script src="scripts/jscript.js"></script>
</head>
<body>
<script>
alert("working123!!!");
$('#dataformas').hide();
$('#dataedit').show();
</script>
<form method='post' action='updatereview.php' id='updata' name='updata'>
Vn<input name='rating' id='rating' type='range' min='1' max='5' maxlength='500' value='<?php echo $RRow[4]; ?>' step='1' required />Pt<br><br>
<textarea name='edittext' id='edittext' rows='5' cols='30'><?php echo $RRow[2]; ?></textarea>
<span id='count2'></span>
<script>
//location.hash = ".updata";
var el_t = document.getElementById('edittext');
var length = el_t.getAttribute('maxlength');
var el_c = document.getElementById('count2');
el_c.innerHTML = length;
el_t.onkeyup = function ()
{
document.getElementById('count2').innerHTML = (length - this.value.length)+' left';
};
</script><br>
<input type='hidden' name='idas' id='idas' value="<?php echo $ged; ?>">
<input type='hidden' name='cidas' id='cidas' value="<?php echo $RRow[3]; ?>">
<button type='submit' form='updata' id='send_button' value='Submit'>Update</button>
</form>
</body>
</html>
I as you can see I need to pass one param which is integer generated by loop, so my changer function is not working and throws
Uncaught TypeError: Cannot set property 'innerHTML' of null
at XMLHttpRequest.xmlhttp.onreadystatechange
I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)
It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.
i'm new to this so i hope you could help me.
i'm try to build one page has the ability to add and remove from sqldb.
from some reason i have to send value from js to php and i try this basic code and it doesn't work .
<html>
<head>
<script src="resources/js/jquery-2.2.3.js"> </script>
</head>
<body>
<form method="get">
<input type="button" value="submit" name="submit" class="test">
</form>
<div id="state"></div>
</body>
<script type="text/javascript">
$('.test').click(passValue);
function passValue(e){
document.getElementById('state').innerHTML="button is clicked";
var js_var = "xml recevid";
var xhr = new XMLHttpRequest();
var url = 'test.php?js_var=' + js_var;
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
document.getElementById('state')xhr.responseText;
}
}
xhr.send();
}
</script>
<?php
if (isset($_GET['js_var'])) $php_var = $_GET['js_var'];
else $php_var = "<br />js_var is not set!";
echo $php_var;
?>
USE $php_var ="<script type='text/javascript'>document.write('js_var');</script>";
NOTE THAT js_var shoul be a global variable, not local one.
My index.php:
<html>
<head>
</head>
<body>
<form name="form1" action="submit.php" method='POST'>
<select id="dropdown1" name="country" onchange="window.getStates()">
<option> Select Country</option>
<option value="1">Pakistan</option>
<option value="2">India</option>
<option value="3">USA</option>
<option value="4">UK</option>
</select>
<input type="text" id="area" style="display: none;" size="16" placeholder=" Enter value"></input>
<input type="submit" id="submit" style="display: none" name="submit" value="submit" onclick="submit()">
</form>
<script type="text/javascript">
function show() {
{ document.getElementById('area').style.display = 'inline-block';
document.getElementById('submit').style.display = 'inline-block';}
}
function getStates()
{
var xmlhttp;
try{
xmlhttp = new XMLHttpRequest;
}catch(e)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp)
{
var form = document['form1'];
var country = form['country'].value;
xmlhttp.open("GET","http://localhost/getStates.php?country="+country,true);
xmlhttp.onreadystatechange = function()
{
if(this.readyState == 4)
{
var s = document.createElement("select");
s.onchange=show;
s.id="dropdown2";
s.name="state";
s.innerHTML = this.responseText;
if(form['state'])
{
form.replaceChild(s, form['state']);
}
else
form.insertBefore(s,form['submit']);
}
}
xmlhttp.send(null);
}
}
function submit() {
var table = document.getElementById("dropdown1").value;
var parameter = document.getElementById("dropdown2").value;
var value = document.getElementById("area").value;
$.ajaxSetup({
url: "http://localhost/database.php",
type: "POST",
});
$.ajax({
data: 'table='+table+'¶meter='+parameter+'&value='+value+,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
}
</script>
</body>
</html>
my getStates.php code:
<?php
$states=array(
"1" => array("NWFP","Sindh","Bala","Punjab","Select"),
"2" => array("gujrat","goa","U.P.","Select"),
"3" => array("bgjs","hhtrs","Bhtrshts","Utah","Select"),
"4" => array("England","Scotland","Bahwgla","Punthwthjab","Select")
);
if(isset($_GET['country']))
{
$c = $_GET['country'];
if(isset($states[$c]))
{
for($i = count($states[$c]) -1; $i>=0; $i--)
{
echo "<option value='".$states[$c][$i]."'>".$states[$c][$i]."</option>";
}
}
}
?>
database.php code:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['table']) && isset($_POST['parameter']) && isset($_POST['value'])){
$table = ($_POST['table']);
$parameter = ($_POST['parameter']);
$value = ($_POST['value']);
$db = mysql_connect(localhost, root, "");
$select = mysql_select_db(records, $db);
$query="INSERT INTO $_POST['table'] (Parameter,Value)
VALUES ('".$_POST['parameter']."','".$_POST['value']."');";
}
mysql_query($query,$connection);}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
Also, the submit button has a onclick() and an action tag. When the submit button is clicked, i want the submit() function to be executed, so what should i do for that? When i press submit, the parameter and value values are not being inputted into my database called records with 4 tables named 1,2,3 and 4. Thanks!
I think there is some probllem with this line:
$query="INSERT INTO $_POST['table'] (Parameter,Value)
VALUES ('".$_POST['parameter']."','".$_POST['value']."');";
You have commented out submit() and Maybe that's the problem...
The form submission overtakes the onclick call.
You should check this out:
http://www.codediesel.com/javascript/prevent-form-submissions-with-javascript-disabled/
<script>
$(function(){
$("form").submit(function(e) {
e.preventDefault();
});
});
</script>
i have a problem with my simple program in php that include an alert javascript.
This is the code:
<?php
function iva(){
$country='IT';
$vatnum=$_POST['n'];
$a="Work";
$b="NotWork";
$url='http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
}
if ($response != 'true'){
echo $b;
}
}
?>
<script>
function ivaz(){
alert("<?php iva() ?>");
}
</script>
<form method="post">
<input name="n" type="textarea" >
<input onclick="ivaz();" value="Validate" type="submit"> </input> </form>
My program take a value from input text box and pass the value to php script that return true or false in a javascript alert. The program work, but return previous value passed in input box.
Can someone help me to solve it?
Thanks guys.
No, it doesn't work that way. If you want to call a PHP function from Javascript without the page refreshing, you need an XMLHttpRequest.
Example:
<?php
// your php process when called by XMLHttpRequest
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vatnum = $_POST['n'];
$country='IT';
$a = "Work";
$b = "NotWork";
$url = 'http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
} else {
echo $b;
}
exit;
}
?>
<form method="post" id="form1">
<input name="n" type="text" id="n" />
<input value="Validate" type="submit">
</form>
<script type="text/javascript">
// when the form is submitted
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
var n = document.getElementById('n').value; // get the textbox value
var xmlhttp = new XMLHttpRequest();
var params = 'n=' + n;
var php_url = document.URL;
xmlhttp.open('POST', php_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
alert(response); // alert the server response
}
}
xmlhttp.send(params);
});
</script>
Remove onclick="ivaz();" from input tag
You cannot run the php script without reloading the page as php is generated serverside and javascript runs clientside.