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']; ?>";
Related
I have
function delImage(posteId,imagebinId) {
$.get("<?php echo base_url('/Home/deletePostimage/') ?>");
return false;
}
i want to be like /Home/deletePostimage/posteId/imagebinId
i tried
$.get("<?php echo base_url('/Home/deletePostimage/')+posteId+"/"+imagebinId ?>");
but it divide the two numbers
like posteId=5 imagebinId =2
the results will be
/Home/deletePostimage/2,5
the params from
<a class="postimgsd" onClick="if(confirm('Are you sure you want to delete this image ?')){delImage(<?php echo $value['id'],$get_images[0]['binId']; ?>); rmItem(<?php echo $i; ?>);}else{} ; " >
With ES6, you can do this with string interpolation:
$.get(`<?php echo base_url('/Home/deletePostimage/${postId}/${imagebinId}') ?>`);
Without ES6, there is another answer that answers it, or use this:
var url = '/Home/deletePostimage/' + postId + '/' + imagebinId;
$.get("<?php echo base_url('" + url + "') ?>");
Furthermore, the code that calls this function should actually be:
<a class="postimgsd" onClick="checkDeletion()" />
<script type='text/javascript'>
function checkDeletion() {
if(confirm('Are you sure you want to delete this image ?')) {
var postId = <?php echo $value['id']; ?>;
var imagebinId = <?php echo $get_images[0]['binId']; ?>;
delImage(postId, imagebinId);
rmItem(<?php echo $i; ?>);
}
}
</script>
You need to keep in mind that PHP is processed on back-end before send the html to your user browser. That said, everything between php tags (<?php ... ?>) is rendered/processed before javascript even exists.
So if you put any JavaScript code inside your PHP code it won't work.
To make it work and be clean, do something like this:
function delImage(posteId,imagebinId) {
let url = "<?php echo base_url('/Home/deletePostimage/') ?>";
$.get(url + posteId + "," + imagebinId);
return false;
}
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
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'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
?>
I am trying to run a update to mysql when a link in a table is clicked.
For this I have made 3 files:
movies.php
<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script src="video.js" type="text/javascript"></script>
</head>
<?php
include 'combo_new.php';
include 'config.php';
include 'opendb.php';
$ndate = $_POST['ndate'];
$result = mysql_query("SELECT *
FROM DayMovie
WHERE FileDate LIKE '$ndate%' ORDER BY FileDate DESC")
or die(mysql_error());
echo "<table border='0'>";
echo "<tr> <th>Dato</th><th>Visninger</th><th>Handling</th></tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo date('d.m.Y', strtotime($row['FileDate']));
echo "</td><td>";
echo $row['Counter'];
echo "</td><td>";
echo "<a href='alldaymovies/{$row['FileName']}' onclick='playVideo(this.href, {$row['FileName']});' onkeypress='playVideo(this.href, {$row['FileName']});'>Se film</a>";
echo "</td></tr>";
}
echo "</table>";
include 'closedb.php';
?>
</html>
video.js
function playVideo(filename)
{
$.post( "update.php" {"filename":filename},
function( data ) {
alert( "Data Loaded: " + data );
});
}
update.php
<?php
include 'config.php';
include 'opendb.php';
$filename = $_POST['filename'];
$result = mysql_query("UPDATE DayMovie SET Counter=Counter+1 WHERE FileName='$filename'")
or die(mysql_error());
include 'closedb.php';
?>
However theres something not correct here... Can anyone see where I am going wrong?
The problem is probably that your user is already redirect to the other page before the call to update.php got finished. Keep in mind that if you redirect the browser to another page that request that are busy get cancelled.
To test if this is really the problem try to replace the href of the "a" element with "#".
And change your playVideo function to look like this:
function playVideo(filename)
{
$.post( "update.php" {"filename":filename},
function( data ) {
alert( "Data Loaded: " + data );
setTimeout(function(){ document.location.href="alldaymovies/" + filename;}, 300);
});
}