javascript prompt sent to php but output empty - javascript

I am trying to allow adding of a category to category dropdownlist by clicking the '+' button below it using ajax but my dropdownlist keeps disappearing instead.
HTML codes are as follows
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script>
function addCategory()
{
var category = prompt("Please enter new category: ", "");
if (category != null){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4){// && xmlhttp.status==200) {
document.getElementById("category").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","add_category.php?category="+category,true);
xmlhttp.send();
}
}
</script>
<script language="javascript" src="calendar/calendar.js"></script>
</head>
<body>
<?php
include ('db_conn.php');
session_start();
if(!empty($_REQUEST['event'])){
$event = $dbc->prepare("SELECT * FROM `COO_DEF_EVENT` WHERE EVENT_ID = :eventid;");
try{
$event->bindParam(':eventid', $_REQUEST['event']);
$event->execute();
$eventdet = $event->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $ex){
echo 'Error getting event data';
}
echo '<form id="form1" name="form1" method="post" action="editEvent.php">';
}else{
echo '<form id="form1" name="form1" method="post" action="addEvent.php">';
}
?>
Category:
<div id="category"><select name="categorydpl" id="categorydpl">
<?php
$categorySQL = $dbc->prepare("SELECT * FROM `CATEGORY` WHERE USER_ID = :userid; ");
try{
$categorySQL->bindParam(':userid', $_SESSION["userid"]);
$categorySQL->execute();
$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
foreach ($categoryList as $category){
echo '<option value="'.$category['CATEGORY_ID'].'">'.htmlspecialchars($category['CATEGORY_NAME']).'</option>';
}
}catch(PDOException $ex){
echo 'Error getting data';
}
?>
</select></div><button onClick="addCategory()">+</button>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit"
value="Submit" /><button onClick="location.href ='index.php';">Cancel</button>
</form>
</body>
</html>
PHP file
<?php
include ('db_conn.php');
session_start();
$category = $_GET['category'];
$print='category entered: '.$category;
$sql = $dbc->prepare("INSERT INTO `COO_CATEGORY` (`USER_ID`, `CATEGORY_NAME`) VALUES (:userid, :category_name);");
try{
$sql->bindParam(':userid', $_SESSION["userid"]);
$sql->bindParam(':category_name', $category);
$sql->execute();
}catch (PDOException $ex){
echo 'Insertion failed. Please try again';
}
$categorySQL = $dbc->prepare("SELECT * FROM `COO_CATEGORY` WHERE USER_ID = :userid;");
try{
$categorySQL->bindParam(':userid', $_SESSION["userid"]);
$categorySQL->execute();
$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
$print .= '<select name="categorydpl" id="categorydpl">';
foreach ($categoryList as $category){
$print.= '<option value="'.$category['CATEGORY_ID'].'">'.htmlspecialchars($category['CATEGORY_NAME']).'</option>';
}
$print.='</select>';
}catch(PDOException $ex){
echo 'Error getting data';
}
echo $print;
?>
When I open the php by typing .../add_category.php?category=sad
The page will display
"category entered: sad " followed by a dropdown list with sad inserted.
But when I try with the html file, the dropdownlist will disappear after I click the plus button and enter any value.
Any advice?
Thanks in advance!!!

Submit buttons submit forms. Submitting a form will reload the page.
Use <button type="button">

Try it with jQuery. In html file
$.ajax(
{
type: 'GET',
url: 'add_category.php',
dataType: 'json',
data: {'category' : category},
success:
function(answer){
$('#categorydpl').empty();
answer && answer.forEach(function(entry){
$('#categorydpl').append(new Option(entry['id'], entry['name']));
})
},
error:
function(){
console.log('Error');
}
}
);
and in your php file
$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
foreach ($categoryList as $category){
$result[] = array('id' => $category['CATEGORY_ID'], 'name' => htmlspecialchars($category['CATEGORY_NAME']));
}
echo json_encode($result);

Make sure your not doing a cross-site request (http://en.wikipedia.org/wiki/Same-origin_policy). When calling a page on a different domain with an ajax call, the browser doesn't allow it by default as a security measure.

Related

Retrieving large data amount as datalist from Remote PC

I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").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("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.

Passing php function through ajax to javascript

I am trying to create a page that will delete a user from my database when it is searched, ask for confirmation, and then delete it, i am extremely close but i need to pass the function through ajax to java script but im not understanding how to do that. Here is my code:
<html> 
<head> 
<?php
require_once('conn.php');
function deleteEmployee($conn, $employee, $table){
$query = "DELETE from $table where EmployeeName = '$employee'";
$confirmed = mysqli_query($conn, $query);
if ($confirmed){
echo "User Deleted";
}
else{
return True;
echo 'User has been deleted';
}
return;
}
//$query1 = 'select *
?>
<script>
function myFunction() {
var txt;
return confirm('Are you sure?');
if (confirm == true) {
deleteEmployee($conn, $name, "employee");//This is where i am having trouble
} else {
txt = "Okay";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</head>
<body>
<p id="demo"></p>
<form action="" method="post">
Search Name to be Deleted: <input type="text" name="term" /><br />
<button onclick="myFunction()" type="submit" value="Submit" />submit</button>
</form>
<?php
if (!empty($_POST['term'])) {
$term = mysqli_real_escape_string($conn,$_POST['term']);
$sql = "SELECT EmployeeName FROM employee ";
$r_query = mysqli_query($conn,$sql);
if($r_query->num_rows == 0){
echo "Name not in database";
} else{
while ($row = mysqli_fetch_array($r_query)){
$name = $row['EmployeeName'];
}
}
}
?>
</form> 
   
 
As of right now, the window pops up but when i press ok, nothing happens since i do not understand how to pass a function through ajax to javascript. Can someone help? If you need more info, let me know
How about using jQuery AJAX, storing your php functions in different files and just past post/get data so your PHP methods can process what you want to process?
Example Usage:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});

How do i display data in the same page while using a form in a html doc?

I've used javascript and php to get data from the database and then posting it on the same page. I've got the output for that. But when i'm using tag, the data is not being retrieved instead the page is just being refreshed and nothing happens. Can someone please help me in getting the output while using the tag. Thanks in advance.
HTML FILE:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter MMTI Number: <input type="text" name="EnrNo" id="EnrNo" /><br/><br />
<input type="submit" name="retrieve" value="submit" id="EnrNo-sub" />
<div id="EnrNo-data"></div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$('#EnrNo-sub').on('click', function() {
var EnrNo = $('input#EnrNo').val();
if (EnrNo != '') {
$.post('retrieve.php', {EnrNo: EnrNo}, function(data) {
$('div#EnrNo-data').html(data);
});
}
});
</script>
</body>
</html>
PHP FILE:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno())
{
die("connection couldn't be established");
}
if(isset($_POST['EnrNo']) === true && empty($_POST['EnrNo']) === false) {
//$Enr = $_POST['EnrNo'];
$EnrNo = mysql_real_escape_string ($_POST['EnrNo']);
$query = "Select * FROM cert WHERE EnrNo = '$EnrNo'";
$result = $db->query($query);
$total_num_rows = $result->num_rows;
while ($row=$result->fetch_array())
{
echo "Enr. No: MMTI- " .$row["EnrNo"].'<BR />';
echo "Name: " .$row["Name"].'<BR />';
echo "Batch Code: " .$row["Batch Code"].'<BR />';
echo "Start Date: " .$row["Start Date"].'<BR />';
echo "End Date: ".$row["End Date"].'<BR />';
echo "Course: " .$row["Course"].'<BR />';
echo "Duration: " .$row["Duration"].'<BR />';
} mysqli_free_result($result);
} else {
echo ('Data not found');
};
?>
You need to stop form from submitting and refreshing page:
You can use event.preventDefault() or return false on your event handler.
$(document).ready(function () {
$('#EnrNo-sub').on('click', function (e) {
e.preventDefault(); // Stop default action of submit form
var EnrNo = $('input#EnrNo').val();
if (EnrNo != '') {
$.post('retrieve.php', {
EnrNo: EnrNo
}, function (data) {
$('div#EnrNo-data').html(data);
});
}
});
});
You could use a button instead of a submit for your button-element, or you could prevent the default action for the button in your click-Event handler:
$('#EnrNo-sub').on('click', function(ev) {
ev.preventDefault();
var EnrNo = $('input#EnrNo').val();
if (EnrNo != '') {
$.post('retrieve.php', {EnrNo: EnrNo}, function(data) {
$('div#EnrNo-data').html(data);
});
}
});
You need to stop page refresh. Your data is not updated because of page refresh.
$('.click').click(function(e){
e.preventDefault();
})

Redirection in an ajax called page

I have read quite a bit and I still am missing something.
I have a page that has a button on it. When you click the button it will call an AJAX function that will then wait and refresh every 5 seconds in waiting for a MySQL database change. Once the change in the database is made, I would like to take the user to a new page all together.
I have tested the refreshing for the database changes and they work great with echos. I have tried to use windows.location and the php header redirect. Neither are working.
I am not using jquery for the ajax call. Any help would be greatly appreciated.
Thank you
code:
index.php
<?php
session_start();
$_SESSION = array(
'player' => 0
);
?>
<!DOCTYPE HTML>
<html>
<head>
<script src="ajax.js"></script>
<title></title>
</head>
<body>
<div id="join"><button type="button" onclick="startGame()">Throwdown!</button></div>
</body>
</html>
rpsjoin.php
<?php
include("db.php");
session_start();
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$gameStatus_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT game.game_status FROM game WHERE game.id =' . $lastId));
$gameStatus = $gameStatus_q['game_status'];
if ($gameStatus == 2) {
mysqli_query($con, "INSERT INTO game (game_status, player1_joined) VALUES(1,1)");
$_SESSION['player'] = '1';
$playerNumber = $_SESSION['player'];
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$_SESSION['lastId'] = $lastId;
} elseif ($gameStatus == 1 && $_SESSION['player'] != 1) {
mysqli_query($con, "UPDATE game SET player2_joined = 1 WHERE id = " . $lastId);
$_SESSION['player'] = '2';
$playerNumber = $_SESSION['player'];
$_SESSION['lastId'] = $lastId;
}
$player1_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player1_joined FROM game WHERE game.id =' . $lastId));
$player2_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player2_joined FROM game WHERE game.id =' . $lastId));
$player1_join = $player1_join_q['player1_joined'];
$player2_join = $player2_join_q['player2_joined'];
echo $lastId . "<BR>";
echo $gameStatus . "<BR>";
echo $player1_join . "<BR>";
echo $player2_join . "<BR>";
if ($player1_join == 1 && $player1_join == $player2_join) {
echo '<form action="rpsover.php" method="post">
<button type="submit" name="player" value="1">Rock</button>
<button type="submit" name="player" value="2">Paper</button>
<button type="submit" name="player" value="3">Scissors</button>
</form>';
} else {
echo "Locating player. Please be patient";
}
echo session_id();
?>
function startGame() {
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("join").innerHTML=xmlhttp.responseText;
setTimeout('startGame()',1000);
}
}
xmlhttp.open("GET","rpsjoin.php",true);
xmlhttp.send();
}
At the end of rpsjoin.php, instead of showing a form, i want to be redirected to another page.
Yes I know my code is bad and there are test echos in it.
Thank you

AJAX, jQuery, javascript for a chatroom

So I was following a tutorial and I came across the current problem. This is my first time using the ajax method. I copied and saved jQuery version 1.7.2.min.js in a folder. My php code seems to be working fine, the only thing that seems off is the code for the ajax part.
This code is in a folder called "includes"
<div id="messages">
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
This is the javascript in a folder called "script" named auto_chat
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'script/Chat.php' ,
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
There is a file called Chat.php containing code that links to the database.
When it runs it should show all the messages inside of the database. Instead it gives me blank and not even errors. Can someone tell me whats wrong with my method?
This is the my Chat.php
<?php
require('../includes/database/connect.db.php')
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
And this is all of my index.php
<!DOCTYPE html>
<?php
require('includes/core.inc.php');
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
?>
<html lang = "en">
<head>
<!--Page TItle --!>
<title>Chat Application </title>
<link type="text/css" rel= "stylesheet" href= "includes/main.css" />
</head>
<body>
<div id="input">
<form action = "index.php" method = "post">
<label>Enter Name:<input type = "text" name = "sender"/></label>
<label>Enter Message:<input type = "text" name = "message"/></label><br />
<input type = "submit" name = "send" value = "Send Message"/>
</form>
</div>
<div id="messages">
<?php
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
</body>
</html>
After a lot of trial and error, we found out that the problem was a simple missing semicolon on chat.php:
require('../includes/database/connect.db.php');
:)

Categories

Resources