Captcha php to js validation - php

I have written in php I want to write this code, but there is an error in the function onclick javascript
<?php
if(isset($_POST["captcha"]))
{
if($_POST["captcha"]==$_SESSION["code"])
{
echo "Correct";
}
else
{
echo "Not Correct";
}
}
?>
Javascript
function ja_k2filter_submit()
{
var captcha = $('captcha');
var code = $('code');
if ($code = '');
{
alert("Güvenlik Kodunu Doğrulayınız!");
}
return false;
if ($code = captcha);
if($('input_searchword'))
{
input = $('input_searchword');
v_label = ($$('label[for=input_searchword]')[0].innerHTML)+'...';
if((input.value !='')&&(input.value!=v_label))
{
$('mod_ja_searchword').value =input.value;
}
}
javascript values ​​but does not

Related

responseText is working but responseXML is null

I am trying to open an XML file with Ajax. Its responseText is working fine but responseXML is returning null. I checked the syntax, there is nothing wrong with the syntax. I don't know what the problem is. Here is my code...
My HTML code
<div id='albumBox'>
<input type='file' multiple name='newsfeedAlbum[]' id='newsfeedAlbum' onchange='uploadNewsfeedImages()' />
</div>
<div id='uploadingImages'>
<progress id='newsfeedImageProgressBar'></progress>
</div>
<div>
<input type='button' id='albumButton' value='post' />
</div>
my JavaScript code…
function uploadNewsfeedImages()
{
//alert("loaded");
var files = document.getElementById("newsfeedAlbum").files;
var formData = new FormData();
var unixTimeStamp = Math.floor(((new Date).getTime())/1000);
formData.append("action","post");
formData.append("thing","album");
formData.append("unixTimeStamp",unixTimeStamp);
formData.append("album_to","news_feed");
for(var i = 0;i < files.length;i++)
{
var file = files[i];
//alert("file name is "+files.item(i).name);
formData.append("albumImages[]",file);
}
var xhr = new XMLHttpRequest();
xhr.open("POST","add_newsfeed.php",true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
//alert(xhr.responseText);
alert(xhr.responseXML);
}
}
xhr.upload.onprogress = function(event)
{
showProgress(xhr,event);
}
xhr.send(formData);
}
function showProgress(xhr,event)
{
var uploaded = event.loaded/event.total;
uploaded = Math.floor(uploaded*100);
//alert(uploaded);
document.getElementById("newsfeedImageProgressBar").value = uploaded;
}
Here is my php code...
session_start();
echo '<?xml version="1.0" encoding="UTF-8"?>';
header("Content-type: text/xml");
if(isset($_POST))
{
echo "<newsfeed>";
$action = $_REQUEST["action"];
if($action == "post")
{
$thing = $_REQUEST["thing"];
if($thing == "text")
{
}
elseif($thing == "album")
{
$succeded = array();
$failed = array();
$targetFolder = "images/";
$extensions = array("jpeg","jpg","bmp","png","gif");
foreach($_FILES["albumImages"]["name"] as $key=>$value)
{
//echo $key."=>".$value."<br />";
if($_FILES["albumImages"]["error"][$key] === 0)
{
$extension = strtolower(pathinfo($value,PATHINFO_EXTENSION));
if(in_array($extension,$extensions))
{
$source = $_FILES["albumImages"]["tmp_name"][$key];
$destination = $targetFolder.basename($value);
if(move_uploaded_file($source,$destination))
{
$succeded[] = $value;
}
else
{
$failed[] = $value;
}
}
else
{
$failed[] = $value;
}
}
else
{
$failed[] = $value;
}
}
if(count($succeded)>0)
{
echo "<succeded>";
for($i=0;$i<count($succeded);$i++)
{
echo "<succeded_file>".$succeded[$i]."</succeded_file>";
}
echo "</succeded>";
}
if(count($failed)>0)
{
echo "<failed>";
for($i=0;$i<count($failed);$i++)
{
echo "<failed_file>".$failed[$i]."</failed_file>";
}
echo "</failed>";
}
}
}
echo "</newsfeed>";
}
?>
It's probably because the content type of the file coming back from the sever is not xml.
Try using header('Content-Type: text/xml'); in your PHP code.

Ajax + PHP validation and call Javascript function inside PHP validation

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.
Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>
Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}
You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

Insert mySQL query if checkbox checked/not checked with 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.

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.

PHP $_GET with jQuery $.get call

I am currently learning jQuery and php.
So I have this php file that gets called with a jQuery function (there is another call somewhere else in the script where a=chkPw):
$.get("checkName.php?a=chkUser&user=" + rqUser, function(data) { ... });
My problem is that the php script doesn't seem to get in the if(isset($_GET)) { } block. I have debugged the value that it returns (1), so I don't understand what's wrong! I have also debugged the value for $_GET['a'] and it is indeed 'chkUser'.
Any help would be greatly appreciated.
<?php
$users = array('bill' => 'ore', 'ted' => 'wood');
if (isset($_GET)) {
if ($_GET['a'] == 'chkUser') {
if (!array_key_exists($_GET['user'], $users)) {
echo 'okay';
} else {
echo 'denied';
}
} elseif ($_GET['a'] == 'checkPw') {
$user = $_GET['user'];
$pw = $_GET['pw'];
$i = 0;
// get username id
foreach (array_keys($users) as $value) {
if ($value == $user) {
$user = $users[i];
}
i++;
}
// match pw
if ($pw == $user) {
echo 'okay';
} else {
echo 'denied'
}
}
}
?>
Hey it seems to me that this is working:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$.get("checkNames.php?a=chkUser&user=bill", function(data) { console.log(data) });
$.get("checkNames.php?a=chkPass&user=bill&pw=ore", function(data) { console.log(data) });
</script>
<?php
$users = array('bill' => 'ore', 'ted' => 'wood');
if (isset($_GET["a"])) {
if ($_GET["a"] == 'chkUser') {
if (!array_key_exists($_GET['user'], $users)) {
echo 'okay';
} else {
echo 'denied';
}
} elseif ($_GET["a"] == 'chkPass') {
$user = $_GET['user'];
$pw = $_GET['pw'];
if(array_key_exists($user, $users))
{
if($users[$user] == $pw)
{
echo "okay";
}
else
{
echo "denied";
}
}
else
{
echo "denied";
}
}
}
?>
Try this if statement instead of current
if (count($_GET) > 0) {
// existing code
}
Hope this will help you.
With a url like www.something.com/index.html?a=1 This code does in fact work on testing:
$users = array('bill' => 'ore', 'ted' => 'wood');
if (isset($_GET)) {
echo 'something';
}
Try commenting it down further to let us know if it is the whole whole elseif or just a part of it
You could try this:
<?php
if(!empty($_GET)){
...
}
?>
To be sure about the GET payload use var_dump($_GET)

Categories