Insert mySQL query if checkbox checked/not checked with PHP - php

During the process of trying to develop an checkbox activated mySQL query based on the value inside a checkbox i've incurred an problem which i can't get past, I've tried the following at the moment
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
The Javascript/Ajax code for the function "updateStatus" is as followed
function updateStatus(id,value) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
The PHP function inside functions/ajax.php
if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
echo "Checked";
} elseif($checked == false) {
echo "Not checked";
} else {
echo "Invalid response";
}
when using this code it always returned "Checked" any idea why ?

try this (code tested),
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
You will get second parameter as true or false;
function updateStatus(id,checked) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id+"checked="+checked, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
You PHP will be:
if(isset($check) and $check == 'update_status' and isset($_GET['id']) AND isset($_GET['checked'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
$query = mysql_query("SELECT * FROM `check_status` WHERE `user_id` = '$_SESSION[userid]' and `id` = '$id'");
else
//some other query
//Then i can insert the query based on if the checkbox checked or not.

Related

how to check already groupname is allow or not

I have form in that I have to check existing username. If username already exist then not allow to submit form. For that I have used ajax to check from submit. In this code It return true and instead of returning false it always return true and submit the form.
function lks()
{
var groupname = document.getElementById('groupname').value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(xmlhttp.responseText=="already"){
alert("Groupname Already in use");
return false;
}
}
};
xmlhttp.open("GET", "checkgroupname.php?groupname=" + groupname, true);
xmlhttp.send();
}
and my checkgrouname.php file is as below
<?php
session_start();
$loginuser = $_SESSION['username'];
$groupname = $_GET['groupname'];
$checkgroupname = trim(`sudo grep -w $groupname /home/$loginuser/.groupmanagement`);
if($checkgroupname!=NULL){
echo json_encode("already");
}
else{
echo json_encode("allow");
}
?>
Please tell any alternative method if possible.

XMLHttpRequest is not allowed by Access-Control-Allow-Origin

PHP:
<?php
header('Access-Control-Allow-Origin: *');
include_once("db_connect.php");
$username = '';
$video = '';
$rating ='';
if(isset($_GET["u"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
echo "No UserName";
}
if(isset($_GET["v"])){
$video= preg_replace('#[0-9]#i','',$_GET['v']);
} else {
echo "No Video ID";
}
...
?>
JavaScript:
function like(u,v) {
document.getElementById("rating").innerHTML="loading...";
var ajax = ajaxObj("POST","http://www.url.com/ratingphp.php");
ajax.onreadystatechange=function(){
if(ajaxReturn(ajax) === true){
document.getElementById("rating").innerHTML=ajax.responseText;
}
};
ajax.send("u="+u+"&v="+v+"&like");
}
function dislike(u,v) {
document.getElementById("rating").innerHTML="loading...";
var ajax = ajaxObj("POST","http://www.url.com/ratingphp.php");
ajax.onreadystatechange=function(){
if(ajaxReturn(ajax) === true){
document.getElementById("rating").innerHTML=ajax.responseText;
}
};
ajax.send("u="+u+"&v="+v+"&dislike");
}
function ajaxObj(meth,url){
var x= new XMLHttpRequest();
x.open(meth,url,true);
x.setRequestHeader("Content-type","application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
So as you can see I've allowed Access-Control-Allow-Origin in my PHP though I keep getting the error:
XMLHttpRequest cannot load http://www.url.com/ratingphp.php. Origin http://www.url2.com is not allowed by Access-Control-Allow-Origin. h37:1
Am I doing something wrong in my ajaxObj function with the setRequestHeader? First time doing a cross site php code. I'm just trying to figure out why my code is not executing correctly for the ACAO
just add this in PHP ..
header("Access-Control-Allow-Headers : Content-Type");
header("Access-Control-Allow-Methods : POST, OPTIONS");
header('Access-Control-Allow-Origin: *');

What is the value of ajax.responseText when there is no response being sent?

I wrote a javascript function that checks if a username is available in a database. If the username is NOT available the ajax send a text response back which changes some css and adds an error message. When the username is available the ajax doesn't send a response, which is fine but I just need to know what is being returned from ajax.responseText since there is no value. I've tried '' and null.
function _(x) {
return document.getElementById(x);
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function verifyEmail(){
var email = _("email").value;
var status = _("estatus");
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.signupform.email.value.search(emailRegEx) == -1) {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
status.innerHTML = "<br />Please enter a valid email address";
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
status.innerHTML = "";
if (email != "") {
status.innerHTML = "checking. . . ";
var ajax = ajaxObj("POST", "fan_signup_local.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
status.innerHTML = ajax.responseText;
console.log(status.innerHTML);
if (status.innerHTML !== '') {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
console.log(ajax.responseText);
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
}
}
}
ajax.send("email="+email);
}
}
}
There's always a response, unless the request times out. If the server script exits without printing anything, the response will be an empty string.

Checkbox always returning true in javascript/php

I'm trying to get the value of the checkbox using an Ajax/Javascript response which passes the value to PHP so i can perform a query based on the value ("Checked","Not checked")
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
The Javascript/Ajax code for the function "updateStatus" is as followed
function updateStatus(id,value) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
The PHP function inside functions/ajax.php
if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
echo "Checked";
} elseif($checked == false) {
echo "Not checked";
} else {
echo "Invalid response";
}
when using this code it always returned "Checked" any idea why ?
In the JS. value will be true or false. When you stringify either of those, you will get a string ('true' or 'false').
Thus $_GET['checked'] will be either "true" or "false" both of which == true.
To fix this on the PHP side, compare to the string "true" and the string "false"; not the boolean.
You are getting $_GET['checked'] as a String.
Change to something like:
if($checked == "true") {
echo "Checked";
} elseif($checked == "false") {
echo "Not checked";
} else {
echo "Invalid response";
}
This might help you in your answer https://stackoverflow.com/a/4228827/90648
You can try replacing the code
"&checked="+value
with
(value ? "&checked=true" : '')
This way you will only send the value true when it is checked, and not send anything (which you can check in PHP with isset)
or you can go with
(value ? "&checked=true" : '&checked=')
which will again, not send anything, thus empty string will be interpreted as false.

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

Categories