Updating parts of a .php page - javascript

Is it possible to update a page and proceeding the next function, similar to refreshing it?
I have a page that when Save button is pressed, it will submit the data into earnings_amendment_account_add.php, and the page will be refreshed.
Now, what I'm trying to achieve through AJAX is for the data to be submitted, and then display Success Notification and refresh the dataTable upon pressing Save in my modal.
Example, this part of the page <?php include 'includes/notif-info-display.php'; ?> will trigger this upon submitting a page.
This Screenshot only displays after I submit the form and the page was refreshed.
<section class="content">
<div id = "content">
<?php include 'panels/accounting_panel.php'; ?>
<?php include 'includes/notif-info-display.php'; ?>
</div>
Now, I did some modifications to avoid refreshing the page. It will send the data to the database, but I cant' find a way for the dataTable to be refreshed, and for <?php include 'includes/notif-info-display.php'; ?> to be reloaded and display if it is Success or Fail, based on the triggers in my earnings_amendment_account_add.php.
$(document).ready(function () {
// Listen to click event on the submit button
$('#add').click(function (e) {
e.preventDefault();
// Add trigger based on button name, value
var add = $("#add").val();
var add_accountcode = $("#add_accountcode").val();
var accounttitle = $("#accounttitle").val();
var accounttype = $("#accounttype").val();
var postedby = $("#postedby").val();
var dateposted = $("#dateposted").val();
$.post("earnings_amendment_account_add.php",
{
// Add trigger based on button name, value
add: add,
add_accountcode: add_accountcode,
accounttitle: accounttitle,
accounttype: accounttype,
postedby: postedby,
dateposted: dateposted
}).complete(function() {
console.log("Success");
});
});
});
The trigger comes from earnings_amendment_account_add.php page
if(sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET))){
$_SESSION['success'] = 'Earnings Amendment Account Data added successfully';
}
else{
$_SESSION['error'] = $conn->echo .print_r(sqlsrv_errors(), true);
}
}
else{
$_SESSION['error'] = 'Fill up add form first';
}
?>
This is the includes/notif-info-display.php
<?php
if(isset($_SESSION['error'])){
echo "
<div class='alert alert-danger alert-dismissible'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
<h4><i class='icon fa fa-warning'></i> Error!</h4>
".$_SESSION['error']."
</div>
";
unset($_SESSION['error']);
}
if(isset($_SESSION['success'])){
echo "
<div class='alert alert-success alert-dismissible'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
<h4><i class='icon fa fa-check'></i> Success!</h4>
".$_SESSION['success']."
</div>
";
unset($_SESSION['success']);
}
?>
This happens after I click this the #addnew modal's submit.
<form autocomplete='off' class="form-horizontal" method="POST" action="earnings_amendment_account_add.php">
FORMS HERE ---
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<!-- Add Button ID, Change Type to button, add name, add value -->
<button type="button" class="btn btn-primary btn-flat" name="add" value="add" id="add"><i class="fa fa-save"></i> Save</button>
</form>
</div>
</div>
Everything works perfectly fine, the data is added, my only problem is that I can't seem to find a way for <?php include 'includes/notif-info-display.php'; ?> to be reloaded again and display the Success Notification upon pressing save.
This is my modal.
Is there a way for this to happen? <?php include 'includes/notif-info-display.php'; ?> will be reloaded and display if the Data Submitted was a success, or a failure, and at the same time, refresh the dataTable and show the latest data there?

use echo "<meta http-equiv='refresh' content='0'>";
after your if(isset($_SESSION['success'])){for the reload.
Also set $activateSuccess = true; here.
Then echo your message with
if($activateSuccess == true) {
echo "
<div class='alert alert-success alert-dismissible'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
<h4><i class='icon fa fa-check'></i> Success!</h4></div>";
}
return;

You must handle this issue on your jquery code.In php code handling the ajax request you must send back the success data as JSON. Then in your ajax request complete section, handle this data, create a table row to add to your Datatable and pop a success notification.
Php does not update partially. this is a matter of client, php runs in server.

Related

How to avoid inserting two time in double click time in codeigniter

I am search the other result of related question and that i implement in my code but that not working ,i have 2 button in a form
my form
<form id="InVoice" action="<?php echo base_url('Staff/add_invoice_spare');?>" method="post" class="form-horizontal">
/*-- content herer--*/
<button style="float:right;" type="submit" name="ready" value="Ready For Bill" class="btn btn-danger" style="border-radius:60px;">Add to Ready for Bill</button>
<button style="float:right;margin-left:15px;" type="submit" name="print" class="btn btn-danger" style="border-radius:60px;">Print</button>
<?php echo form_close(); ?>
and used script is
<script type="text/javascript">
$(document).ready(function() {
$("form#InVoice").submit(function() {
alert();
$('button[type=submit]').prop('disabled',true);
return true;
});
});
</script>
this my controller for inserting
public function add_invoice_spare()
{
$bill=$this->input->post('ready');
if($bill)
{
$reg=$this->input->post('rno');
$data=array(
/*-----------datas here-----*/
);
$ans=$this->Bill_model->check_registration($reg);
$form_data= $this->input->post();
$result=$this->Bill_model->invoice_dtls_ready($form_data,$data);
if($result){
redirect('Staff/list_invoice/'.$result);
}
}else{
$reg=$this->input->post('rno');
$data=array(
/*-----------datas here-----*/
);
}
$form_data= $this->input->post();
$result=$this->Bill_model->invoice_dtls($form_data,$data);
if($result)
{
?>
<script type="text/javascript" language="Javascript">
window.open('invoice_pdf/<?PHP echo $result ?>', '_blank');
window.location.href = "invoice_labour";
</script>
<?php }
}
}
but in double click or single click the Add to Ready for Bill button the print button is work why that redirect?
any way to solve this issue and only one time submitte the data ?
thanks in advance!!!
Both the buttons that you are clicking on are of the type submit or they are submit buttons. So the only way to differentiate this will be at the backend.
For eg, according to the above example when you submit the $_POST array will have the submit button value. It is based on this value that you have to build your code logics.
If you click on Print then $_POST['submit'] will be the value will be print and when you click on "Add to Ready for Bill" the $_POST['submit'] value will be ready.
If you want to control it in the Frontend i.e., jQuery end you can by using the preventDefault (the example of which is given by #pradeep) but I suggest you modify the Backend as well to differentiate between these 2 submit buttons.
Hope this helps.

PHP Trigger submit on other page from iframe

I am trying to submit the page inside the iframe using the submit button from modal of Page1.php to trigger the submit button of Page2.php. Can I ask for a help if what is the best way to execute this?
The reason why my submit is in modal is to execute multiple functions from Page1.php, and the Page1.php codes is some part of the button from dataTable just incase you notice those single (')s
Page1.php
<a class='btn btn-md btn-warning' data-toggle='modal' data-target='#editModal' >View</a>
<div class='modal fade' id='editModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-dialog' style='width:95%; height:100%'>
<div class='modal-content' style='height:100%'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='myModalLabel'>EDIT HERE</h4>
</div>
<div class='modal-body'>
<iframe src='page2.php' id='info' class='iframe' name='info' seamless='' height='100%' width='100%'></iframe>
</div>
<div class='col-lg-12' style='text-align: center' ><button type='submit' name='outerSubmit' id='outerSubmit' value='Submit' class='btn btn-lg btn-danger'>SAVE</button></div>
</div>
</div>
</div>
Page2.php
<form id="getedit" name="getedit" action="someaction..." method="POST" class="form-horizontal" onSubmit="if(!confirm('Are you sure you want to save changes?')){return false;}" >
<div class="col-sm-3">
<label for="exampleInputtext1">Name:</label>
<input type="text" class="form-control" id="dogr" value='somename'readonly/>
</div>
<div class="col-lg-12" style="text-align: center" ><button type="submit" name="getData" id="getData" value="Submit" class="btn btn-lg btn-danger" hidden>SAVE</button></div>
</form>
I just want to let the readers understand the whole process because I think I already have the correct codes but I dont know how to apply it properly in this situation. so here is my whole function:
function suysing_search($data)
{
$sEcho = intval($data["sEcho"]);
$sSearch = $data["sSearch"];
$iDisplayStart = intval($data["iDisplayStart"]); //start of record
$iDisplayLength = intval($data["iDisplayLength"]); //display size
$pageNum = ($iDisplayStart/$iDisplayLength)+1; //page num
$colSort = $data['iSortCol_0'];
$dirSort = strtoupper($data['sSortDir_0']);
$qString = "CALL suysing_list(";
$qString .= " " . $colSort . ",";
$qString .= "'" . $dirSort . "',";
$qString .= "" . $pageNum . ",";
$qString .= "" . $iDisplayLength . ",";
$qString .= "'" . $sSearch . "',";
$qString .= "" . $sEcho . ")";
//$res = $this->db->query($qString);
//$res = $res->result();
$res = $this->db->query($qString)->result();
//print_r($res);
//$res = $res->result();
$iTotalDisplayRecords = 0;
$iTotalRecords = 0;
//echo intval($res[0]->TOTAL_ROWS);
if(count($res) > 0)
{
$iTotalDisplayRecords = intval($res[0]->TOTAL_ROWS); //used for paging/numbering; same with iTotalRecords except if there will be search filtering
$iTotalRecords = intval($res[0]->TOTAL_ROWS); //total records unfiltered
}
$output = array(
"sEcho" => intval($sEcho),
"iTotalRecords" => $iTotalRecords,
"iTotalDisplayRecords" => $iTotalDisplayRecords,
"aaData" => array()
);
$countField = "<input type='hidden' name='ctd_count' id='ctd_count' value='".$iTotalRecords."' />";
//print_r($res);
setlocale(LC_MONETARY, 'en_PH');
if(count($res) > 0)
{
foreach($res as $row)
{
$output['aaData'][] = array(
$row->ref_no,
"
<script>
function sample(){
alert('Outer submit triggered!');
window.frames['innerframe'].document.forms['getedit'].submit();
}
</script>
<a class='btn btn-md btn-warning' data-toggle='modal' data-target='#editModal".$row->ref_no ." ' >View</a>
<div class='modal fade' id='editModal". $row->ref_no ."' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-dialog' style='width:95%; height:100%'>
<div class='modal-content' style='height:100%; '>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='myModalLabel'>EDIT HERE</h4>
</div>
<div class='modal-body' style='background:url(".base_url()."images/animal.gif) center center no-repeat; height:85%'>
<iframe id='innerframe' src='".base_url()."index.php/suysing/view_profile/".$row->ref_no."/a/ASHAJSHAKS'class='iframe' name='innerframe' seamless='' height='100%' width='100%'></iframe>
</div>
<div class='col-lg-12' style='text-align: center'><button name='outerSubmit' id='outerSubmit' class='btn btn-lg btn-danger' onClick='sample();'>SAaaaaaVE</button></div>
</div>
</div>
</div>
"
);
}
}
echo json_encode($output);
}
One way you can do this is using only javascript to add a javascript function to page1.php that will submit your form on page2.php. Add this code to the top of page1.php
<script type="text/javascript">
function sumbit_up_form()
{
window.frames["info"].document.forms["getedit"].submit();
}
</script>
Then Modify the button on page1.php to run the function when clicked by using:
<button type='submit' name='dateData' id='dateData' value='Submit' class='btn btn-lg btn-danger' onclick='sumbit_up_form();'>SAVE</button>
instead of
<button type='submit' name='dateData' id='dateData' value='Submit' class='btn btn-lg btn-danger'>SAVE</button>
EDIT -- ADDITION
If you want this to work using your jquery script then use:
window.frames["info"].document.forms["getedit"].submit();
instead of
$('#info').contents().find('#getData input[type="submit"]').click();
Breakdown of how the code works:
window. is a reference to the browser window object. In order for this code to work Page1.php will need to be the top document in the browser window. If Page1.php is in an iframe itself then you will need to reference the iframe or leave window. out of the code. However, leaving out the window. could make your site/app more easy to hijack.
frames["info"]. is a reference to the iframe object using the name attribute.
document. is a reference to the document inside the iframe.
forms["getedit"]. is a reference to the form object using the name attribute. If you prefer to use the ID then use getElementById("getedit"). instead. NOTE: In XHTML, the name attribute is deprecated. Use the id attribute instead.
submit() calls the submit method for the form object.
When you submit your form with i frame,after successful submission set value in session flash data.
session()->flash('operation_status', 'success');
and then get that flash data in your iframe.
Inside Your Iframe
$operation_status = session()->get('operation_status', false)
if ($operation_status == 'success')
var p = window.parent;
p.jQuery('body').trigger('refreshPage');
}
In parent page
$('body').on('refreshPage', function (e) {
window.location.reload();
});
This code is from laravel

Issues inserting data into my database after user has logged in

I have a script that I would like to have run using jQuery and PHP. After a user logs in, they fill out a form and hit the 'save' button. The jQuery attaches a click event which runs the PHP script. I've got console logs at certain break points and I'm showing that my script is actually stopping at a certain point, however, I have no idea why.
TABLE CREATION AND DATABASE CONNECTION
$create_table_scenarios = "CREATE TABLE IF NOT EXISTS $scenarios(id VARCHAR(25), PRIMARY KEY(id))";
mysqli_query($connect, $create_table_scenarios);
I know that the connection is being made and the table is being created because it shows up in the database.
THE FORM
<form id="scenario_builder" method="post" action"../php/processing.php">
<div id="form_general" class="form_view">
<h3>General Info</h3>
<div class="half">
<fieldset for="center_menu">
<label>Center:</label>
<div class="select" name="center_menu" id="center_menu">
<div class="arrow"></div>
<div class="option-menu">
<div class="option"></div>
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'><input type='hidden' name='center' id='center' value='" .$center_name ."' />" .$center_name ."</div>";
}
?>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<input type="submit" name="save" id="save" class="button" value="Save" />
</form>
PROCESSOR
ob_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$center = $_POST["center"];
$query = "INSERT INTO `$scenarios`(`id`) VALUES('" .$center ."')";
mysqli_query($connect, $query);
}
ob_clean();
echo json_encode(array("success" => 1));
jQUERY
$("input[id='save']").on("click", function(){
console.log("Save clicked");
$.post("..php/processing.php", {}, function(response){
if(response.success == "1"){
console.log("Data entered.");
}
else{
console.log("Data not entered.");
}
}, "json");
})
The only console message I'm getting is the "Save clicked" one. So, for some reason, the $.post function isn't running. Can someone show me why based on the code I've provided? On a different note, yes, I understand that my queries are vulnerable to injection, I'm just trying to get the basics to work right now.
From what i see you are double submitting the form. You once submit the form due to the form's submit button push and the second time you submit the form with the AJAX request due to the event handler you added to the button. You either let the form submit with a regular POST, or on the submit button press you prevent the event's default behavior and submit the data by AJAX.

using jquery in php post method

I am not very experienced in jquery and ajax but I need the following. After users have successfully logged in they can download pdf files from the page. The site has a collapse div from where they can choose which file to download. Everything is done in php and works ok. However, if the file is not found the collapse div is closed back. In other words the web page gets reloaded. So the user has to make a new selection newly which is inconvenient. So I would the following. If the file is not found then the div should stay collapsed and the previous value in the input field 's' on the form. I know this should be done via jquery or javascript. I have tried the following but it does not work.
//PHP
<?php
//if download is clicked
if (isset($_POST["download"])) {
$data = $_POST["s"];
//if file is found
if (fileexists($data){
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile($data);
}
//else the div should remain open
else{
echo "<script> if ($('#collapseOne').is(':hidden')) {
$('#collapseOne').show();
}</script>";
}
}
?>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form id='searchForm' method="post" action=''>
<p><label>Select Month</label></p>
<input id='s' name = 's' type='text' required><br><br>
<button type="submit" id='download' name='download' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download
</button>
<br> <br>
<button id='download1' name = 'download1' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download All
</button>
</form>
</div>
</div>
In short, you echo PHP into Javascript
<script>
$(document).ready(function(){
var hasDownload = "<?php echo $_POST['download']; ?>";
var oldInput = "<?php echo $_POST['s']; ?>";
if(hasDownload == false) {
$('#collapseOne').show();
$('input#s').val(oldInput);
}
})
</script>
When the server serves your file, those values will be present for your Javascript. Place you're jQuery at the bottom in another if statement & a doc ready block so that the dom is loaded first and echo your PHP variables into Javascript variables to perform your jQuery logic.
<?php
if (isset($_POST["download"]) && fileexists($_POST["s"]) {
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($_POST["s"]);
}
?>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form id='searchForm' method="post" action=''>
<p><label>Select Month</label></p>
<input id='s' name = 's' type='text' required><br><br>
<button type="submit" id='download' name='download' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download
</button>
<br> <br>
<button id='download1' name = 'download1' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download All
</button>
</form>
</div>
</div>
<?php if(isset($_POST["download"]) == false && fileexists($_POST["s"] == false) : ?>
<script>
$(document).ready(function(){
var hasDownload = "<?php echo $_POST['download']; ?>";
var oldInput = "<?php echo $_POST['s']; ?>";
if(hasDownload == false) {
$('#collapseOne').show();
$('input#s').val(oldInput);
}
})
</script>
<?php endif; ?>
Try using this!
$.ajax({
url:"/path/to/your/script/",
type: "post",
data: //fetch the data which you want to pass
}).done(function(status){
//status is the data returned from the script called
});

jQuery/ajax form submitting not working with multiple forms + modals not closing

I have a page on my site where I got n+1 forms (n being the number of images on the site)
I have this piece of javascript to submit the forms without the user seing it directly:
$('#commentform').on('submit', function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
var imgid = $(this).find("input[name='imageid']").val();
$('#comment-'+imgid).modal('hide');
},'json');
return false;
});
That code will submit the form in a modal like this one:
<div id='comment-<?php echo $image->id; ?>' 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'>Tilføj kommentar til billede <?php echo $orig_name; ?></h3>
</div>
<form action="<?php echo base_url(); ?>order/do_updateComment/<?php echo $image->id; ?>" method="POST" id="commentform">
<div class='modal-body'>
<textarea name="comment" rows="3" class="span6" placeholder="Skriv din kommentar her..."><?php echo $image->comment; ?></textarea>
<input type="hidden" name="imageid" value="<?php echo $image->id; ?>" />
</div>
<div class='modal-footer'>
<button class='btn' data-dismiss='modal' aria-hidden='true'>Luk</button>
<input type="submit" name="submit" class='btn btn-primary' value="Gem kommentar" />
</div>
</form>
</div>
This works perfect for the first form on the page - all the rest gets submitted the wrong way (with a redirect to the submission page)
What am I missing here? I am suspecting it to be because of the use of id="commentform" on all of the forms, but how else could this be done? I got one form on the site that needs to be submitted the normal way.
Also on a side-note, I want to close the modal once the submit has finished, which should be done with these lines of code:
var imgid = $(this).find("input[name='imageid']").val();
$('#comment-'+imgid).modal('hide');
inside the javascript (complete is in the top of the question)
However, that does not work either.. The modal stays open..
I am running the whole thing on Bootstrap 2.x with jquery 1.9.0
The reference to $(this) is dropped when you're in the callback. Save the reference outside of the post and it should work.
I am suspecting it to be because of the use of id="commentform" on all of the forms
Correct, ids must be unique. Using classes is the common way to select multiple similar elements.

Categories