How to PHP_SELF in a UI dialog? - javascript

So I've been spending hours on finding something specific to my issue, but I can't seem to find any.
I'm in the middle of creating a small CMS. My problem is that I don't know how to make a submitted form in a UI dialog to do the action of PHP_SELF inside of the UI dialog. I have a list of user which can be selected by a radio button. There is a delete button which has some javascript attached:
$('#delete_user').on('click', function(e) {
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
e.preventDefault();
return false;
});
Now, my problem is that I have made it to the UI dialog where i get the ID sent with the url, but I have no idea how to send a form and still keep it in the dialog with the underneath PHP:
<?php
if ((isset($_GET['id'])) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
} elseif ((isset($_POST['id'])) && is_numeric($_POST['id'])) {
$id = $_POST['id'];
} else {
echo "<p>An error has occurred. Please try again.</p>";
echo "Close";
$jQuery_close = <<<msg
<script>
$('.close_dialog').on('click', function(){
location.reload();
dialog("close");
});
</script>
msg;
echo $jQuery_close;
exit();
}
require('includes/db_con.php'); //making a connection to the database
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') {
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) {
echo "<p>The user has been deleted</p>";
} else {
echo "<p>The user could not be deleted due to system error. Please try again.</p>";
}
} else {
echo "The user has NOT been deleted!";
}
} else {
$q = "SELECT email, CONCAT(firstname, ' ',lastname) AS name FROM users WHERE user_id='$id'";
$r = #mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if ($num = 1) {
while ($row = mysqli_fetch_array($r, MYSQL_ASSOC)) {
echo "<p>Are you sure you want to delete this user?</p>";
echo $row['email'] . '<br />';
echo $row['name'];
}
echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">
<input type="HIDDEN" name="id" value="' . $id .'" />
<input type="submit" name="sure" value="Yes" />
<input type="submit" name="sure" value="No" />
</form>';
} else {
echo "This page has been accessed in error";
}
}
mysqli_close($dbc);
?>
When pressing "yes" or "no" in the form, it just directly goes to a new page.
My question is, how do I fire the php and send the form within the dialog?

Place your e.preventDefault() at the start of the delete click handler, not at the end where you currently have it, it should be like this:
$('#delete_user').on('click', function(e) {
e.preventDefault();
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
return false;
});

Related

PHP Undefined index (caused by jquery file upload)

I've been trying to get a file-upload working for a website I'm working on. I'm doing this outside of a form, and after days of searching I finally found something that fits my method from the answer on this question:
The thing is, as soon as I applied the code to my own script, I got 'Undefined index' errors, and when I removed it, everything went fine.
Here is my code:
HTML
<div class='error-msg'></div>
<input type='text' id='newsitem-message' />
<input type='file' id='newsitem-thumbnail' />
<div class='submit' onclick='newsItem(\"insert\");'>Post news</div>
jQuery
function newsItem(action){
var thumbnail = $('#newsitem-thumbnail')[0].files[0];
var fileReader = new FileReader();
fileReader.readAsText(thumbnail, 'UTF-8');
fileReader.onload = shipOff;
function shipOff(e){
var r = e.target.result;
if(action == "insert"){
$.post("requestPages/newsitems.php", {message:$("#newsitem-message").val(),
thumbnail:thumbnail.name,
action:action,
data:r},
function(result){
console.log(result);
console.log(r); //This freezes my console/inspector window, forcing me to restart the browser-tab
if(result == "succes"){
window.location.reload();
}else{
$(".error-msg").html(result);
}
});
}else if(action == "delete"){
//To be implemented when I get the submit working D:
}
}
}
PHP (Please excuse the mess -needs serious cleaning)
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
echo print_r($_POST);
echo var_dump($_POST);
$message = $_POST['message'];
$action = $_POST['action'];
$thumbnail = $_POST['thumbnail'];
$data = $_POST['data'];
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
if($_POST['message'] != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "succes";
}
}else if($action == "delete"){
$sql = "";
}
?>
Does anybody see what's going wrong here? Or does anyone have an alternative option?
I hope someone can help me out with this issue.
Change it like this:
include("../assets/libs/SQLLib.php");
DB_Connect("test");
print_r($_POST); //Dont echo, what is already echoed
var_dump($_POST); //Dont echo, what is already echoed
$message = !empty($_POST['message'])?$_POST['message']:'';
$action = !empty($_POST['action'])?$_POST['action']:'';
$thumbnail = !empty($_POST['thumbnail'])?$_POST['thumbnail']:'';
$data = !empty($_POST['data'])?$_POST['data']:'';
if(!empty($thumbnail) && !empty($data)){
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
} else {
echo json_encode(array('error'=>'No data and thumbnail assigned'));
}
if($message != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "success";
}
}else if($action == "delete"){
$sql = "";
}
As well you only need to change error reporting level in .htaccess or php in order to prevent warning message to be displayed. In .htaccess:
php_flag error_reporting E_ERROR
If in .php file then
<?php error_reporting(E_RROR); //This displays only Errors, no warning and notices.
Hope you have tried using
isset($_POST) or isset($_POST['message']) if you get "Notice: Undefined index: message".
So in the end I opted out of a full jQuery-upload, and went for something else.
I am now uploading files purely through a PHP call, instead of a jQuery post event, with a small JavaScript check next to it to see if the form is submittable.
The code:
HTML
<div class='error-msg'></div>
<form method='post' action='requestPages/newsitems.php' enctype='multipart/form-data'>
News message
<textarea id='newsitem-message' name='newsitem-message' onchange='checkFormSubmit()'/>
<input type='file' name='newsitem-thumbnail' id='newsitem-thumbnail' />
<input hidden type='text' value='insert' name='newsitem-action'/>
<input class='submit' id='newsitem-submit' type='submit' value='Post news' disabled/>
</form>
PHP
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
var_dump($_FILES);
var_dump($_POST);
$message = $_POST['newsitem-message'];
$action = $_POST['newsitem-action'];
$errors= array();
$hasFile = false;
if($action == "insert"){
echo ($_FILES['newsitem-thumbnail'][0] == UPLOAD_ERR_NO_FILE);
if(isset($_FILES['newsitem-thumbnail']) && $_FILES['newsitem-thumbnail']['error'] != UPLOAD_ERR_NO_FILE){
$file_name = $_FILES['newsitem-thumbnail']['name'];
$file_size =$_FILES['newsitem-thumbnail']['size'];
$file_tmp =$_FILES['newsitem-thumbnail']['tmp_name'];
$file_type=$_FILES['newsitem-thumbnail']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['newsitem-thumbnail']['name'])));
$extensions= array("jpeg","jpg","png");
if(!in_array($file_ext,$extensions)){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
$hasFile = true;
}
if(empty($errors)){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$file_name."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
if($hasFile){
if(!move_uploaded_file($file_tmp,"../assets/images/thumbnails/".$file_name)){
echo "Moving the file failed!";
}
}
}
}else{
print_r($errors);
}
}else if($action == "delete"){
$sql = "";
}
?>
JavaScript
function checkFormSubmit(){
if($.trim($('#newsitem-message').val()) != ""){
$('#newsitem-submit').prop('disabled', false);
}else{
$('#newsitem-submit').prop('disabled', true);
}
}

How to get AJAX to show a success function and allow the page to update database results

I have the following code that I cannot figure out how to allow my AJAX call to send to my PHP file and then allow my page to show the changes on the page without submitting the form. The reason I need the page to not reload is to allow the success message to display.
What I am trying to do is approve a user and once they have been approved their name will show up in a different section of the page and then I want the success message to display after the changes have been made.
As of now everything works in my database and the status changes. Also the success message shows up where it is supposed to, but the user's name does not move until I reload the page.
How can I get all of this to work without reloading the page?
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
$pending_email = $row['email'];
?>
<form action="" method="POST" id="status">
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
?>
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button class="deny" type="submit" form="status" name="deny" value="<?=$pending_id;?>">Deny</button>
</form>
AJAX
$('.approve').click(function () {
$.ajax({
url: 'userRequest_approve.php',
type: 'POST',
data: {
id: $(this).val(), //id
status: 'Approved' //status
},
success: function (data) {
//do something with the data that got returned
$("#success").fadeIn();
$("#success").show();
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);
},
//type: 'POST'
});
return false;
});
UPDATE TO SHOW OUTPUTTED DATA
<h2>Approved User Requests</h2><br>
<div id="success" style="color: red;"></div><br>
$run2 = mysqli_query($con2,"SELECT * FROM user_requests ORDER BY id DESC");
$runUsers2 = mysqli_query($con2,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
Is it the same page you call from your ajax query and for the message success ?
You should use json in your php file, then you can check for any values you add in the callback like this:
userRequest_approve.php
<?php
header('Content-type: application/json');
echo '[{"success":1,"username","theusername"}]';
?>
script.js
$('.approve').click(function(){
$.post('userRequest_approve.php',$('#status').serialize(),function(data){
alert(data[0].success+' username='+data[0].username);
},'json');
return false;
});

form submitting twice in php

I have two appointment forms for new patients and already registered patients respectively,
mobile number is used as primary key.
So in the new patient registration we check if that mobile is already present, if yes then shows an error otherwise enter the new data into the tables.
However at present even when I enter a new mobile number it shows "already present" error and also enters the data into db.
so I thought the form was submitting 2 times, but i can't figure out at where this is happening.
my php file code snippet is:
if ($_POST['isnewpatient'] == "true") {
#$name = mysql_real_escape_string(trim($_POST['aaptntname']));
#$email = mysql_real_escape_string(trim($_POST['emlid']));
#$mobile = mysql_real_escape_string(trim($_POST['mobile']));
$qqcSql = "select * from " . WP_eemail_TABLE_SUB
. " where eemail_mobile_sub ='" . trim($_POST['mobile'])
. "' OR eemail_patient_id ='" . trim($_POST['mobile']) . "'";
$qqdata1 = $wpdb->get_results($qqcSql);
var_dump($qqdata1);
if (!empty($qqdata1)) {
$err = 1;
echo "<div id='message' class='aerror'>Already patient details exists. Use your existing patient ID !</div>\n";
}
else {
$pt_id = mysql_real_escape_string(trim($_POST['mobile']));
$sql = "insert query to WP_Appointment";
$wpdb->get_results($sql);
$sqls = "insert query to WP_Appointment_Contact";
$wpdb->get_results($sqls);
$sqql = " insert query to table WP_eemail_Table_Sub";
$wpdb->get_results($sqql);
echo "<div id='message' class='asuccess'>Request has been sent for appointment </div>";
}
}
else {
// Already registered patient form
}
<form name="FormEdit" action="<?php echo the_permalink(); ?>" method="post" onsubmit="return p_appointment()" class="aform">
/* Form part */
</form>
The javascript part
function p_appointment()
{
if($('input:radio[name=new_patient]:checked').val() == "new")
document.FormEdit.isnewpatient.value = "true";
if($('input:radio[name=new_patient]:checked').val() == "old")
document.FormEdit.isnewpatient.value = "false";
document.FormEdit.appsmssend.value = "true";
document.FormEdit.appemailsend.value = "true";
}
change your js method to this:
function p_appointment()
{
if($('input:radio[name=new_patient]:checked').val() == "new")
document.FormEdit.isnewpatient.value = true;
if($('input:radio[name=new_patient]:checked').val() == "old")
document.FormEdit.isnewpatient.value = false;
// document.FormEdit.appsmssend.value = "true";
// document.FormEdit.appemailsend.value = "true"; commented because i did not added these field while testing.
return document.FormEdit.isnewpatient.value;
}
this is what i used as form:
<form name="FormEdit" method="post" onsubmit="return p_appointment()" class="aform">
<input type="text" name="name"/>
<input type="submit" value="submit"/>
</form>
do not use:
if ($_POST['isnewpatient'] == "true") {
}
if ($_POST['isnewpatient'] == "false") {
}
use:
if($_POST['isnewpatient']) {
}else {
}

Checkbox Input doesn't work at all in chrome. Doesn't function in other browsers

Basically I want a checkbox to onClick change whether or not to show explicit content. I'll get right to the code HTML (and PHP):
</form>
<?php if (login_check($mysqli) == true) {
$username = $_SESSION['username'];
echo '
<form name="explicit">
<input type="checkbox" onClick="changeexplicit();" value="Filter Explicit Content" id="explicitcheckbox" ' ;
if (checkadult($mysqli,$username)!=1){echo "checked";}
echo ' /> <label for="explicitcheckbox" class="explicit">Filter Explicit Content</label>
</form>';}?>
Jquery: (i left the error handling blank because I didn't realize JQuery doesn't have a built in popup alert)
<script>
changeexplicit()
{
!(function($){
$(function() {
$.post('includes/changeadult.php', $('form[name="explicit"]').serialize(), function(data){
data = $.parseJSON(data);
if(data.success){
window.location.reload(true);
}
else if(data.error){
}
else{
}
});
});
})(window.jQuery);
}
</script>
PHP:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
$response = array();
if (login_check($mysqli) == true) {
$username=$_SESSION['username'];
$result=mysqli_query($mysqli,'SELECT isAdult FROM members WHERE username = "'.$username.'"');
$userinfo = mysqli_fetch_array($result);
$isAdult=$userinfo['isAdult'];
if ($isAdult==1)
{mysqli_query($mysqli,'UPDATE members SET isAdult=0 WHERE username="'.$username.'"');}
else{
{mysqli_query($mysqli,'UPDATE members SET isAdult=1 WHERE username="'.$username.'"');}}
$response['success'] = true;
}
else if(login_check($mysqli) == false) {
$response['error'] = true;
}
echo json_encode($response);
<script>
function changeexplicit(){
$.post('includes/changeadult.php', $('form[name="explicit"]').serialize(), function(data){
data = $.parseJSON(data);
if(data.success){
window.location.reload(true);
}else if(data.error){
}else{}
});
}
</script>
Try change onClick toonchange?

having multiple buttons in one form and every button should be able to update database

Hi Friends please tell me where I am wrong cause the database is still unchanged even though update query is executed successfully
Thank you
here is the form code
echo'<form action="processor.php" method="post" id ="post_form">';
echo '<input type="hidden" name= "status" id="status" value="">';
$upload_arr=array("1");
foreach($upload_arr as $upload_id)
{
echo '<input type="button" name="accept-<?=$upload_id?>" value="accept" onclick="submit_this(this.name)"/><br>';
echo '<input type="button" name="reject-<?=$upload_id?>" value="reject" onclick="submit_this(this.name)"/><br>';
echo '<input type="button" name="saccept-<?=$upload_id?>" value="saccept" onclick="submit_this(this.name)"/><br>';
echo '<input type="button" name="sreject-<?=$upload_id?>" value="sreject" onclick="submit_this(this.name)"/><br>';
}
echo '</form>';
Note :here i have used $upload_id a php variable which has row[upload id] i.e. it is like accept 1,reject1,saccept1 ans sreject1 for first image and for second image it is accept2 reject2 and so on
Now the code for processor.php
$status_pass = isset($_POST['status'])?$_POST['status']:NULL;
if(!empty($status_pass)){
$status_arr = explode('-', $status_pass);
$action = $status_arr[0];
$upload_id = $status_arr[1];
if($action == 'accept'){
$status = 1;
}
if($action == 'reject'){
$status = 2;
}
if($action == 'saccept'){
$status = 3;
}
if($action == 'sreject'){
$status = 4;
}
echo $status;
$sql="UPDATE upload SET status='$status' where upload_id = '$upload_id' ";
echo "update success";
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
}
in your form
<form action="processor.php" method="post" id ='post_form'>
<input type="hidden" name= "status" id="status" value="">
<?php
foreach($upload_arr as $upload_id){
?>
<input type="button" name="accept-<?=$upload_id?>" value="accept" onclick='submit_this(this.name);'/><br>
<input type="button" name="reject-<?=$upload_id?>" value="reject" onclick='submit_this(this.name);'/><br>
<input type="button" name="saccept-<?=$upload_id?>" value="saccept" onclick='submit_this(this.name);'/><br>
<input type="button" name="sreject-<?=$upload_id?>" value="sreject" onclick='submit_this(this.name);'/><br>
<?php
}
?>
</form>
<script>
function submit_this(name){
document.getElementById('status').value = name;
document.getElementById('post_form').submit();
}
</script>
in you php file
<?php
$status_pass = isset($_POST['status'])?$_POST['status']:NULL;
if(!empty($status_pass)){
$status_arr = explode('-', $status_pass);
$action = $status_arr[0];
$upload_id = $status_arr[1];
if($action == 'accept'){
$status = 1;
}
if($action == 'reject'){
$status = 2;
}
if($action == 'saccept'){
$status = 3;
}
if($action == 'sreject'){
$status = 4;
}
$sql="UPDATE upload SET status='$status' where upload_id = '$upload_id' ";
//execute sql here
}
?>
can you please replace $_POST["accept'.$upload_id.'"] this with $_POST["accept".$upload_id]
Don't use '' quotes for $upload_id input tag, It will work then properly
there's some problems of your code
First
if you want to multiple submit form, the type shuold be button, you can use javascript to contorl submit form, and before submit, you can also pass some value to a hidden input field, as your example, you can set hidden input value = "accept'.$upload_id.'"
Second
in your php file,
$sql="UPDATE upload SET status='1'";
has no where condition, of course, this will update all your records.

Categories