JsTree submit form when a node is selected - javascript

I am using JsTree to create a tree structure to display folder hierarchical order.
What I want to do is, when the user selects a node and move button is clicked, a form will be submitted.
<?php
echo $this->Form->create("MediaDirectory", ['type' => 'post', 'class' => 'form-horizontal','autocomplete' => "off",'novalidate' => "novalidate"]);
?>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-4 col-form-label">Testing</label>
<div class="col-8">
<?php
$folderData = $hah;
$folders_arr = array();
foreach($folderData as $row)
{
$parentid = $row['MediaDirectory']['parent_id'];
if($parentid == null) $parentid = "#";
$folders_arr[] = array(
"id" => $row['MediaDirectory']['id'],
"parent" => $parentid,
"text" => $row['MediaDirectory']['name'],
);
}
?>
<div id="folder_jstree"></div>
<textarea id='txt_folderjsondata' hidden><?= json_encode($folders_arr) ?></textarea>
</div>
</div>
</div>
</div>
<button type="button" name="cancel" class="btn btn-secondary btn-rounded btn-bordered waves-effect" onclick="window.history.back();">Cancel</button>
<button type="submit" name="submit" class="btn btn-primary btn-rounded waves-effect waves-light">Move</button>
<?php echo $this->Form->end(); ?>
Script
<script type="text/javascript">
$(document).ready(function(){
var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());
$('#folder_jstree').jstree({ 'core' : {
'data' : folder_jsondata,
'multiple': false
} });
});
</script>
I don't have any experience expereience with Javascript and JsTree. Can someone help me.

Related

Codeigniter do_upload method is not working

I am working on a cms with Codeigniter. I am trying to upload file from system. I am receiving the file but the do_upload method is not working. There are similar questions on this topic, but none of the answers of them worked.
Here is my method:
public function fileupdate($productId=False){
$formData = $this->input->post();
if (isset($formData['activityNewFile'])) {
foreach ($formData['activityNewFile'] as $key => $value) {
$rndNumber = rand(1,500);
$fileLastName = sef_url($formData['activitynewfilename'.$value]);
// Set preference
$config['upload_path'] = '../assets/';
$config['allowed_types'] = 'pdf|doc|docx|xls|xlsx';
$config['max_size'] = '80960'; // max_size in kb
$config['file_name'] = $fileLastName;
$upFile = 'activitynewfile'.$value;
// Load upload library
$this->load->library('upload',$config);
// File upload
if($this->upload->do_upload($upFile)){
// Get data about the file
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$daData = array(
'productId' => $productId,
'productFileName' => $formData['activitynewfilename'.$value],
'productFile' => $filename
);
$productfileInsert = $this->db->insert('productfile',$daData);
}
}
}
$this->success("İşlem tamamlandı.");
}
HTML part:
<form class="m-form m-form--fit m-form--label-align-right" role="form" method="POST" id="product_file_edit" action="<?=base_url('product/product/fileupdate/'.$productInfo->productId);?>" enctype="multipart/form-data" onsubmit="return false; form_gonder('product_file_edit')" >
<div class="modal-body">
<div class="form-group m-form__group row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="col-md-12" style="margin-bottom: 10px;padding: 0;" id="file_row">
<button onclick="addFileRow('file_add')" class="btn btn-primary btn-sm">
<i class="zmdi zmdi-plus"></i> Add
</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button onclick="form_gonder('product_file_edit')" class="btn btn-green btn-sm">
Save
</button>
</div>
</form>
Javascript part:
function addFileRow(tur){
if(tur=="file_add"){
emreFile = Math.floor(Math.random() * 10);
myhtmlFile = '<div class="col-md-12 row" id="filenew'+emreFile+'" style="padding: 0;margin: 0;margin-bottom: 10px;"><div class="input-group"><input type="hidden" name="activityNewFile[]" value="'+emreFile+'"><img src="../assets/file/pdfword.png" style="width: 38px;float: left;height: 38px;"><input type="text" name="activitynewfilename'+emreFile+'" class="form-control" placeholder="Dosya Adı" style="width: 45%;float: left;height: 39px;"><input type="file" name="activitynewfile'+emreFile+'" accept=".xls,.xlsx,.doc,.docx,.pdf" class="form-control" placeholder="Dosya Adı" style="width: 46%;opacity: 1;float: right;position: relative;"><span class="input-group-btn"><button class="btn btn-red btn-fab btn-fab-sm animate-fab" onclick="deleteNewFileRow('+emreFile+')" type="button"><i class="zmdi zmdi-delete"></i></button></span></div></div>';
var icerikFile = myhtmlFile;
jQuery("#file_row").prepend(icerikFile);
}
}
I would be very grateful if you could find out what the problem is.
Your problem is actually the file is not loading properly. There is no error in your codes. Make sure file_uploads is turned on on your server. Make sure the upload_max_filesize value is not smaller than your file size.

Display data from database into existing textbox when click submit button

I have a problem. I want to display the data from database in the existing textbox but unfortunately, it does not display the result. My if else loop is not working. I don't want to display the textbox only if the button is click. I want the result display inside the existing textbox after the search button click.
here is my code html code:
<div class="row">
<div class="column middle2" style="background-color:transparent">
<div class="container"><br><br>
<div class="row">
<div class="col-01">
<label for="icno"><b>IC No :</b></label>
</div>
<div class="col-02">
<form action="" method = "POST">
<div class="input-group">
<input type="text" name="icpayer" value = "<?php if(isset($_POST['icpayer'])){echo $_POST['icpayer'];} ?>" class="form-control bg-light border-0 small" >
<div class="input-group-append">
<button type="button" id = "searchValue" class="btn btn-primary">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-01">
<label for="name"><b>Payer Name :</b></label>
</div>
<div class="col-02">
<input type="text" id="payername" name="payername" >
</div>
</div>
</div>
</div>
</div>
here is my javascript code:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
here is my php code:
<?php
if(isset($_POST['icpayer'])){
$searchValue = $_POST['icpayer'];
$query="SELECT * FROM ptregistration WHERE patientic = '$searchValue'";
$result = mysqli_query($con, $query) or die(mysqli_error($con,$query));
while($row = mysqli_fetch_array($result)){
echo $row['patientname'];
}
}else{
echo "No Record Found";
} ?>
my problem is when I click the search button, the result display "No Record Found" even there is similar data in the database. please help me as I am a beginner.
You should modify the ajax request to send the icpayer parameter. I do not use jQuery so I'm sure a better jQuery method exists but you can do so like this:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
data:{
icpayer:document.querySelector('input[name="icpayer"]').value
},
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
The PHP was exposing your database to SQL injection (potentially) so you should use Prepared Statements
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['icpayer'] ) ){
include($_SERVER['DOCUMENT_ROOT'].'/mhcsys/include/config.php');
$icpayer=filter_input( INPUT_POST, 'icpayer', FILTER_SANITIZE_STRING );
$sql='select `patientname` from `ptregistration` where `patientic`=?';
$stmt=$con->prepare($sql);
$stmt->bind_param('s',$icpayer);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows();
if( $rows > 0 ){
$stmt->bind_result( $patientname );
while( $stmt->fetch() )echo $patientname;
}else{
echo 'No Record Found';
}
}
?>

How to check if id selector has data or not in bootstrap modal

I am trying to check if an id selector like (ajax response) has some data in it or not in Bootstrap modal. Based on the result I want to display input field otherwise the input field for data update should not be displayed.
I don't want to display blank input field for data update.
<body>
<!-- The Update Modal -->
<div class="modal" id="update_notes">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Notes Editor</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group"><input type="text" id="up_heading" class="form-control" placeholder="Heading"></div>
<?php
if('.$("#up_notes1").val().' != ""){
>
<div class="form-group"><input type="text" id="up_notes1" class="form-control" placeholder="Notes Details"></div>
<?php
}
?>
<?php
if('.$("#up_notes2").val().' != ""){
?>
<div class="form-group"><input type="text" id="up_notes2" class="form-control" placeholder="Notes Details"></div>
<?php
}
?>
<?php
if('.$("#up_notes3").val().' != ""){
?>
<div class="form-group"><input type="text" id="up_notes3" class="form-control" placeholder="Notes Details"></div>
<?php
}
?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal" onclick="updatenotesdetails()">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="hidden" id="hidden_notes_id">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
load_data();
function load_data(page, query = '')
{
$.ajax({
url:"notes_sa_add_fetch.php",
method:"POST",
data:{page:page, query:query},
success:function(data)
{
$('#dynamic_content').html(data);
}
});
}
//Edit and Update record
function GetnotesDetails(notesid){
$('#hidden_notes_id').val(notesid);
$.post(
"notes_sa_add_bk.php",{
notesid:notesid
},
function(data, status){
var notes = JSON.parse(data);
$('#up_heading').val(notes.HEADING);
$('#hidden_notes_hid').val(notes.HID);
$('#hidden_notes_pid').val(notes.PID);
$('#up_notes1').val(notes.P_1);
$('#up_notes2').val(notes.P_2);
$('#up_notes3').val(notes.P_3);
}
);
$('#update_notes').modal("show");
}
function updatenotesdetails(){
var heading_up = $('#up_heading').val();
var notestype_up = $('#up_notestype').val();
var notes1_up = $('#up_notes1').val();
var notes2_up = $('#up_notes2').val();
var notes3_up = $('#up_notes3').val();
var hidden_notes_id_up = $('#hidden_notes_id').val();
$.post(
"notes_sa_add_bk.php",{
hidden_notes_id_up:hidden_notes_id_up,
heading_up:heading_up,
notestype_up:notestype_up,
notes1_up:notes1_up,
notes2_up:notes2_up,
notes3_up:notes3_up
},
function(data, status){
$('#update_notes').modal("hide");
readRecords();
}
);
}
</script>
</body>
Thanks in advance.
Please change the code to the following to check if up_notes1, up_notes2 and up_notes3 are empty:
<!-- Modal body -->
...
<?php
$up_notes1 = $_POST['up_notes1'];
if(isset($up_notes1) && $up_notes1 != "") {
>
<div class="form-group">
<input type="text" id="up_notes1" class="form-control" placeholder="Notes Details" value="<?php echo $up_notes1; ?>">
</div>
<?php
}
?>
<?php
$up_notes2 = $_POST['up_notes2'];
if(isset($up_notes2) && $up_notes2 != "") {
?>
<div class="form-group">
<input type="text" id="up_notes2" class="form-control" placeholder="Notes Details" value="<?php echo $up_notes2; ?>">
</div>
<?php
}
?>
<?php
$up_notes3 = $_POST['up_notes3'];
if(isset($up_notes3) && $up_notes3 != "") {
?>
<div class="form-group">
<input type="text" id="up_notes3" class="form-control" placeholder="Notes Details" value="<?php echo $up_notes2; ?>">
</div>
<?php
}
?>
...
If you want to check if they are empty before post to server, add the following code to updatenotesdetails():
function updatenotesdetails() {
var heading_up = $('#up_heading').val();
var notestype_up = $('#up_notestype').val();
var notes1_up = $('#up_notes1').val();
var notes2_up = $('#up_notes2').val();
var notes3_up = $('#up_notes3').val();
var hidden_notes_id_up = $('#hidden_notes_id').val();
if(heading_up == '' || notestype_up == '' || notes1_up == '' || notes2_up == '' || notes3_up == '' || hidden_notes_id_up == '') {
alert('Please fill in all fields!');
return false;
} else {
// Post data to server...
}
}
Don't forget to rate if it was helpful.
Thanks.

Pass Value From URL Link To Form Field

I have a link in a table from results of an SQL query. Each row has a unique ID. I define this in my script as $id
What I am trying to do is have a link that opens up a form in a modal box where a user can insert a note about that row and save it. This then gets inserted into DB with ID, rowID, Note, Date
echo "<td class='agentid'>" . $id. "<br><a href='#notes' data-toggle='modal' data-row-id='".$id."'>Add Note</a></td>" ;
The modal:
<div class="modal" id="notes">
<div class="modal-dialog">
<div class="modal-content">
<form action="postnote.php" method="post">
<div class="modal-body">
<div class="modal-header">
<h4 class="modal-title">Add a Note</h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
</div>
<p>Note will show when page is refreshed</p>
<label for="fname">Note: </label>
<input type="hidden" name="rowID" value=""/>
<input class="form-control" type="text" name="notes" value="<?php echo date('m/d/Y h:i'); ?> - "/>
<div class="modal-footer">
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$('#notes').on('show.bs.modal', function(e) {
var row = $(e.relatedTarget).data('row-id');
$(e.currentTarget).find('input[name="rowID"]').val(row);
});
</script>
my postnote.php
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
$pdo = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, MYSQL_USER,MYSQL_PASSWORD,$pdoOptions);
$data = [
'notes' => $_POST['notes'],
'id' => $_POST['rowID'],
];
$sql = "INSERT INTO act_recon_notes (note_id, note) Values(:id, :notes)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
header('Location: ' . $_SERVER['HTTP_REFERER']);
I have this exact script on another page and it is working just fine. This does not post the $id into the form. So after submit it is a blank rowID value in the DB.
The issue was I had conflicting JS on the page. I removed the JS that was not needed for this page and the issue resolved.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

Trying to submit a form to MySql with AJAX

I am trying to post from a form to SQL by using Ajax.
However, when clicking the button to submit the form, no error is shown in the chrome console and it looks like the PHP is also not being called in the network tab. Could anyone please help me out or point me in the right direction?
HTML
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/signup.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body background-color="#000000">
<section class="section section-full bg-secondary overflow-hidden z-2">
<div class="container z-2">
<div class="row justify-content-center pt-6 pt-md-5 pb-0 mb-2">
<div class="col-12 col-xl-7">
<div class="card card-tertiary">
<div class="card-header text-center">
<span>Register</span>
</div>
<div class="card-body">
<p class="font-weight-bold">
</p>
<p class="card-text text-center">
Please enter your Email:
</p>
<form class="d-flex justify-content-between mb-2" method="POST" name="email-form" id="email-form">
<div id="name-group" class="form-group">
<p>Name: <input type="text" id="uname" name="uname" class="form-control w-75" required/>
</div>
<div id="email-group" class="form-group">
<p>Email: <input type="text" id="uemail" name="uemail" class="form-control w-75" required/>
</div>
<div class="form-group">
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="button" action="submit" id ="submit" name="submit">
<span class="btn-text">Sign-Up</span>
</button>
</div>
<div id="message"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
signup.js Javascript
$(document).ready(function() {
$('#email-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: 'emailsend.php',
data: {
'uname': $('#uname').val(),
'uemail': $('#uemail').val()
}
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
if(result == 1) {
str = 'User record saved successfully.';
} else if( result == 2) {
str == 'All fields are required.';
} else{
str = 'User data could not be saved. Please try again';
}
$("#message").css('color', 'red').html(str);
})
})
});
emailsend.php PHP
<?php
$dbhost = "localhost";
$dbuser = "------";
$dbpass = "------";
$db = "signup";
$data = '';
$result = 0;
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connect failed: %s\n". $conn -> error);
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$uname = $_POST['uname'];
$email = $_POST['uemail'];
/* validation */
if(!$uname || !$email){
$result = 2;
}elseif (!strpos($email, "#") || !strpos($email, ".")) {
$result = 3;
}else {
//SQL query to get results from database
$sql = "INSERT INTO emails (name, email) VALUES ('$uname', '$email')";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $uname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close()
?>
since you have
$(document).ready(function() {
$('#email-form').submit(function(e) {
and
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="button" action="submit" id ="submit" name="submit">
i dont see how will be submited when button type is not submit
change the button type to submit like this
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="submit" action="submit" id ="submit" name="submit">
First, change your button type attribute to submit instead of button:
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="submit" action="submit" id ="submit" name="submit">
Second, change your JQuery version as
Bootstrap's JavaScript version 3.3 requires jQuery version
1.9.1 or higher, but lower than version 3

Categories

Resources