For some reason a POST variable from my form is always empty. Here's my code...
I have a bootstrap select which returns information which I display upon selecting a new item from the dropdown (select).
Code:
$(function() {
$("#shiftsDD").change(function(){
var selectedItemId = $('#shiftsDD option:selected').val();
$.post('/step/services/shiftInfo.php', { shiftID : selectedItemId }, function(res){
$("#shiftCard").show();
var jsonRes = $.parseJSON(res);
$("#address").html(jsonRes[0]);
$("#duties").html(jsonRes[1]);
$("#employer").html(jsonRes[4]);
$("#payRate").html(jsonRes[5]);
$("#theShiftID").html(jsonRes[6]);
console.log(res);
});
});
});
All of those values from the jsonRes array are assigned in here:
<form role="form" name="cardForm" method="POST">
<div class="card" id="shiftCard">
Employer:
<h3 id="employer">Test Employer</h3><br>
Address:
<h3 id="address">Test Address</h3><br>
Duties include:
<h3 id="duties">Test duties</h3><br>
Pay rate:
<h3 id="payRate">Test PayRate</h3><br>
<h5 id="theShiftID" name="myShiftID"></h5>
<br>
<button type="submit" class="btn btn-lg btn-green-solid" name="shiftsBtn">Accept work</button>
</div>
</form>
I've tried lots of things but I am new to ajax and not a pro in PHP so I don't know why:
if (isset($_POST['shiftsBtn'])) {
$theId = $_POST['myShiftID'];
...
myShiftID is always empty
ShiftsDD select code:
<select name="shiftsDD" id="shiftsDD" class="form-control form-control-45">
<option value="0">Select a shift</option>
<?php
$theQuery = "
SELECT DATE_FORMAT(StartTime, '%d/%b/%Y' ) AS ShiftDate, ShiftID,ShiftTitle,TIMESTAMPDIFF(MINUTE, StartTime, EndTime) AS ShiftDuration, ROUND(PayRate,2) as PayRate FROM Shifts;
";
$result = $DBH->query($theQuery);
$result->execute();
while($r = $result->fetch()) {
$theDuration = $r['ShiftDuration'] / 60;
echo "<option value='" . $r['ShiftID'] ."'>[". $r['ShiftDate'] . "] " . $r['ShiftTitle'] . " (Hours: " . $theDuration . ")</option>";
}
?>
</select>
Ok so you need to change the form to match below. Have removed the elements you don't need to change. Note changing the h5 to an input.
<form role="form" name="cardForm" method="POST">
<div class="card" id="shiftCard">
<input id="theShiftID" name="myShiftID" value="" /><br />
<button type="submit" class="btn btn-lg btn-green-solid" name="shiftsBtn">Accept work</button>
</div>
</form>
Then once you've made the form changes, you need to change your js from .html() to .val()
$(function() {
$("#shiftsDD").on('change', function(){
var selectedItemId = $(this).val();
$.post('/step/services/shiftInfo.php', { shiftID : $(this).val() }, function(res){
$("#shiftCard").show();
var jsonRes = $.parseJSON(res);
$("#theShiftID").val(jsonRes[6]);
});
});
});
Related
I have a table with multiple edit buttons. Each edit button is supposed to open up a modal and I am trying to pass the delivery_id to it, so I can then use it in MySQL query
echo "<td><button type='button' class='btn dt_buttons' data-toggle='modal' data-id='$delivery_id' data-target='#editModal'>Edit</button></td>";
What's the best way of retrieving that value in the modal and using it as a variable? I thought that just using $delivery_id would work, but of course that would be too simple!
Code inside the modal:
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Purchase</h4>
</div>
<div class="modal-body">
<?
$query = "SELECT id, supplier_id, date as del_date, delivery_number, po_number, cost_value FROM store_purchases WHERE id = $delivery_id";
echo $query;
$retval = f_select_query($query, $datarows);
$lint_product_id = f_htmlspecialchars_decode($datarows[0]->id , ENT_QUOTES);
$supplier_id = intval($datarows[0]->supplier_id);
$delivery_date = $datarows[0]->del_date;
$delivery_number = intval($datarows[0]->delivery_number);
$lint_unit_cost = f_htmlspecialchars_decode($datarows[0]->cost_value , ENT_QUOTES);
$lint_unit_cost = floatval($lint_unit_cost);
$lint_unit_cost = number_format($lint_unit_cost, 2);
$department_id_dropdown = f_get_dropdown("supplier_name", "supplier_name", "supplier_master", $supplier_id, "id", " store_id = $store_id", '', '', '', false, false, true);
?>
<div class="container-fluid" id="div_user_master" class="ae_form" >
<form id="myForm" action="/platformDev/create_subscription.php" method="POST">
<?
echo "Supplier Name: <td class='text-right' id='department_id' style='width:20%;'> $department_id_dropdown </td> <input id='purch_id' name='purch_id' class='form-control purch_id' value='$product_id' type='hidden'/>";
echo "Delivery Date: <span class='required_field'><i class='fa fa-star fa-sm'></i> </span> <input class='form-control' tabindex='3' id='date' name='date' value= '$delivery_date' type='text'/> <br/>";
echo "Delivery Number: <input type='text' id='unit_cost' name='unit_cost' class='form-control unit_cost' style='width:80%;' value='$delivery_number' />";
echo "Invoice Cost: <input type='text' id='unit_cost' name='unit_cost' class='form-control unit_cost' style='width:80%;' value='$lint_unit_cost' /></div>";
?>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn form-btns btn-primary" style="float: left;" data-dismiss="modal" id="customButton">Add Purchase</button>
<button type="button" class="btn dt_buttons close_this ajax_forms" data-dismiss="modal">Close</button>
</div>
</div>
</div>
The code below will get the data-id value from the button that was clicked.
You can use this template:
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var delivery_id = button.data('id'); // delivery id here
var modal = $(this)
modal.find('.modal-title').text('Delivery #' + delivery_id);
modal.find('.modal-body').html('content here');
});
https://getbootstrap.com/docs/4.0/components/modal/
https://getbootstrap.com/docs/3.3/javascript/#modals
I guess that you are trying to use that id to fetch records and populate the modal with that data.
If that's the case :
You can retrieve the data-id attribute value with Javascript and send Ajax request to your php script and query your database.
$('.dt_buttons').on('click', function()
{
var id = $(this).attr('data-id');
$.ajax
({
url: "your/url",
data:
{
id : id
},
method: 'POST'
}).success(function(response)
{
var json = response,
obj = JSON && JSON.parse(json) || $.parseJSON(json);
// say you have following fields.
var fid = obj[0].id;
var title = obj[0].title;
//retrieve record fields here.
// or just pass the `id` skipping the Ajax stuff above.
$('#editModal')
.find('span.doc-title').text(title).end()
.find('[name="id"]').val(id).end();
/* show modal.. */
$('#editModal').modal('show');
});
});
I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php
I have a page that prints out rows from a mysql table. I'm trying to create an ajax form that allows users to delete rows but for some reason I can only seem to get it to delete the very top row that is printed out.
I've only included the script that might be needed here and left out the database query(which works fine).Firebug only shows my form being posted when I click the top row of results, any other rows it does nothing. Can anyone tell me what's wrong? Thanks
My_reviews.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
//Delete Review
$(document).ready(function(){
$("#deleteReview").click(function (e) {
e.preventDefault();
var username=$("#username").val();
var film_id=$("#film_id").val();
var id=$("#id").val();
$.post('ajax_deleteReview.php', {username: username, film_id: film_id, id: id},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
</head>
<div class="container">
<div id="message"></div>
<?php
$sql = "SELECT * FROM user_reviews WHERE username='$username' ORDER BY DATE desc";
$result = $db_conx->query($sql);
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$film_id = $row['film_id'];
$review = $row['review'];
$movie = $tmdb->getMovie ($film_id);
echo '
<div class="row">
<div class="col-md-1">
<img id="image1" src="'. $tmdb->getImageURL('w150') . $movie->getPoster() .'" width="80" />
<p>
</p>
</div>
<div class="col-md-4">
<h3>
' . $movie->getTitle() .'
</h3>';
echo'
<p>
'.$review. '
</p>
<form>
<input type="hidden" id="username" name="username" value="'. $username.'">
<input type="hidden" id="film_id" name="film_id" value="'.$film_id .'">
<input type="hidden" id="id" name="id" value="'.$id .'">
<button type="submit" id="deleteReview" class="btn btn-danger btn-xs pull-right">delete</button>
</form>
</div>
<div class="col-md-7">
</div>
</div>';
}
?>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js">
</script>
</div>
</body>
</html>
ajax_deleteReview.php
<?php
//include db configuration file
include_once("ajax_review/config.php");
//Configure and Connect to the Databse
$username=$_POST['username'];
$film_id=$_POST['film_id'];
$id=$_POST['id'];
//Delete Data from Database
$delete_row = $mysqli->query("DELETE * FROM `user_reviews` WHERE id='$id' AND username='$username' AND film_id='$film_id' LIMIT 1");
if($delete_row){
echo '<img src="images/tick_large.png"/>';
}
else{ echo "An error occurred!"; }
?>
You have duplicated IDs in inputs, so jQuery returns the 1st occurrence of input.
You can add film_id, id and film_name to the <a> link with a data attribute, then read with jquery.
JavaScript function for ajax request need to be assigned to the class:
$(".deleteReview").click(function (e) {...
and
<a class="deleteReview"....
so with this you eliminate duplicate IDs in HTML code.
I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
I have a column in Database with name URL and ID(PK) i'm using PHP/MYSQL
Im displaying values from db now i want to perform EDIT(update) operation Using Jquery/Ajax.
When i click on Edit link it is replaced with Update/Cancel links Which is working fine and im able to perform update operations.
My requirement is when i click on edit Url data which im using lable tag should replace with input textbox and i should perform update operation
HTML Code
<div class='col-md-4'>
<label class="feed_label" id="feed_label" idl='<?php echo $row->id;?>'><?php echo $row->url; ?></label>
<input name="url1" class="form-control url1 feed_text" value="<?php echo $row->id;?>" id="url1" type="text" placeholder="enter url" style="display:none;">
</div>
<div class='col-md-2'>
<a ide='<?php echo $row->id;?>' id="edit" class='edit' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update btn btn-primary btn-sm' href='#' style='display:none;'>UPDATE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancel btn btn-warning btn-sm' href='#' style='display:none;'>CANCEL</a>
</div>
JQUERY CODE
JQUERY CODE
//EDIT,DELETE TO UPDATE,CANCEL
$('body').delegate('#edit','click',function(){
//alert();
$(this).siblings('#delete').hide();
$(this).siblings('#update,#cancel').show();
$(this).hide();
$('#feed_label').removeClass('feed_label').addClass('feed_url');
});
$('body').delegate('#cancel','click',function(){
//alert();
$(this).siblings('#edit,#delete').show();
$(this).siblings('#update').hide();
$(this).hide();
$("#update_url")[0].reset();
});
//ENDS
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
//alert(IdEdit);
//return false;
$.ajax({
url:"pages/feeds.php",
type:"post",
datatype:"json",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
//alert('success');
$('#id').val(show.id);
$('#url1').val(show.url);
//$('#add_feed_form')[0].reset();
//$('#showdata').load('pages/feeds.php');
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
//alert('update');
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
//alert();
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
//alert('updated');
$('input[type=text]').val('');
showdata();
$('#add_feed_form')[0].reset();
$('#showdata').load('pages/feeds.php');
}
});
});
//UPdate Ends
PHP Code
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
//Ends
Any help Is appreciated Thanks!!
Here i give sample for your case :
HTML
<div class="container">
<label>John</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
<hr/>
<div class="container">
<label>John Who</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
JS (you can simplified below code into one handler)
$(document).on('click', '.edit', function(e){
var data = $(this).prev();
if ( data.is('label') ) data.replaceWith('<input value="'+data.text()+'">');
});
$(document).on('click', '.delete', function(e){
var data = $(this).prev().prev();
if ( data.is('input') ) data.replaceWith('<label>'+data.val()+'</label>');
});
DEMO