Pass Value From URL Link To Form Field - javascript

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>

Related

how to get specific id to show specific detail from modal

i created an article and using modal i can view the article but the problem is when i tried to view the article only the first article is being shown. not specifically the one that i clicked.. i noticed that the variable that i declared only gets the first id.
<?php
include_once('../model/articles.php');
$database = new Database();
$conn= $database->getConnection();
$db= new articles($conn);
$output = $db->viewAllarticles();
$articleid ='';
$artname = '';
$artpublished = '';
$arttitle= '';
$artbody = '';
foreach ($output as $key) {
$articleid = $key['art_id'];
$artpublished = $key['date_published'];
$arttitle = $key['art_title'];
$artbody =$key['art_body'];
if($key['art_isSaved'] == '0'){
?>
<style>
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
<div id="article" class="col-lg-4" style="background:#f9f9f9;width:218px;margin-right:10px;">
 <strong class="font-1"><?php echo $key['firstname'].' '.$key['lastname'] ?></strong><br>
<?php echo $key['art_body']?><br>
<?php
<i class="fa fa-eye"></i> <?php echo $key['art_seen']?>
<span class="pull-right"><span style="color:#59960b;" data-toggle="modal" data-target="#myModal">Read more..</span><input type="hidden" value="<?php echo $articleid; ?>"> </span>
</div>
<?php
}
}
?>
what i wanted to do is when i clicked read more the id of the one that i clicked will be sent to the modal.
<div class="modal fade margin-top-70" id="myModal" role="dialog" style="margin-left:-50px;">
<div class="modal-dialog">
<?php
$output = $db->viewArticle($articleid);
foreach ($output as $key):
if($key['art_id'] == $articleid){
?>
<!--view Modal content-->
<div id="articlepost" class="modal-content-article">
<div class="modal-header-article">
<input type="hidden" name="aid" id="aid" value="<?php echo $articleid ?>"/>
<button type="button" style="padding-left:1155px;position:fixed;" class="close" data-dismiss="modal">×</button>
</div>
<img src="./<?= $key['art_cphoto'];?>" style="margin-left:100px;"/>
<div class="modal-body">
<div align="center" style="color:#222;">
<strong class="font-2" id="title"><?php echo $arttitle ?></strong>
<br>
</div>
<?php }?>
</div>
</div>
i tried to use javascript to get the id of the article and it works but the problem is i dont know how to use the variable from javascript to declared it to my php if condition...do you have any idea on how can i get the id of the specific article so when i click the article the one that i click will be the one to shown???
This is happen because you are using repeated modal id. You have to make Modal Id unique like this:
<span class="pull-right" id="artid"><span style="color:#59960b;" class="read" data-id="myModal_<?php echo $articleid; ?>">Read more..</span><input type="hidden" value="<?php echo $articleid; ?>"> </span>
<div class="modal fade margin-top-70" id="myModal_<?php echo $articleid; ?>" role="dialog" style="margin-left:-50px;">
<div class="modal-dialog">
<?php
$output = $db->viewArticle($articleid);
foreach ($output as $key):
if($key['art_id'] == $articleid){
?>
<!--view Modal content-->
<div id="articlepost" class="modal-content-article">
<div class="modal-header-article">
<input type="hidden" name="aid" id="aid" value="<?php echo $articleid ?>"/>
<button type="button" style="padding-left:1155px;position:fixed;" class="close" data-dismiss="modal">×</button>
<img src="./<?= $key['art_cphoto'];?>" style="margin-left:100px;"/>
</div>
<?php }?>
</div>
</div>
jQuery for Modal Open:
$("body").on("click",".read",function(){
var id = $(this).data('id');
('#'+id).modal('toggle');
});
You have to use AJAX with PHP. Because each click you have to fetch data from database depend on you article id.kindly read through about ajax.
Now i just try to solve you problem .
First add jquery library in your file
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js'></script>
Replace you read more button with this
<span class='pull-right'><span style='color:#59960b;' data-toggle='modal' data-id='<?php echo $articleid; ?>' data-target='#myModal'>Read more..</span><span>
Change your modal like below
<div class="modal fade margin-top-70" id="myModal" role="dialog" style="margin-left:-50px;">
<div class="modal-dialog">
</div>
</div>
Add this script below to your page
<script>
$(document).ready(function(){
$(document).on('click','span[data-toggle=modal]',function(){
var articleID=$(this).data('id');
$.ajax({
'url':'../model/read_more_articles.php',//create a page and give the url
'data':{id:articleID},//pass id into read_more_articles.php page using method post
'method':'POST',
success: function (data) { //data contain return of the read_more_articles.php
$('.modal-dialog').html(data);//put generate html of the modal-dialog div
}
})
});
})
</script>
Create a page like read_more_articles.php. Here get details of crrosponding article id and populate html .
<?php
$output="";
$articleid=$_POST['id'];//receive article id which is sent by ajax.
$output = $db->viewArticle($articleid);
foreach ($output as $key){
if($key['art_id'] == $articleid){
$output .="<div id='articlepost' class='modal-content-article'>
<div class='modal-header-article'>
<input type='hidden' name='aid' id='aid' value='".$articleid."'/>
<button type='button' style='padding-left:1155px;position:fixed;' class='close' data-dismiss='modal'>×</button>
</div><img src='".$key['art_cphoto']."' style='margin-left:100px;'/>
<div class='modal-body'>
<div align='center' style='color:#222;'>
<strong class='font-2' id='title'>".$arttitle."</strong><br></div>"
}
}
echo $output;
?>
i finally found a way how to do it.. so here is what i did.. first i change my span to button
<button type="button" class="btn openModal" data-toggle="modal" data-target="#myModal" data-id="<?php echo $articleid;?>">Read More....</button>
and then
my modal div
<div class="modal fade margin-top-70" id="myModal" role="dialog" style="margin-left:-50px;">
<div class="modal-dialog">
</div>
</div>
then created a jquery script to get the id from the button and send it to another page where my html content is and return it and display it in modal-dialog.
<script type="text/javascript">
$('.openModal').click(function(){
var id = $(this).attr('data-id');
alert(id);
$.ajax({url:"../controller/displayarticle.php?id="+id,cache:false,success:function(result){
$(".modal-dialog").html(result);
}});
});
</script>
after sending the id to another page i use $_GET to get the id that is being sent.
$artid = '';
if ( !empty($_GET['id'])) {
$artid = $_GET['id'];
}else{
header("Location: home.php");
}
after sending the id i use for loop to display the data from database in a modal based on the id that is being sent.
$output = $db->viewArticle($artid);
foreach ($output as $key):
<div id="articlepost" class="modal-content-article">
<div class="modal-header-article">
<input type="hidden" name="aid" id="aid" value="<?php echo $artid ?>"/>
<img src="./<?= $key['art_cphoto'];?>" style="margin-left:100px;"/>
</div>
<div class="modal-body">
<img src="./<?= $key['image'];?>" style="border-radius:50%;margin-top:10px;" width="5%" height="5%" />
</div>
<?php
foreach ($db->countarticlecomment($artid) as $value) {
?>
<i class="fa fa-comment" style="color:#59960b;"></i> <span style="color:gray;"><b><?php echo $value['comments']?></b></span> 
</div
<?php endforeach ?>

Showing bootstraps modal after redicted to page

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');

Bootstrap Modal shows up on one page but not the other?

I am trying to code a website using Bootstrap. I already have it implemented on one page using a modal (here) and the other page doesn't seem to show the modal (here) on that page, there is a button that can edit the ban details but when I click the edit button, it does nothing.
Also, I am using jQuery for form submissions so that I can redirect to the returned ID, however, I am stuck on how my function can return the ID because using
get_mysql()->fetch_assoc($result)["id"]
causes a 500 internal server error.
Codes can be found below.
ban.php
<div class="modal fade" id="modal" 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-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<input type="hidden" id="id" name="id" value="<?php echo $ban["id"] ?>" />
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("add.php", { id: id, uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "ban.php?id=<?php echo data ?>";
});
});
});
</script>
index.php
<div class="modal fade" id="modal" 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-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("functions/add.php", { uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "functions/ban.php?id=<?php echo data ?>";
});
});
});
</script>
api.php
<?php
define("key", "redacted");
function get_mysql() {
$mysql = new mysqli("localhost", "redacted", "redacted", "redacted");
if($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = gmdate("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
$result = get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'");
get_mysql()->fetch_array($result);
return $result["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->num_rows > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into `users` (`username`, `password`) values ('$username', '$password'");
}
function get_key() {
return key;
}
?>
I've found the answer thanks to #stain88. I didn't provide the correct link to bootstrap.min.js (facepalm)
Thanks again #stain88.

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!

Categories

Resources