Undefined $_POST after xmlhttp request - javascript

My code makes an xmlhttp request to a php file, sending an ID so that a record can be identified and deleted from the database. However, when performing the delete query, I'm get an error saying 'comicID' is undefined (the variable using the ID value sent by POST). I'm not sure how to make sure it is defined correctly. Currently, the error I'm getting back from error handling is: "No comic supplied." and the error I get when removing the ISSET section of code is: "Error. Pages in comic not deleted." As it stands, the delete query doesn't work.
Javascript:
function delComic()
{
var radioButtons = $("#listID input:radio[name='comicList']");
var radioID = radioButtons.index(radioButtons.filter(':checked'));
console.log(radioID);
if (radioID < 0)
{
window.alert("You must select a comic before deleting.");
}
else
{
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php?comicID="+radioID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
}
PHP:
<?php
if (isset($_POST["comicID"]))
{
$comic = $_POST["comicID"];
$dir = 'comics/'.$comic.'/';
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
include_once('includes/conn.inc.php');
mysqli_query($conn, "DELETE FROM serieslink WHERE comicID = '$comic'");
$query = ("DELETE FROM page WHERE comicID = '$comic'");
if (!$result = mysqli_query($conn, $query))
{
echo ("Query1 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
$dirHandle = opendir($dir);
while($file = readdir($dirHandle))
{
if(!is_dir($file))
{
unlink("$dir"."$file");
}
}
closedir($dirHandle);
rmdir($dir);
$query2 = ("DELETE FROM comic WHERE comicID = '$comic'");
if (!mysqli_query($conn, $query2))
{
echo ("Query2 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
echo ("The selected comic was successfully deleted.");
}
else
{
echo ("Error. Comic not deleted.");
}
}
}
else
{
echo "Error. Pages in comic not deleted.";
}
}
$conn->close();
}
else
{
$comic = null;
echo "No comic supplied";
}
?>

With POST you do your Ajax request different that with GET. The query string is an argument to the send() function rather than part of the url, and you leave off the ?:
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send("comicID="+radioID);
Edit:
You also really should urlencode the parameter values, if they can contain spaces, etc. And to circumvent possible browser caching you can add a parameter with the time:
var d = new Date();
xmlhttp.send("comicID="+encodeURIComponent(radioID)+"&ts="+d.getTime());
There's no need to read that timestamp param on the server-side; its only to trick the browser.

Change the three first lines to, and everything should work fine.
if (isset($_GET["comicID"]))
{
$comic = $_GET["comicID"];

I actually solved it myself by accident. It turns out the error is that the program is halting at the point that it tries to delete all pages associated with a comic. When it is presented with an already empty comic, it tries to delete nonexistent records. Manually adding a page to the comic and THEN trying to delete the comic outright worked perfectly.
So basically, I just need error handling for empty comics.
Thanks for the pointers regarding POST, however.

Related

javascript ajax login form handling

Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>
Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>
do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}

Update a php variable with AJAX Javascript

I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";

Chat system using Mysqli, PHP and AJAX is inserting blank message into Database

I've hit a brick wall in my chat system project and I have tried all day to find a solution. So here I am.
In the file insert.php I am trying to use $_REQUEST to get the value of the textarea from chat.php.
When I type something in and click send, a blank message is sent to the database.
After playing around with it, sometimes the webpage displays a "1" in the div element im trying to display the message in.
Any help would be very much appreciated thank you.
chat.php
<!DOCTYPE html>
<html>
<head>
<title>{ Chat App }</title>
<link rel = "stylesheet" href = "styles/style.css" media = "all" />
<script src="insert.js"></script>
<link href='https://fonts.googleapis.com/css?family=Rokkitt' rel='stylesheet' type='text/css'>
</head>
<body>
<form name = "form1">
<textarea name = "message"></textarea>
<br>
Send
<br>
<div id = "msg"></div>
</form>
</body>
</html>
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
insert.php
<?php
include("connection/connection.php");
global $con;
$msg = isset($_REQUEST['msg']);
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
$get_msg = "SELECT * FROM msg ORDER by id DESC";
$run_msg = mysqli_query($con, $get_msg);
while($row = mysqli_fetch_array($run_msg)){
echo $row['message'];
}
?>
The first problem is when you check for the null value, the function continues and submits the form if it is null or not.
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
// stop the submit action
return;
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
The next problem is in the form handler, you are saving a boolean value isset($_REQUEST['msg']). Try this
insert.php
...
$msg = (isset($_REQUEST['msg']) && !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : false;
if($msg){
// save data to database
...
}
or
...
if((isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
// message was submitted and it is not an empty string
$msg = $_REQUEST['msg'];
// save data to database
...
}else{
// do nothing
}
xmlhttp.open('GET', 'insert.php', true); try changing to xmlhttp.open('GET', 'insert.php?msg='+msg, true);
Hope it helps !
better to add "return" on error when you check if message is empty
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
so it could be
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
return;
}
in submit() function
so the rest of function will not execute and empty message won't be sent.
and assign to variable message not the validation ))
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
$msg = $_REQUEST['msg']; //addiotionally this need escape
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
}

how to handle php echo'ed message in ajax.

I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}

JavaScript/AJAX is saying "undefined" when it should show a picture

On my register page, I am trying to set it up so that when somebody enters a username into the username box, it will either show a green check mark if the username doesn't exist, or a red 'X' if the username already exists. When the page loads though (the body tag is <body on_load="process();">), it doesn't come up with a picture, it comes up with the word "undefined".
JavaScript code:
var xmlHttp = createXmlHttpRequestObject();
//Create object for function
function createXmlHttpRequestObject(){
var xmlHttp;
//Check if IE
if(window.ActiveXObject){
try{
//Setting variable equal to object for IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}else{
//Anything not IE
try{
//Want to use this object if not IE
xmlHttp = new XMLHttpRequest;
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}
//If couldn't set object
if(!xmlHttp){
//Tell people that JS couldn't create the object (new XMLHttpRequest or ActiveXObject)
alert("Couldn't create an object with JavaScript!");
}else{
//Return object
return xmlHttp;
}
}
//Use this attribute for body tag: <body onload="process()">
function process(){
/*readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
*/
try{
//Check if ready to communicate
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//<input type="text" id="userInput" /> relates to this
//Set variable to value they typed in
username = encodeURIComponent(document.getElementById("register_name").value);
//Creates request to send to server
//Need PHP file, GET would be in PHP file, also can be POST, etc.
xmlHttp.open("POST","functions/check_used.php",true);
//Doing something to make it pretend like it's a form, for POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Handle server response when server responds to the request
xmlHttp.onreadystatechange = handleServerResponse;
//Send request (this is used for POST, use null when using GET)
xmlHttp.send("username="+username);
}else{
//Not ready to communicate, wait for 1 second and try again
setTimeout('process()',1000);
}
}catch(e){
//Something doesn't work, tell them what happened
alert(e.toString());
}
}
//When response received, tells what to do with it
function handleServerResponse(){
//Response done communicating
if(xmlHttp.readyState==4){
//Communication went OK
if(xmlHttp.status==200){
//Put response into variable
xmlResponse = xmlHttp.responseXML;
//Get document element
xmlDocumentElement = xmlResponse.documentElement;
//Get data from XML file
message = xmlDocumentElement.firstChild.data;
//Access document, put it in element on page, innerHTML is stuff shown on webpage
document.getElementById("checkedUser").innerHTML = message;
//Pause 1 second before communicating with server again
setTimeout('process()',1000);
}else{
//There was an error with data
alert('Something went wrong!');
}
}
}
On the register page, I have an input box with the div next to it:
<input type="text" id="register_name" name="username" /><div id="checkedUser"></div>
Finally, I have the PHP file that it is posting to:
<?php
require_once('../includes/db.php');
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<username>';
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
echo '</username>';
?>
I have tried troubleshooting it, but I couldn't figure out what was wrong.
Listen for keystrokes in input, and check username when the input changes :
$(function() {
$('#register_name').keyup(function() {
$.ajax({
type: 'POST',
url : 'functions/check_used.php',
data: {username : this.value},
success: function(result) {
$('#checkedUser').html(result);
}
});
});
});
And there's no need to return XML:
<?php
require_once('../includes/db.php');
header('Content-Type: text/html');
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
?>
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
should be
if(xmlHttp.readyState== 4 && xmlHttp.status == 200){

Categories

Resources