Checkbox state from HTML (JS) to PHP - javascript

I'm new to JS and i want to receive the value from a variable in JS, send it by post (or ajax) to a PHP file, and see the text display. The thing is i've been trying different ways to do it but i always get a undefined index in php.
My code is below
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checked=$("#switch").attr("checked");
if(checked)
{
$("switch").removeAttr("checked");
console.log("estado apagado switch 1");
var estados="1";
$.post("accion.php", {estado: "david"});
}else
{
$("#switch").attr("checked","checked");
console.log("estado encendido switch 1");
var estados="2";
$.post("accion.php", {estado: "david 2"});
}
});
</script>
</body>
</html>
accion.php
<?php
$est = $_POST['estado'];
echo $est;
if ($est=="david") {
echo "no mameees";
}else{
echo "no mameees no se puso ";
}
?>
Someone has any idea ?

$("#switch").change(function () {
var checked=$("#switch").prop("checked");
if(checked)
{
console.log(checked);
}else{
console.log(checked);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Switch <input type="checkbox" name="switch" id="switch" >
Use prop instead of attr to find checkbox is checked or not.

You can let php check if the checkbox was checked or not in a success callback from $.post:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checkbox = $("#switch");
$.post("accion.php", {estado: checkbox.val()}, function(data){
$("h1").html(data);
});
});
</script>
</body>
</html>
accion.php
<?php
$checkbox = isset($_POST['estado']) && $_POST['estado'] == 'on'; // 'on' is the default checkbox value when you don't specify it in html
if ($checkbox) {
echo "it's been checked";
}else{
echo "it wasn't checked";
}
?>
PS: when working with ajax ( check out $.post options) i recommend using dataType: 'json' and your php should respond with a valid JSON, you have json_encode for that.

use
var checked = $('#switch').is(':checked');
instead of
var checked=$("#switch").attr("checked");

Related

HTML disappearing after PHP function called

This displays the result of a button press. The idea is that it reads and writes from a file so that users in different browsers can see the same result.
I had some issues accessing the DOM originally but then discovered that after the first button press, everything below my php script is wiped This area doesn't get shown after button click
The easy workaround is to simply move the DOM element higher up but... I want to know...
Why is this area getting deleted? It's as if it's being treated like PHP.
//Background Loop
function updateChat(){
var file = 'word.txt?v=' + Date.now() ;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText);
document.getElementById("shownword").innerHTML = allText;
}
}
}
rawFile.send(null);
setTimeout(updateChat, 500);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Random Word Generator</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script language="javascript" src="update.js" type="text/javascript"></script>
</head>
<body onload="updateChat();">
<p id=shownword></p>
<form action="" method="post">
<input type="submit" name="word"
class="button" value="Button1" id="button1"/>
<input type="submit" name="word"
class="button" value="Button2" id="button2"/>
</form>
<?php
//This function gets called when button is pushed
function postword(){
$fp = fopen('word.txt', 'w');
fwrite($fp, $_POST['word']);
fclose($fp);
}
//When the button is pushed, the function will be called
if (isset($_POST['word'])) {
postword();
return;
}
?>
This area doesn't get shown after button click
</body>
</html>
Just remove the "return;"
if(isset($_POST['word'])) {
postword();
// return;
}

How to connect HTML page to MySQL Workbench Server using JavaScript,Ajax and PHP?

I have an HTML page where we enter the name of a movie and if that movie is present in the database,then the name is displayed. I am trying to connect to the database using JavaScript, Ajax and PHP. The database is in the MySQL Workbench Server.
This is what I have done:
pc.html
<html>
<head>
<script type="text/javascript">
function Search_Data()
{
var httpr = new XMLHttpRequest();
var movie_name=document.getElementById("moviename").value;
console.log(movie_name);
httpr.open("GET","get_data.php",true);
httpr.send();
httpr.onreadystatechange = function()
{
if(this.readyState==4 && this.status==200)
{
alert(this.responseText);
}
}
}
</script>
<body>
<input type="text" name="moviename" id="moviename" placeholder="Enter a movie...">
<br/>
<input type="button" name="search" value="Search" onclick="Search_Data()">
<br/>
<span id="response"></span>
</body>
</head>
</html>
get_data.php
(Below code is a trial code to see if its working)
<?php
echo "Hello World"
?>
In the browser,the result I am getting is:
The files are in the following location:
C:\Users\Admin\AppData\Roaming\MySQL\Workbench\scripts
The entire code is getting displayed instead of just "Hello World".I am new to web development and PHP and I am not sure what seems to be the problem.
what are you using is ajax with normal java-script i suggest to use jquery ajax and this is a full example how to connect it to php and how to get the value or list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
<td width="90%"><span id="employee_name"></span></td>
second
<input type="input" id="inputs" value="submit">
<p id="email"></p>
<p id="pass"></p>
<p id="permission"></p>
<script>
$(document).ready(function(){
$('#search').click(function(){
var val = document.getElementById("inputs").value;
var id= $('#employee_list').val();
setInterval(function(){
$.ajax({
url:"db.php",
method:"POST",
data: {val : val},
dataType:"JSON",
success:function(data)
{
$('#email').text(data[val].email);
$('#pass').text(data[val].pass);
$('#permission').text(data[val].perm);
}
})
}, 1000);
});
});
</script>
</body>
</html>
the php file
<?php
$items = array();
$url="localhost";
$user= "root";
$pass="";
$dbname="test";
$value= 0;
if(isset( $_POST['val'])){
$value= $_POST['val'];
}
$num=0;
$connect=mysqli_connect($url,$user,$pass,$dbname);
$result="SELECT email,pass,permission FROM test where id=$value";
$sql=mysqli_query($connect,$result);
while($row=mysqli_fetch_assoc($sql) ){
/* add a new item */
$num++;
$items[$value] = array(
'email' => $row['email'],
'pass' => $row['pass'],
'perm' => $row['permission']
);
}
$json_response = json_encode($items);
echo $json_response;
?>

How to handle google recaptcha with jquery?

i need a little info on google recaptcha. I want to grab the value of "g-recaptcha-response" that compares in the captcha.php file i inserted below in my jquery file and then send it to the captcha.php file using jquery $.post() method. I apologize if this is duplicate but i really cannot find someone with my same problem ;)
THE HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="handle_spam.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div class="g-recaptcha" data-sitekey="6Lf8LxIUAAAAALg93pw24l53KTeqrIwl7kUY-opk"></div>
<button id="go">Register</button>
</body>
</html>
THE PHP
<?php
$captcha=$_POST['g-recaptcha-response'];
echo $captcha;
if(!$captcha){
echo 'You must verify yourself';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Lf8LxIUAAAAACB9iqeOermR-rPOW0zcWRfoetBO&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'abort_all';
}else
{
echo 'success';
}
?>
THE JS
$(document).ready(function(){
$('#go').click(function(){
send=$('')
$.post('captcha.php',function(data){
alert(data);
});
});
});
Use this
<div class="g-recaptcha" data-callback="captchaCallback" data-sitekey="...">
and provide the function:
function captchaCallback(response) {
alert(response);
}

AJAX is not working for me

I am trying to send AJAX but it is not working. Could someone please clarify what it is I am doing wrong or not doing. Just trying to figure this out.
FIRST PAGE.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="text-center">Button</div>
<input class="form-control" name="cartID" id="cartID" type="hidden" value="<?php echo $order['clientid'] ;?>">
<p id="edit_box"></p>
<script>
$("#scaleButton").click(function() {
var cartID = "hello"
var second = "second";
///////// AJAX //////// AJAX //////////
$.ajax({
type: 'POST',
url: 'testing1234.php',
data: {first:cartID,second:second},
success: function( response ){
alert('yay ajax is done.');
$('#edit_box').html(response);//this is where you populate your response
}//close succss params
});//close ajax
///////// AJAX //////// AJAX //////////
}
</script>
</body>
</html>
SECOND PAGE
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
echo $second;
?>
</body>
</html>
In your case, it's just a syntax issue. You forgot to close the click event with an ending parenthesis. This kind of problem can be easily avoided by using a text editor with linting. There are many out there, like Sublime Text, Atom, etc. Or as suggest in comment, open up developer console in your browser to check for any errors/warning.

Checkbox value insert into MySQL

Here is what my front end looks like. I have created checkbox for email on and off, and I would like to store this ON/OFF information in MySQL.
This is my PHP code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Better Check Boxes with jQuery and CSS </title>
<link rel="stylesheet" type="text/css" href="css123/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.tzCheckbox123/jquery.tzCheckbox.css" />
<script src="jquery123.js"></script>
<script src="jquery.tzCheckbox123/jquery.tzCheckbox.js"></script>
<script src="js123/script.js"></script>
</head>
<body>
<div id="page">
<form method="post" action="">
<br>
<ul>
<li><label for="ch_emails">Email notifications: </label><input type="checkbox" id="ch_emails" name="ch_emails" data-on="ON" data-off="OFF" value="1" CHECKED/></li>
</ul>
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_POST['ch_emails'])){
echo $check=$_POST['ch_emails'];
$sql=mysql_query("Update scott123.rahul_tbl_users set group=$check where Dingoid=$dingo");
if($sql==1){
echo "Checked";
}
else{
echo "Not Checked";
}}}
?>
</body>
</html>
### And here is my Javascript code
(function($){
$.fn.tzCheckbox = function(options){
// Default On / Off labels:
options = $.extend({
labels : ['ON','OFF']
},options);
return this.each(function(){
var originalCheckBox = $(this),
labels = [];
// Checking for the data-on / data-off HTML5 data attributes:
if(originalCheckBox.data('on')){
labels[0] = originalCheckBox.data('on');
labels[1] = originalCheckBox.data('off');
}
else labels = options.labels;
// Creating the new checkbox markup:
var checkBox = $('<span>',{
className : 'tzCheckBox '+(this.checked?'checked':''),
html: '<span class="tzCBContent">'+labels[this.checked?0:1]+
'</span><span class="tzCBPart"></span>'
});
// Inserting the new checkbox, and hiding the original:
checkBox.insertAfter(originalCheckBox.hide());
checkBox.click(function(){
checkBox.toggleClass('checked');
var isChecked = checkBox.hasClass('checked');
// Synchronizing the original checkbox:
originalCheckBox.attr('checked',isChecked);
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
});
// Listening for changes on the original and affecting the new one:
originalCheckBox.bind('change',function(){
checkBox.click();
});
});
};
})(jQuery);
I tried to write a code like this but the information email ON/OFF is not storing in database. I have created checkbox for email on/off, and I would like to store this ON/OFF information in MySQL, but the value is not getting stored.

Categories

Resources