How to get value from php to input using ajax request [duplicate] - javascript

This question already has answers here:
ajax calling of php function from a php page
(6 answers)
Closed 6 years ago.
Hi My question is how can I get the value from php script using an ajax with a onclick event.
I have a text field and a button
<button type="button" class="btn btn-primary" onclick="getid(this)">Generate ID</button>
<input type="text" name="pin" class="form-control" readonly>
And here is my php script named getrowcount.php
include_once 'conx.php';
$query ="SELECT * FROM patientprofile";
$result = $DBcon->query($query);
$count = $result->num_rows;
if ($result) {
if($count >= 0){
$count_res = $count += 1;
$idnum = $count_res;
$test = str_pad($idnum, 5, "0", STR_PAD_LEFT);
}
}
And now my problem is how can I get the value from $test and put it in the input text field using ajax.

You can use AJAX to display the output from the query in the input field.
Step 1: Add this line of code to the bottom of getrowcount.php:
echo $test;
Step 2: Amend your HTML so that it looks like this:
<form id="get">
<input type="text" id="pin" name="pin" class="form-control" readonly>
<input type="submit" class="btn btn-primary" value="Generate ID">
</form>
Step 3: Add this script to the bottom of the page.
<script>
$(document).ready(function(){
$("form#get").submit(function(event) {
event.preventDefault();
var input = $("#pin");
$.ajax({
type: "POST",
url: "getrowcount.php",
success: function(data) { input.val(data); }
});
});
});
</script>

May be this will help you
Your PHP code :
<?php
// Your database query and results store in $test
echo $test;
?>
Your ajax call should be -
$.ajax("getrowcount.php").done(function(data) {
$('.form-control').val(data);
})

You could use the jQuery method $.get() in your javascript script :
function getid(_this){
$.get('php_script_url.php',{},function(response){
alert(response);
$("[name=pin]").val(response);
})
}
Then in your PHP script you should add echo to the result you want to return :
echo $test;
Hope this helps.

For this you'd run the ajax call on button press, load the php from the ajax, in the php do an echo with the variable you want to use, then in the ajax success section, you'd use the returned variable.

Related

How to post both a javascript variable and a html form via $.ajax post?

I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz

Pass JavaScript argument to PHP with ajax

I need to be able to send a JavaScript variable to a PHP function. I was able to get it working for hard-coded values such as the code below.
<button onclick="submitform()">Click me</button>
<script>
function submitform(){
document.write(' <?php send_mail('hello'); ?> ');
}
</script>
<?php
function send_mail($subject){
//$subject => 'hello'
//Do something with subject
}
?>
However, I cannot replace the hard-coded value with a variable. I would also like to find another way to issue the PHP function call. I believe the solution lies in an ajax request. I cannot find a way to do this with the PHP code directly embedded as it is now. All of the other examples I cannot get to work. If possible, I would appreciate a demo as well. Thanks!
You can do it using forms:
<form action="send_mail.php" method="post">
<input type="text" id="mail" name = "mail">
<input type="submit" class="btn" value="Send Mail">
</form>
Then you can access the mail using $_POST["mail"] from the send_mail.php page
Another way to do it is ajax:
$.ajax({ url: '/send_mail.php',
data: {action: 'sendEmail', mymail:$('#mail').val()},
type: 'post',
success: function(output) {
alert(output);
}
});
Then in the send_mail.php page you can do:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
$mail = $_POST['mymail'];
switch($action) {
case 'sendEmail' : send_email();break;
// ...etc...
}
}
Demo for same page call:
<?php
if(isset($_GET['action'])=='myfunc') {
echo "Hello";
}
?>
<form action="?action=myfunc" method="post">
<input type="text" id="mail" name = "mail">
<input id="clickMe" type="submit" value="clickme"/>

How to increment number of fields in php using javascript or jquery or ajax without reload whole page

I have a form in yii and there is a text field named certificate_name in it.
Now i want that when I click on the plus icon, the text field should increment by one and appear below the previous field.
Here is my php code:
<?php for ($i = 0; $i <= $_REQUEST['total_certi']; $i++) { ?>
<div class="pr-ser">
<div class="row">
<?php echo $form->labelEx($model4, 'certificate_name'); ?>
<?php echo $form->textField($model4, 'certificate_name', array('maxlength' => 300)); ?>
<?php echo $form->error($model4, 'certificate_name'); ?>
</div><!-- row -->
</div>
<?php } ?>
<p id="demo"></p>
<div class="row buttonsub">
<input type="button" id ="trainer_certi" onclick="myFunction()" value="Add" />
</div>
There is no issue if I increment the whole div instead of a fild. I can manage this. My JavaScript code is as below:
<script>
function myFunction() {
var value = parseInt(document.getElementById('demo').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('demo').value = value;
var total_certi = value;
alert(total_certi);
}
</script>
If I get the result in $_REQUEST['total_certi'] and if it works in for loop then I complete my work.
Here I can get incremented value in alert in script but how to apply this value to php and increment the number of field without reloading page?
You can do using ajax request but for multi text fields you need to write/array certificate_name[] instead of certificate_name.
here is working & simple codes for you -
Add More Button -
<a class="btn btn-primary add-more" href="#">Add More</a>
Add More Field JS Code -
$('.add-more').live('click', function(){
var url_path = ''; //your project base url
$.ajax({
url:url_path+'?r=ajax/addmore',
data:'req=add_more',
dataType:'html',
type:'POST',
async: true,
cache: false,
success:function(resp){
$('.pr-ser').append('<div class="row">'+resp+'</div>');
},
error:function(er){
alert("An error has occured, Please reload/refresh the page and try again.");
}
});
return false;
});
Write code into your Ajax Controller -
public function actionAddmore(){
if(Yii::app()->request->isAjaxRequest){
$cert_name = CHtml::textField('certificate_name[]', '', array('maxlength'=>'300'));
echo $cert_name
}
}
If you are using Yii2 - have a look at following extension: Yii2 Dynamicform. I've used it in my project and it does exactly that you are trying to build.

Table form dynamically refresh with php and ajax

I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.

Why I can not receive data from jQuery (PHP)?

I have a PHP form:
<form action="" method="post" id="CheckBoxForm">
foreach ( $results as $result ) :
<input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).'"/>
<input type="submit" name="submit" value="Submit"/>
</form>
I take values from it in js file:
jQuery('#CheckBoxForm').on('submit', function(e) {
var chkArray = [];
var CheckBoxForm=jQuery(this).serialize();
alert(CheckBoxForm);
jQuery(".chk:checked").each(function() {
chkArray.push($(this).val());
});
var selected;
selected = chkArray.join(',') + ",";
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: selected,
success:function(data){
jQuery("#feedback_country").html(data);
}
});
return false;
});
});
If I alert selected it gives me list of values. So script has initialized and took data.
At the end of the script it receive feedback data html(data) and send it back to initial php file.
PHP file which take request from js file (POST REQUEST) has such code:
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}
And it send back 0. I can't understand what is wrong.
You have too much extra code in your JavaScript that is unneeded. You don't need those chkArray or selected variables.
jQuery('#CheckBoxForm').on('submit', function(e) {
var CheckBoxForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: CheckBoxForm,
success:function(data){
jQuery("#feedback_country").html(data);
}
});
return false;
});
That should be all you need. serialize() will take all the values from the form and create a string in the correct format to be sent to your PHP script.
Note: Your HTML is incorrect, your form should look like this:
<form action="" method="post" id="CheckBoxForm">
<?php foreach($results as $result): ?>
<input type="checkbox" class="chk" name="check_list[]" value="<?=$result->meta_value?>"/>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
You want to use the name attribute, not id on your checkboxes.
Your problem is that you are sending a single string instead of key - value pairs:
selected = chkArray.join(',') + ",";
...
data: selected,
Although I would not recommend building the query string manually - serialize() will take care of the correct escaping - you can send your check-list string like:
data: {check_list: selected},
Edit: Now in php you will have a $_POST['check_list'] variable but that is a list in a comma-separated string. So to convert it into an array and loop over it, you would need something like:
$arr = explode(',', $_POST['check_list']);
foreach ($arr as $selected) {
echo $selected."</br>";
}

Categories