Passing Javascript variable to php on same page without reload - php

I have been having problems passing Javascript variable to php using ajax on the same page.I have a try.php page and once a button is clicked, I want a value sent to try.php variable without reloading the page..
This is my form code,I am actually looping trough a database record
<?php
foreach($vars as $var){
?>
<form method="POST">
<button class="btn btn-warning btn-sm btn_edit" name="btn_edit" value="<?php echo $var['mem_id'];?>">
<span class="glyphicon glyphicon-pencil"></span></button>
<?php
}
?>
Here is my ajax code
$('.btn_edit').click(function(e){
var uid = $(this).val()
$.post("try.php",{ btn_edit : uid},
function(){
});
console.log(uid);//I could see the id logged on console
$('#edit_details').modal('show');
e.preventDefault();//prevent the form from submitting
});
On my try.php page, I have this code to check if it passed succesfully
<?php if(isset($_POST['btn_edit'])){
$user_id = $_POST['btn_edit'];
}?>

There are two modifications need to be done:
Change 1: Only input elements can have value attribute. And as you have <button>, it should be assigned with some other attribute which can be captured using jQuery, so here I am going to use data-bind attribute with it.
<button class="btn btn-warning btn-sm btn_edit" name="btn_edit" data-bind="<?php echo $var['mem_id'];?>">
And then,Change 2:
Get data-bind value with jQuery like this:
$('.btn_edit').click(function(e){
var uid = $(this).attr('data-bind'); // Using attr, not val()...
$.post("try.php",{ btn_edit : uid},
function(){
});
console.log(uid);//I could see the id logged on console
$('#edit_details').modal('show');
e.preventDefault();//prevent the form from submitting
});

Related

Recaptcha v3 not working - form doesn't submit

I am trying to implement recaptcha v3 in CakePHP 3.x. My template page looks like:
<?php $this->start('script'); ?>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script type="text/javascript">
function registerSubmit(token) {
document.getElementById("register").submit();
}
</script>
<?php $this->end(); ?>
...
<?php echo $this->Form->create($user, [ 'id' => 'register', 'name' => 'register']) ?>
...
<button type="submit"
data-sitekey="<?php echo Configure::read('Captcha.site')?>"
data-callback='registerSubmit'
data-action='submit'
class="g-recaptcha btn btn-lg btn-secondary text-uppercase">Get Started</button>
<?php echo $this->Form->end(); ?>
As far as I can tell the registerSubmit call never gets executed and my form doesn't submit - why?
I followed the instructions on the Google Developers page
I suspect the issue is that you have a button in the form with the id "submit". Any element in the form with a name or an id is reflected in a form attribute with that name. So if you have an element <input id="elephants"/> the form object will have an "elephants" attribute. In this case the submit button is accessible via form.submit, but this masks the submit() function. You can test this by adding an alert to the start of your registerSubmit() function. I believe the alert will get executed, and then the submit() call will fail to run the submit button as it is not a function.
If a form control (such as a submit button) has a name or id of submit, this method will mask the form's submit method.
MDN Web docs

Not able to reload a page after clicking on a button in php

I am not able to reload the php page after a certain button is pressed. That is there is no change until I reload the page by myself. The php script is:
<?php
// Initialize the session
session_start();
if (($_SESSION['ShowGenerated'] == 'hidden'))
{
$class = 'hidden';
}
else if (($_SESSION['ShowGenerated'] == 'visible'))
{
$class = 'show';
}
?>
<html>
<head>
....
<td><button id="pdf" name="Change" class="btn btn-primary"><i class="change-a"" aria-hidden="true"></i>Click Here</button></td>
...
On clicking "Click here" button, Change.php is called where $_SESSION['ShowGenerated'] value is generated. How do I load the current page or a URL to show a change?
EDIT: Instead of reloading the whole page, can I only reload to check if the $_Session has changed in the html page?
Try to put tag inside :
<button id="pdf" name="Change" class="btn btn-primary"><i class="change-a"" aria-hidden="true"></i>Click Here</button>
like this

Jquery function doesen't work when I change page/row or when I search some specific

I made a JQuery function the one deletes the row I selected. I know that the option exist in the DataTables option, but I want to do by myself, because I prefer to not use AJAX, just JQuery and JSON.
The problem appears when I search some specify row in the datatable with the search option, then I click the button to delete, and nothing happens. The other mistake is when I click to the next page, then, all the rows from that page will not work either.
Do you guys know what this could be?
Here I let my JQuery function:
$(document).ready(function() {
$( ".botFactura" ).click(function(e) {
alert("jkn");
idFact = this.id;
var confirmacio = confirm("Segur que vol esborrar la factura "+idFact);
/*if(confirmacio){
$.post("operacions/borraFact.php", {idFact: idFact}, null, "json").done(function(data){
alert(data.missatge);
})
}*/
});});
Then, I have the JSON file there:
<?php
include("../connexio.php");
$idFact= $_POST['idFact'];
$arrayDatos = array();
if($idFact!=""){
$borrar = 'DELETE FROM factures WHERE id="'.$idFact.'"';
//$connBorr = mysqli_query($conn,$borrar);
$arrayDatos['missatge'] = "Factura ".$idFact." esborrada!";
}else{
$arrayDatos['missatge'] = "No s'ha trobat";
}
echo json_encode($arrayDatos);
?>
I call the $(".botFactura") there:
<button type="button" name="<?php echo $line2['id']?>" id="<?php echo line2['id']?>" class="btn btn-danger botFactura">
<span class="glyphicon glyphicon-trash"></span>
</button>
<button type="button" name="<?php echo $line2['id']?>" id="<?php echo $line2['id']?>" class="btn btn-success botFactura">
<span class="glyphicon glyphicon-pencil"></span>
</button>
Finally, I'll upload some graphical example about what's my problem:
:The first one, is when the page works correctly
Then,the first issue appears when: I change the page of the table. As we can see, I click and nothing happens
The same issue appears when I try to search some specific row into the search box.
Well, I would really appreciate if someone could help to explain why this is not working! Thank you!
I don't know which version of jQuery you are using but if you are jQuery 1.9 or upper version try this
$( document ).on('click', '.botFactura', function(e)
or if you are using lower version try this
$( ".botFactura" ).live('click', function(e)

Echo form data without sending to server

I have a tiny form on a page where I ask for the users name, the form sends the data to name.php and echos back the users name for example "Hello Steven" Steven being the name entered into the form.
Now that the name has been echoed to that form, I would like to echo that same data again elsewhere on the page. This is where I've run into a wall.
I would rather not send the names entered into the form to a server or database, but simply keep them for a session and then lose them.
The issue now is echoing the form data multiple times on one page.
The code I am using right now for the tiny form is as follows:
<form role="form" id="inviteform3" class="form-inline" action="name.php" method="POST">
<div class="form-group">
<input type="text" class="form-control input-sm" name="name" placeholder="Your Name"
id="hello" autocomplete="off" style="margin-top:10px">
</div>
<center>
<span id="result"></span>
<button class="btn btn-brand btn-sm next-screen animated bounceInUp"
id="go" style="margin-top:5px; display:none" href="#services" data-animation-delay=".5s">
Let's Go!</button></center>
<button class="btn btn-block btn-brand btn-xs invitebtn3" id="casi" type="submit"
style="margin-top:5px"><i class="fa fa-thumbs-o-up"></i> Submit</button>
</form>
My php form (name.php) is as follows:
<html>
<body>
Let's get started, <?php echo $_POST["name"]; ?>
</body>
</html>
and my js code is:
<script>
$(document).on("ready", function(){
//Form action
$("#inviteform3").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'name.php',
data:$('#inviteform3').serialize(),
success: function(response)
{
$('#inviteform3').find('#result').html(response);
}});
});
});
</script>
We need to get a few things straight:
I would rather not send the names entered into the form to a server or database, but simply keep them for a session and then lose them.
You ARE sending that data to the server, you have used jQuery and AJAX to POST your form to name.php (php works on the server) from which you receive the response and add it your page with the line:
$('#inviteform3').find('#result').html(response);
If you want to KEEP that data stored (for example in a session), you can use the PHP suggested by Antony D'Andrea in name.php. When the browser is closed, the session is destroyed. Untill then you can use the session variable where ever you want.
Now that the name has been echoed to that form, I would like to echo
that same data again elsewhere on the page. This is where I've run
into a wall.
You are echoing the name in name.php, your AJAX call then retrieves the whole page (including the html and body tags) and adds it to #result. If you want to show the name mulitple times, just append it multiple times with the line above.
$("#inviteform3").on("submit", function(event) {
var name = $("form input['name']").val();
// Here is the interesting part
sessionStorage.setItem("name", name);
}
// Get that name
var access_name = sessionStorage.getItem("name");
$("#some_id").html(access_name); // Inserts the name where you want it.
sessionStorage is wiped every time the tab/window is closed.
You could use PHP instead of Javascript.
session_start();
$_SESSION['name'] = $_POST['name'];
The $_SESSION variable is cleared when the browser is closed and is global so can be accessed anywhere. session_start has to be the very first thing you do though on line 1 of the first page that is run.
More info about sessions in PHP can be found here and the about $_SESSION here.
For example:
You are posting to name.php. So on line 1 of name.php do
<?php session_start(); ?>
Then do
<?php
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
}
?>
Then wherever you want to use it, just do echo $_SESSION['name'];
If you want to echo in other files. Then in line 1 of the other file do
<?php session_start(); ?>
Then:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
}
?>
The if statement is just there for checking, but you don't need it if you are confident it is set.

Change a form in order to use jQuery and avoid the page refresh

I'm trying to change the form tag below in order to use jQuery. Already, clicking the buttons changes the display from rows to columns and vice-versa but I want to avoid the page refresh. I'm really new at jQuery and can't honestly say what my mistakes are when trying to change it myself.
<form id="rowsToColumns" action="index.php?main_page=specials&disp_order=1" method="POST">
<input type="hidden" name="style_changer" value="columns"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Column</button>
</form>
<form id="columnsToRows" action="index.php?main_page=specials&disp_order=1" method="POST">
<input type="hidden" name="style_changer" value="rows"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Rows</button>
</form>
I'm also trying for the buttons to call a different stylesheet upon click. This stylesheet is not needed for the display to change from/to rows/columns as I mentioned above. The actual page is written using php as shown below:
<?php $this_page = zen_href_link($_GET['main_page'], zen_get_all_get_params()); ?>
<div id="style_changer">
<?php if($current_listing_style == 'rows') {?>
<form id="rowsToColumns" action="<?php echo $this_page;?>" method="POST">
<input type="hidden" name="style_changer" value="columns"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Column</button>
</form>
<?php } else { ?>
<form id="columnsToRows" action="<?php echo $this_page;?>" method="POST">
<input type="hidden" name="style_changer" value="rows"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Rows</button>
</form>
<?php } ?>
</div>
If the question is "how to change a form in order to use jQuery and avoid the page refresh", then the jquery form plugin is your friend, as it turns any html form into an ajax-powered one.
Simply follow their instructions and you'll get it working in no time (provided your form already works as is).
You can prevent the Default form Submission by preventing the default action on the submit button..
$('button[type=submit]').submit( function(e){
e.preventDefault(); // Stops the form from submitting
});
Well, for a very vague method you can use $.ajax and take advantage of reading the <form>'s pre-existing attributes to decide on submission method and read the elements' values as submissiong data:
$('form').on('submit',function(e){
var $form = $(this);
// submit the form, but use the AJAX equiv. instead of a full page refresh
$.ajax({
'url' : $form.attr('action'),
'method' : $form.attr('type'),
'data' : $form.serialize(),
'success' : function(response){
// process response (make CSS changes or whatever it is
// a form submission would normally do)
}
});
// prevent the normal submit and reload behavior as AJAX is now
// handling the submission
e.preventDefault();
});
However, for this to work you'll need some variation of a stripped-down PHP response just for the purpose of the AJAX request (avoid resending headers, script tags, etc. and just return the raw data that jQuery can use to make a UI decision).

Categories