Hello guys I have this code that displays mysql data in a table,which it does, I want to take the data from the cells,which it does, and use an ajax request to post the data to a php file,which it doesn't, and the data retrieved to be displayed in a paragraph tag,just for testing. When I take the cell data and post it to an alert in works.
What am I doing wrong
test.php
if(isset($_POST['searchbox'])){
$bloodonation =$_POST['searchbox'];
$multiple= explode(',',$bloodonation);
$var1 = $multiple[0]; // firstname
$var2 = $multiple[1]; // fathername
$var3 = $multiple[2]; // lastname /*bloodtype.blood_type='$var4' AND bodytype.bodytype='$var5' AND */
$_SESSION["firstname"] = $var1;
$_SESSION["fathername"] = $var2;
$_SESSION["lastname"] = $var3;
if(!empty($bloodonation)){
//$myfile = fopen("file.txt", "w");
//file_put_contents('file.txt',$bloodonation);
//fclose($myfile);
$bloodquery ="SELECT d.firstname AS donnerfirstname,d.fathername AS donnerfathername,d.lastname AS donnerlastname,bloodtype.blood_type,bodytype.bodytype,MAX(d.bloodonation_date)
FROM personprofile d,personprofile r,bloodtype,bodytype
WHERE r.firstname = '$var1' AND r.fathername='$var2' AND r.lastname= '$var3' AND r.bloodtype=d.bloodtype
AND d.hascancer='No' AND d.chronicdisease='No' AND d.autoimmunedisease='No' AND d.substanceabuse=1
AND d.hospitaladmission=134 AND d.health_issues='No'";
//$sql = "SELECT `firstname`, `fathername`, `lastname` FROM `personprofile` WHERE chronicdisease=\"No\" AND hascancer=\"No\" AND autoimmunedisease=\"No\"";
$bloodqr=mysqli_query($link,$bloodquery);
echo "<table>";
echo "<tr><th>Firstname</th><th>Fathername</th><th>Lastname</th><th>Blood type</th><th>Body type</th></tr> ";
while($row=mysqli_fetch_assoc($bloodqr)){
echo"<tr><td id='dfirstname'>";
echo $row['donnerfirstname'];
echo "</td><td id='dfathername'>";
echo $row['donnerfathername'];
echo "</td><td id='dlastname'>";
echo $row['donnerlastname'];
echo "</td><td id='dbloodtype'>";
echo $row['blood_type'];
echo "</td><td id='dbodytype'>";
echo $row['bodytype'];
echo "</td><td>";?><html><button onclick="outputdata()">Send Email</button></html> <?php
echo"</td></tr>";
}
}
} ?>
<!DOCTYPE html>
<html>
<head>
<script>
var donorfirstname = document.getElementById("dfirstname");
var dfn = donorfirstname.innerHTML;
var donorfathername = document.getElementById("dfathername");
var dfan = donorfathername.innerHTML;
var donorlastname = document.getElementById("dlastname");
var dln= donorlastname.innerHTML;
var donorbloodtype = document.getElementById("dbloodtype");
var dbt=donorbloodtype.innerHTML;
var donorbodytype = document.getElementById("dbodytype");
var dbot= donorbodytype.innerHTML;
function outputdata() {
$.ajax({
type: 'POST',
url: 'mytest.php',
data: {dofirstname: dfn,dofathername:dfan,dolastname:dln,dobloodtype:dbt,dobodytype:dbot},
success: function(data) {
$("#demo").html(data);}
});
//alert(dfn+dfan);//this works when uncommented
}
</script> </head>
<body>
<p id="demo"></p>
</body>
</html>
mytest.php
Uncaught ReferenceError: $ is not defined this error caused if you didn't include the jquery. In the code you showed, i didn't see the reference for jquery.
If you don't want to use jQuery then you have to do with the pure Javascirpt for your ajax request.
Refer https://www.w3schools.com/xml/xml_http.asp, https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
Related
I am trying to make some code where a click of a SQL html button can display a different SQL table as a popup. I have already gotten the variable from the table to pass through using this:
echo "<td><a class='btn-floating btn-large waves-effect waves-light black' onclick='partSearch(".$product.")' value='display'><i class='material-icons'>search</i></a></td>";
The 'part search' code is as follows:
<script type="text/javascript">
function partSearch() {
$.ajax({
url: 'serv.php?id=<?php echo $product ?>',
type: 'GET',
success: function(result){
var obj = jQuery.parseJSON(result)
alert(obj)
}
})
}
</script>
Even though the variable is passed through to 'serv.php', I can't manage to get the sql data to be returned as a popup using alert. All I get is either nothing or [object, Object]. This is the SQL/php code:
<?php
include 'includes/dbh.inc.php';
$id = $_GET['id'];
$result = mysqli_query($conn,"SELECT * FROM pr WHERE product_ID='".$id."'");// test this
$rows = array();
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
Any help is appriciated
<script type="text/javascript">
function partSearch() {
var product_id = "<?php echo $product; ?>";
$.ajax({
url: 'serv.php?id=product_id',
type: 'GET',
success: function(result){
alert(result);
}
})
}
</script>
I have cut this down to be a simple as possible. I create a typeahead variable that works perfectly.
but I need to pass two other variables $php_var1 and $php_var2 that are unrelated to the typeahead. The PHP variables are defined in
start.php. The typeahead script calls search_script.php then calls cart.php. cart.php is were I will need the two PHP variables to
be passed to. Thanks in advance for any help
start.php
<?php
$php_var1 = "my php variable 1";
$php_var2 = "my php variable 2";
?>
<script>
$(document).ready(function() {
var php_var1 = <?php echo $php_var1; ?>;
var php_var2 = <?php echo $php_var2; ?>;
$('#my_input').typeahead({
source: function(query, result) {
$.ajax({
url: "search_script.php",
method: "POST",
data: {
query: query
},
dataType: "json",
success: function(data) {
result($.map(data, function(item) {
return item;
}));
}
})
},
updater: function(item) {
location.href = 'cart.php?shop_name=' + item
return item
}
});
});
</script>
<form action="cart.php" action="post">
<input type="text" id="my_input" placeholder="Typeahead Search" />
</form>
search_script.php
<?php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = " SELECT * FROM all_shops WHERE p_shop_name LIKE '%".$request."%'";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["p_shop_name"];
}
echo json_encode($data);
}
?>
cart.php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
echo $php_var1;
echo $php_var2;
?>
You need quotes around the php output in order to generate javascript strings
var php_var1 = "<?php echo $php_var1; ?>";
var php_var2 = "<?php echo $php_var2; ?>";
Stackoverflow is an excellent resource, but sometimes you don't get the answer, so you need to persevere and keep trying. I worked on this all day yesterday and just couldn't figure it out. Woke up this AM and it came to me. The answer is as follows. In the typeahead script change the following line
location.href = 'cart.php?shop_name=' + item
to
location.href = 'cart.php?shop_name=' + item + '&php_var1=<?php echo $php_var1 ?>' + '&php_var2=<?php echo $php_var2 ?>'
I need help with returning values from jQuery/AJAX to html form inside index.php
index.php :
<script type="text/javascript">
$(document).ready(function () {
$('#display').ready(function () {
var pageid = '<?php echo $_GET[\'ID\'] ;?>';
var powiat = '<?php echo $row[\'powiat\'] ;?>'
$.ajax({ //create an ajax request to display.php
type: 'GET',
url: 'display.php?ID=' + pageid + '&powiat=' + powiat,
dataType: 'html', //expect html to be returned
success: function (response) {
$('#responsecontainer').html(response);
//alert(response);
}
});
});
});
(...)
echo "<form action=\"save.php\" method=\"GET\">";
echo "<tr><td>IP</td><td><div id=\"responsecontainer\"></td></tr>";
echo "<input type=\"submit\" value=\"Save\">" ;
echo "</table></form>
display.php file contains:
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
echo "<option value=\"".$disp_row_1['ip']."\">".$disp_row_1['ip']</option>";
}
In return I have filed html as expected but when I try submit form filed by jquery/ajax I have error
Notice: Undefined index: ip.
How can I handle with that?
Thanks.
Syntax error in your code when you are printing the option.
Updated code is as below.
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
?>
<option value="<?php echo $disp_row_1['ip'];?>" ><?php echo $disp_row_1['ip'];?></option>
<?php }
i have this code, now i want to send this $_SESSION['roll_id'] variable to another page menu.php where ajax function is written. how i send this variable to another ajax page for set data.
this is login.php page.
if($row["Login_Id"]==$username and $row["Login_Pass"]==$password)
{
echo "<h2 align='center'>" ."Login Sucessfull welcome" ." " .$row["Login_Id"]
."</h2>" ;
$_SESSION['roll_id']=$row['Roll_Id'];
//echo "ID" .$_SESSION['roll_id']; (give roll id)
header("Location: menu.php");
}
else
{
echo "<h2 align='center'>" ."Login Failed" ."</h2>";
}
this is menu.php page where whole functionality is written. i want to send rollid from this page to submenu.php where i can use this roll id in sql query.
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = '<?php json_encode($session); ?>';
$.ajax
({
type:'post',
url:'submenu.php',
data:{"roll_id":rollid},
success:function(response)
{
//console.log(response);
var menuArray= JSON.parse(response);
var html ="";
$.each( menuArray, function( key, value )
{
html += "<li><a href=''>" + value.Menu_Name + "</a>";
if(value.subMenu.length > 0)
{
console.log(JSON.stringify(value.subMenu));
html += "<ul>";
$.each( value.subMenu, function( key, subValue )
{
html += "<li><a href=''>" + subValue.text + "</a></li>";
});
html += "</ul>";
}
html += "</li>";
});
console.log(html);
if(response!="")
{
$("#main_menu").html(html);
}
}
});
});
this is submenu.php page
<?php
session_start();
include('config.php');
$roll_id = $_POST['roll_id'];
$q="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,b.Menu_Level,
b.MainMenu_ID, b.Menu_Order, b.Account_id,b.is_deleted from roll_menu AS a
join menu AS b on a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id;
$menu = mysqli_query($conn, $q);
$mainMenu = array();
foreach($menu as $x=>$value)
{
if($value['MainMenu_ID']==0)
$mainMenu[]=$value;
}
$menuData= array();
foreach($mainMenu as $y=>$value1)
{
$subMenu= array();
$m=$mainMenu[$y]['Menu_Id'];
$q1="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,
b.Menu_Level, b.MainMenu_ID, b.Menu_Order, b.Account_id,
b.is_deleted from roll_menu AS a join menu AS b on
a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id."and b.MainMenu_ID=$m";
$menu1 = mysqli_query($conn, $q1);
while($row=mysqli_fetch_array($menu1))
{
if($row["MainMenu_ID"]==$m)
{
$subMenu[]=array("text"=>$row["Menu_Name"]);
}
}
$value1["subMenu"] = $subMenu;
$menuData[] = $value1;
}
$menuDataJSON = json_encode($menuData);
echo $menuDataJSON;
now i attach the full code of submenu.php page.
Try like this may its helpful for you
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = "<?php echo $session; ?>"; //change here
alert(rollid)
$.ajax
({
type:'post',
url:'submenu.php',
data:{roll_id:rollid}, // change alse here
/*success: function (data) {
alert(data);
}*/
You echoed the <h2 ... on successful login and then used the header function to redirect. This will cause a warning `Warning: Cannot modify header information - headers already sent by” and redirection might not work.
As for AJAX, you need to echo the roll_id like this:
var rollid = '<?php echo json_encode($session); ?>';
I woudl also like to point out that since rollid is a single value, you dont really need to json_encode it.
1st : You missed to echo the variable .
2nd : if it's not a array no need json_encode
3rd : Before header function you will not echo any browser out put like html or echoing something will cause Warning: Cannot modify header information - headers already sent so take care about that .
4th : Try to put exit(); function after header function
header(....);
exit();
Js :
var rollid = '<?php echo $session; ?>';
just start_session() at top of page and try like this
var rollid = "<?php echo $_SESSION['roll_id']; ?>";
I'm currently doing a PHP page that displays bans and also gives an option to unban users.
I can't seem to get the button to work and run the query to unban. Any help would be much appricated.
It currently does nothing and I'm also unsure as to how to display the Pnotice errors as I get
Uncaught TypeError: Cannot read property 'required' of undefined
Here is the function listed in lightcms.php for banlist.php;
function banListAll() {
global $db;
$getBanListAllQuery = "SELECT * FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
echo "<tr id=\"banID" . $showBanListAll['id'] . "\">";
echo "<td>";
echo $showBanListAll['id'];
echo "</td>";
echo "<td>";
echo $showBanListAll['added_date'];
echo "</td>";
echo "<td>";
echo $showBanListAll['value'];
echo "</td>";
echo "<td>";
echo $showBanListAll['reason'];
echo "</td>";
echo "<td>";
echo $showBanListAll['expire'];
echo "</td>";
echo "<td>";
echo "<button data-id=\"" . $showBanListAll['id'] . "\" type=\"button\" class=\"btn btn-xs btn-danger btn-unban\">Unban</button>";
echo "</td>";
echo "</tr>";
}
}
Here is the javascript on banlist.php
<script type="text/javascript">
$(".btn-unban").click(function(){
var articleId = "#banID"+ $(this).attr("data-id");
var myData = "unban="+ $(this).attr("data-id"); //post variables
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "./engine/post/unban.php",
dataType:"json",
data: myData,
success: processJson
});
function processJson(data) {
// here we will handle errors and validation messages
if (!data.success) {
if (data.errors.required) {
new PNotify({
title: 'Uh oh!',
text: data.errors.required,
type: 'error'
});
}
} else {
new PNotify({
title: 'Success!',
text: data.message,
type: 'success'
});
$(articleId).fadeOut("slow");
}
}
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE users_bans WHERE id = '$id'";// Do Your Insert Query
if($db->query($insert)) {
echo '{"success":true,"message":"User was unbanned!"}';
} else {
echo '{"error":true,"message":"Sorry this has not worked, try another time!"}';
}
//Need to work on displaying the error^
?>
Your JS looks for "errors.required" but your PHP sends "error" with no required.
Here's some code edits that (IMO) clean up the code. (any changes to sql are based on the assumption that you're using mysqli. that assumption based on the use of ->fetch_assoc()) Please consider atlest the change to unban.php as what you currently have is open to sql injection
Your new banListAll function:
function banListAll() {
global $db;
// don't use SELECT * if you can help it. Specify the columns
$getBanListAllQuery = "SELECT id, added_date, value, reason, expire FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
$showBanListAll[] = "<button type='button' class='btn btn-xs btn-danger btn-unban'>Unban</button>";
// array_slice to get ignore the ['id']
echo "<tr data-banid='" . $showBanListAll['id'] . "'><td>" . implode("</td><td>", array_slice($showBanListAll,1)) . "</td></tr>";
}
}
New JS on banlist.php
<script type="text/javascript">
function processJson(data) {
// here we will handle errors and validation messages
if (data.error === false) {
row.fadeOut("slow");
}
// assuming we always get a "message"
new PNotify({
title : 'Uh oh!',
text : data.message,
type : 'error'
});
}
$(".btn-unban").click(function() {
var $this = $(this); // creating jQuery objects can be costly. save some time
var row = $this.closest('tr');
var banID = row.data('banid');
var postData = { unban: banID };
var formData = new FormData(this);
$.ajax({
type : "POST",
url : "./engine/post/unban.php",
dataType : "json",
data : postData,
success : processJson
});
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
// Don't just concat variables that came from users into your DB queries.
// use paramterized queries. If $db is a mysqli connection
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
$deleteStmt = $db->prepare($insert);
// if id is a number change "s" to "i" below
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
// add this function to return results to your JS functions
// should make it harder to put "errors" instead of "error" ;)
function jsonResult($hasErrors, $msg) {
return json_encode(array("error"=>$hasErrors,"message"=>$msg));
}
and just in case you thought unban.php was getting unnecessarily long, here it is without comments
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
if ($deleteStmt = $db->prepare($insert)) {
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
}
else {
print_r($db->error);
}
// the function should go into your general functions file
?>