Showing bootstraps modal after redicted to page - javascript

So I have been making a website where settings.php and saveSettings.php page where it insert $_POST functions to database.
Here is part of settings.php
echo '
<form action="saveSettings.php" method="POST">
<div class="form-group">
<textarea class="form-control no-resize" rows="4" id="profilecomment" name="profilecomment"></textarea>
</div>
<input type="submit" class="btn btn-success" name="submit" style="margin-top:10px" value="Submit" />
</form>
';
and here part of saveSettings.php
$userComment = $_POST["profilecomment"];
$updateComment = "UPDATE users SET comment = '$userComment' WHERE steamid = '$steamID' ";
header('Location: settings.php');
This is what I have tried:
I added my modal load script to settings.php page
<script>
$(window).load(function(){
$('#settingsSave').modal('show');
});
</script>
And modal script:
<div class="modal fade" id="settingsSave" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>You have successfully saved your settings!</p>
</div>
</div>
</div>
</div>
I am not sure if it does not popup because of that:
header('Location: settings.php');
I hope I can get some help.

First, please be aware of mysql Injection, I see you dont escape your POST parameters.
Do it like this:
$userComment = mysql_real_escape_string($_POST["profilecomment"]);
or use mysqli instead of mysql
To your question:
$(window).load(function(){
$('#settingsSave').modal('show');
});
is wrong, you must use something like:
$( document ).ready(function() {
<?
if(isset($_GET['save'])){
echo "$('#settingsSave').modal('show');";
}
?>
});
ans pass a parameter to your new location
header('Location: settings.php?save');

Related

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>

Data from displayed summary must submit to database using modal form

Sorry, english is not my Native Language. I've been really stuck since I've just use PHP to store data in my Database (I'm using mysql).
So in my html I have the main
function display() {
var canvas = document.getElementById('displaycanvas');
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
if(document.getElementById('color1').checked){ context.strokeStyle="#FF0000"; } else if(document.getElementById('color2').checked){ context.strokeStyle="#0000FF"; }
if (document.getElementById('shape1').checked) {
context.beginPath(); context.arc(95,50,40,0,2*Math.PI); context.stroke(); }
if (document.getElementById('shape2').checked) {
context.beginPath(); context.rect(50, 27, 50, 100); context.stroke(); }
}
$('#review').click(function () {
$('#shape').html($('input[name="shape_design"]:checked').val());
$('#color').html($('input[name="color_design"]:checked').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="displaycanvas"></canvas>
<form role="form" id="showchoices" name="showchoices" method="post" onsubmit="return entry_check()" action="/user/ps/add/">
<div> <input type="radio" id="shape1" name="shape_design" value="CIRCLE" onchange="display()" /> O
<input type="radio" id="shape2" name="shape_design" value="RECTANGLE" onchange="display()" /> [] </div>
<div> <input type="radio" id="color1" name="color_design" value="RED" onchange="display()"/> RED
<input type="radio" id="color2" name="color_design" value="BLUE" onchange="display()" /> BLUE </div> </form>
<input type="button" name="btn" value="Review" id="review" data-toggle="modal" data-target="#con_rev" class="btn btn-primary" />
<!-- this modal displays the SUMMARY,working fine -->
<div class="modal fade" id="con_rev" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">Confirm Order</div>
<div class="modal-body">
<form action="#myModal1" role="form" method="POST"> <!-- display for the Order sent -->
<p> Shape: <span id="shape" name="shape" ></span> </p>
<p> Color: <span id="color" name="color" ></span> </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" class="btn btn-success" name="order"/> </div>
</div> </form>
</div>
</div>
Everything above is working fine, I just would like to show how it looks like.
So this is how it works. Once the user will choose her/his choices, first it will display a modal that "Summarizes" the data its modal id="con_rev".
So here we have the data displayed based on user's choices.
Now I've made another modal when the user decides to "ORDER" or submit its choices.
Modal same in HTML page: (this one isn't working)
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">ORDER SENT</h4> </div>
<div class="modal-body">
<?php
include 'database.php';
$pdo = Database::connect();
$shape = $_POST['shape'];
$color = $_POST['color'];
$dbc = #mysql_connect('localhost' , 'root', '');
#mysql_select_db('order_db', $dbc);
$query = "INSERT INTO choice VALUES(NULL, '$shape','$color')";
if(#mysql_query($query,$dbc)){
print '<h1> Your order has been sent </h1>'; }
else{ print '<p> failed. '.mysql_error().'</p>'; }
?>
</div>
</div>
</div>
</div>
I've followed different sources of tutorial and combined them.
It won't display error, but if I'm going to check at my database its still empty. Hope you could really help me out.
In case you'll use Ajax, our class haven't tackled it so I'm not sure if I could advance but still if its the only way I'll take it!
Thank you in advance!
First of all, mysql_connect() is deprecated and has been removed in PHP 7.0.0
Now what is confusing me is that, you're taking the pdo instance (pressumably it's PDO extension) through:
include 'database.php';
$pdo = Database::connect();
but didn't use it at all:
Try this (I've adapted to your configuration by using PDO extension) :
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">ORDER SENT</h4> </div>
<div class="modal-body">
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'order_db';
$shape = $_POST['shape'];
$color = $_POST['color'];
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
try {
$pdo = new PDO("mysql:host=host;dbname=database", $user, $pass, $options);
}
catch (PDOException $e) {
echo "connection error : <br> :";
echo $e->getMessage();
}
$sql = "INSERT INTO 'choice' VALUES (:mynull, :shape, :color)";
$statement = $pdo->prepare($sql);
$statement->bindValue(':mynull', null, PDO::PARAM_INT);
$statement->bindValue(':shape', $shape, PDO::PARAM_STR);
$statement->bindValue(':color', $color, PDO::PARAM_STR);
$inserted = $statement->execute();
if($inserted){
echo 'Your order has been sent !<br>';
}
?>
</div>
</div>
</div>
</div>
also don't use # , it's intended to suppress the errors thus you cann't see it when the error thrown.

j query updating div of drop-down after inserting data

I have a drop down which i am filling from database (ss and source attached)
<div id="divmedium">
<label>Medium:</label> <a data-toggle="modal" role="button" href="#medium_m">[Add New Medium]</a>
<select data-placeholder="Select Medium" class="select-full" tabindex="2" id="media" name="media">
<option value=""></option>
<?php
$quee = 'SELECT `media_id` , `mediatype` FROM `media` WHERE `bus_id_fk` = "'. $_SESSION['bus_id_fk'].'" order by `mediatype` asc';
$rs=$DBH->query($quee);
while($row = $rs->fetch_assoc()){
echo "<option value=$row[media_id]>$row[mediatype]</option>";
}
?>
</select>
</div>
if i click on [Add New Medium] , a model appears in which i can add value.
<div id="medium_m" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="icon-paragraph-justify2"></i> Add New Medium </h4>
</div>
<!-- Form inside modal -->
<form action="#" role="form" id="med1">
<div class="modal-body with-padding">
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<label>First Medium</label>
<input type="text" name="fname" placeholder="Eugene" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
<button type="submit" id = "m_btn" class="btn btn-primary">Submit form</button>
</div>
</form>
</div>
</div>
click on submit form (AJAX)
$(document).ready(function(){
$('#med1').submit(function(){
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'addmedium.php',
//data: formData.serialize()
data: $(this).serialize()
})
.done(function(data){
$('#response').html(data);
if(data.status == 'success'){
$("#divmedium").html(data);
}else if(data.status == 'error'){
alert("Error on query!");
}
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
addmedium.php
<?php
session_start();
INCLUDE './config/databases.php';
header('Content-type: application/json');
$loc= $_POST['fname'];
$busid=$_SESSION['bus_id_fk'];
$sql = "INSERT INTO media (mediatype,bus_id_fk)VALUES ( '$loc','$busid' )";
//echo $sql;
if ($DBH->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
// echo "Error: " . $sql . "<br>" . $DBH->error;
}
$response_array['status'] = 'success';
echo json_encode($response_array);
exit;
?>
Now the problem is
data getting inserted in the database but i am unable to refresh the
div,
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
after clicking on Submit form , the div divmedium is disappearing.
Let me know what i am doing wrong.
I'll start from the end, if you won't mind.
after clicking on Submit form , the div divmedium is disappearing.
In your AJAX code $("#divmedium").html(data); you are replacing divmedium content with json_encode($response_array);
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
I don't see any code that should close it. Try to add data-dismiss="modal"
data getting inserted in the database but i am unable to refresh the div
Same stuff as in 3rd question, check this and edit your AJAX success callback.

Ajax is not updating data

I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>">
Edit <i class="fa fa-pencil-square-o"></i>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $list['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="container">
<form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form">
<input type="hidden" name="commentID" value="<?php echo $list['id']; ?>">
<div class="from-group">
<label for="title">Title: </label>
<input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title">
</div>
<div class="from-group">
<label for="label">Label: </label>
<input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label">
</div>
<br>
<div class="from-group">
<label for="body">Body: </label>
<textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea>
</div>
<br>
<input type="hidden" name="editted" value="1">
<br>
<br>
<input type="submit" id="btnupdate" value="Edit">
</form>
</div>
</div>
as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate';
if(isset($_GET['editted'])){
$title = $_GET['title'];
$label = $_GET['label'];
$body = $_GET['body'];
$action = 'Updated';
$q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID'];
$r = mysqli_query($dbc, $q);
$message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ;
}
and here is the ajax code snippet;
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1";
$.get(tempUrl);
});
I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
This (untested code) may be similar to what you should do:
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempParams = {"page":"postupdate","title":tempTitle,"label":tempLabel,"body":tempBody,"commentID":30,"editted":1};
$.post("index.php",tempParams,function(data) {
alert(data);
});
});
UPDATE
Try ajax instead of get to see if some error occurs in the loading
$.ajax( {url:"index.php",data:tempParams,type: "POST"} ).done(function() {
alert( "success" );
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});`
UPDATE
Start testing if the click handler works then (just to be sure!):
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
UPDATE
Start testing if the script gets executed then:
alert("yes at least the script gets executed");
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
If not you must have a javascript error somewhere.
https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
If yes, your button does not get caught by JQuery (no idea why)
anyway it's got nothing to do with ajax or get!

How to Upload a file and save to DB using PHP, JavaScript, Bootstrap

everyone..
i've problem using javascript.
i want to make CRUD using Modal(bootstrap), PHP and javascript. but unfortunatelly til now i can't upload a file and save them to database. i have 3 files (index, form, javascript, process) here is my code :
for modal (index) :
<div id="dialog-admin" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"></h3>
</div>
<!-- tempat untuk menampilkan form admin -->
<div class="modal-body"></div>
<div class="modal-footer">
<button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Batal</button>
<button id="simpan-admin" class="btn btn-success">Simpan</button>
</div>
this code for form file :
<form class="form-horizontal" id="form-admin" enctype="multipart/form-data" >
<div> ... bla bla bla.. field.. </div>
<div class="control-group">
<label class="control-label" for="ava">Image</label>
<div class="controls">
<input type="file" id="ava" name="ava" value="<?php echo $ava ?>" required="required" />
</div>
</div>
this code for javascript :
$("#simpan-admin").bind("click", function(event) {
var url = "admin-proses.php";
// mengambil nilai dari inputbox, textbox dan select
var v_username = $('input:text[name=username]').val();
var v_email = $('input:text[name=email]').val();
var v_pass = $('input:text[name=pass]').val();
var v_ava = $('input:file[name=ava]').val();
// mengirimkan data ke berkas transaksi admin-proses.php untuk di proses
$.post(url, {username: v_username, email: v_email, pass: v_pass, ava:v_ava, id: id} ,function() {
// tampilkan data admin yang sudah di perbaharui
// ke dalam <div id="data-admin"></div>
$("#data-admin").load(main);
// sembunyikan modal dialog
$('#dialog-admin').modal('hide');
// kembalikan judul modal dialog
$("#myModalLabel").html("Tambah Data Admin");
});
});
and this code for file process :
require 'dbase.php';
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$imageName = $_FILES['ava']['name'];
$imageSize = $_FILES['ava']['size'];
$imageError = $_FILES['ava']['error'];
if ($imageSize > 0 || $imageError == 0){
$move = move_uploaded_file($_FILES['ava']['tmp_name'], '../uploads/ava/'.$imageName);
if ($move){
echo 'success';
} else {
echo 'failed';
}
} else {
echo 'failed to save file to DB : '.$imageError;
}
mysql_query("INSERT INTO tb_admin VALUES('','$username','$email','$pass','$imageName')") or die (mysql_error());
could you to help me ?
thank
Regard
check whether the post has been done properly in jquery. do step by step debugging.Be sure of getting all input field values.
I would suggest that you should go to this link by W3Schools:
http://www.w3schools.com/php/php_file_upload.asp
It covers all the basics of file uploading.
For Database, go through this:
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

Categories

Resources