Pass JavaScript argument to PHP with ajax - javascript

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"/>

Related

refresh post user without refresh page ajax not working

i don't know , not working !
-i have table post for user
i want display post without refresh page used ajax
<form class="posting" method="POST" autocomplete="off"
action="createpost.php">
<textarea name="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
</form>
// code mysql the same page
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
(jquery exist in page index ) ( )
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'createpost.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
- but not working
Change this button. Since you want to run an AJAX call It shouldn't be a SUBMIT.
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
to this
<button class="btn-ajouter" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
and change your JQuery from
$('form').on('submit', function (e) {
to
$('#ajouter').on('click', function (e) {
Also, you won't need to e.preventDefault();
Seems like that you are trying to display the information on the same page where the user submits the form. I would advise you to put the php code in a separate file and then print it somewhere on the page with javascript. A sample code for that would be something like this:
Javascript code on your current page
<script>
$(function () {
// I actually agree with Lawrence Cherone's suggestions here, so i'm including them
$('form.posting').on('submit', function (e) {
form_data = $(this).serialize()
e.preventDefault();
$.ajax({
type: 'post',
url: 'separate.php',
data: form_data,
success: function (response) {
//then you can have the server output as an object
response = JSON.parse(response);
//And print it somewhere, for example:
$('#someDiv').html(response.whatever);
}
});
});
});
</script>
Code for php in a separate file
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
$row = $stmt->fetch();
echo json_encode($row['post']);
Change this form,
<form class="posting" method="POST" autocomplete="off" onSubmit="return false">
<textarea name="text" id="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
</form>
Ajax Goes Here,
$(function(){
$("#ajouter").click(function(){
var text=$("#text").val();
$.ajax({
url:"createpost.php",
method:"POST",
data:{text:text},
cache:false,
success:function(data){
$("#result").load(location.href+ "#result");
}
});
});
});
PHP & HTML Code goes here
<div id="result">
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
</div>

Ajax call to a php file is not working

I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.
index.html
<html>
<head>
<script>
function submitForm(formId){
//var formData= $.(formId).serialize();
$.ajax({
url:'new-user.php',
type:'POST',
data:{
user_name=$("#user_name").val(),
password=$("#password").val();
}
success:function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>
</html>
new-user.php
<?php include 'database.php';?>
<?php
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
$name_error="name is required";
}
mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
echo "<p>Credentials added</p>";
echo "<a href='index.html'>Go back</a>";
}else{
echo "<p>Error</p>";
echo mysqli_error($connect);
}
?>
database.php
<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
echo 'failed to connect';
}
?>
The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.
Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm
Change your function to this:
function submitForm(formId){
$.ajax({
url:'/new-user.php',
type:'POST',
data:{
user_name: $("#user_name").val(),
password: $("#password").val()
}
})
.complete(function (response) {
alert(response)
})
return false; // Prevents the form from submitting the standard way
}
EDIT: Change the form to this:
<form onsubmit="return submitForm('#myForm');" id='myForm'>
In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success
Also, to avoid refreshing the page, insert return false; at the end of the function submitForm

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

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.

Calling ajax inside ajax html return prevents first ajax script from further working

HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
...
...
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div> // placeholder for html code that is returned
<script> // main script
var form=$('#validate_mail');
form.submit(function(ev){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize(),
success : function(result{
$('#validate_mail_result').html(result);
}
});
ev.preventDefault();
});
</script>
PHP (which is called by the main script)
<?php
...
...
// Connect to MySQL
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$connection = new mysqli($servername,$username,$password);
if (mysqli_connect_errno()){
printf("MyErrorMsg: %s\n", mysqli_connect_error());
exit();
}
// Perform request
$mail_name = $_POST[mail_name];
$full_mail_name = $mail_name . "#mydomain.me";
$connection->select_db("MAILSERVER");
$queryMailExists = "SELECT id FROM users WHERE mailname = '" . $mail_name . "'";
$resultMailExists = $connection->query($queryMailExists);
$row_cnt = $resultMailExists->num_rows;
$connection->close();
if (is_valid_email_address_5321($full_mail_name)==0){
echo "Not a valid email-address according to RFC5321";
}elseif(row_cnt==0){ //check if email name allready taken
echo "Mail available";
echo "
<form id=\"purchase_mail\" action=\"/wp-content/custom-php/purchase_mail.php\" method=\"POST\">
<input id=\"password\" style=\"width: 280px;\" name=\"password\" type=\"password\" value=\"\" />
<div id=pswrd_struct_chk></div>
<input id=\"password_retyped\" style=\"width: 280px;\" name=\"password_retyped\" type=\"password\" value=\"\" />
<div id=pswrd_match_chk></div>
<script> // this script and the one after this are blocking the main script
var form=$('#purchase_mail');
$('#password').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_structure_check.php\",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val(\"\");
$('#pswrd_match_chk').html(\"\");
});
</script>
<script>
var form=$('#purchase_mail');
$('#password_retyped').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_match_check.php\",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
<input type=\"submit\" value=\"PAY\" />
";
}else{
echo "<div>Mailname allready taken!</div>";
}
?>
When i comment out the two last scripts everything works as intended. The 3 different if-cases in the PHP do echo their html codes into the placeholder but when i leave the scripts uncommented once the "elseif(row_cnt==0)" section is executed the main script gets stuck and i do not get any echo for the other two if-cases no matter what is submited (enterd in the input field with the id=mail_name).
I was not able to google my problem.
Thanks for your time end effort.
AJAX does not allow script tags to be passed in the results when type is HTML. Supposing that you somehow manage to pass the scripts, you will still have to retrigger the script which is somewhat bothersome.
I would suggest you to write the html adding code in the success message and passing on the variables such as form action, URLs, etc from PHP. This way you won't face those issues and you will also be able to get the job done.
I checked your code. You can try doing something like:
First AJAX:
$.ajax({
//logic for the first ajax
}).done(function(){
//**second ajax**
})
First of all you should follow the rule:
in php script - just php code, no js and css; in js script - just js, no css.**
It not just a good style, it will help you to facilitate your work!
I just move your html and js from validate_mail.php to main page, and it looks like:
<html>
<head></head>
<body>
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input id="btn_validate_mail" type="button" value="submit" />
</form>
<div id="validate_mail_result1" style="display: none;">Not a valid email-address according to RFC5321</div>
<div id="validate_mail_result2" style="display: none;">
Mail available
<form id="purchase_mail" action="/wp-content/custom-php/purchase_mail.php" method="POST">
<input id="password" style="width: 280px;" name="password" type="password" value="" />
<div id="pswrd_struct_chk"></div>
<input id="password_retyped" style="width: 280px;" name="password_retyped" type="password" value="" />
<div id="pswrd_match_chk"></div>
</form>
</div>
<div id="validate_mail_result3" style="display: none;">Mailname allready taken!</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('#btn_validate_mail').click(function () {
var form = $('#validate_mail');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (result) {
$('#validate_mail_result'+result).show();
},
error: function (xhr, status, error) {
// If you will receive any errors - you will see it here.
console.log(error);
},
complete: function () {
form.hide();
}
});
});
$('#password').keyup(function(ev){
var form=$('#purchase_mail');
$.ajax({
type : form.attr('method'),
url : "/wp-content/custom-php/password_structure_check.php",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val("");
$('#pswrd_match_chk').html("");
});
$('#password_retyped').keyup(function(ev){
var form=$('#purchase_mail');
$.ajax({
type : form.attr('method'),
url : "/wp-content/custom-php/password_match_check.php",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
</html>
It looks much better, but still terrible. And js don't should be here, and css too.
Now validate_mail.php looks:
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$connection = new mysqli($servername,$username,$password);
if (mysqli_connect_errno()){
printf("MyErrorMsg: %s\n", mysqli_connect_error());
exit();
}
// Perform request
$mail_name = $_POST['mail_name'];
$full_mail_name = $mail_name . "#mydomain.me";
$connection->select_db("MAILSERVER");
$queryMailExists = "SELECT id FROM users2 WHERE mailname = '" . $mail_name . "'";
$resultMailExists = $connection->query($queryMailExists);
$row_cnt = $resultMailExists->num_rows;
$connection->close();
if (is_valid_email_address_5321($full_mail_name)==0){
echo 1;
}elseif($row_cnt==0){ //check if email name allready taken
echo 2;
}else{
echo 3;
}
So much easier...
I don't want talk about xss, sql injections and else, because your question not about it, but you should remember about it.
You need to continue separate js and html and css...
I just try to show how it can be much easier to reach what you need... hope it will be helpful...
Good news. You just had typos in your code. I ran the relevant parts on a local server and your scripts are executing as expected. Enjoy!
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form id="validate_mail" action="validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div>
<script> // main script
var form = $('#validate_mail');
form.submit(function(ev){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize(),
// success : function(result{ <-- typo
success : function(result){
$('#validate_mail_result').html(result);
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP - validate_mail.php
<?php
// }elseif(row_cnt==0){ <-- typos here too, maybe more above, didn't check
// }else if($row_cnt == 0){
echo "Mail available";
echo "
<form id=\"purchase_mail\" action=\"/wp-content/custom-php/purchase_mail.php\" method=\"POST\">
<input id=\"password\" style=\"width: 280px;\" name=\"password\" type=\"password\" value=\"\" />
<div id=pswrd_struct_chk></div>
<input id=\"password_retyped\" style=\"width: 280px;\" name=\"password_retyped\" type=\"password\" value=\"\" />
<div id=pswrd_match_chk></div>
<script> // this script and the one after this are blocking the main script
var form=$('#purchase_mail');
$('#password').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_structure_check.php\",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val(\"\");
$('#pswrd_match_chk').html(\"\");
});
</script>
<script>
var form=$('#purchase_mail');
$('#password_retyped').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_match_check.php\",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
<input type=\"submit\" value=\"PAY\" />
";
//}else{
// echo "<div>Mailname allready taken!</div>";
//}
?>
Ignoring the already-mentioned errors here (invalid HTML, invalid PHP, etc.), your easiest (and best) solution to this is simply to refactor your code so it doesn't return the HTML/JS. Just put all of the HTML/JS that is currently being returned by the PHP into your page and hide it. Have the PHP return a status code of some sort ("invalid-email"/"ok"/"taken", etc.) and have jQuery hide/unhide the appropriate response on the page. This keeps a separation of concerns between your presentation and your business logic.
If you are using jQuery version 1.7 and above
Change
var form=$('#validate_mail');
form.submit(function(ev){
$.ajax({
To:
var $(document).on('submit','#validate_mail',function(ev){
$.ajax({
Also try and keep your JQuery scripts together maybe in a main.js file and definitely outside and away from your PHP. So you should write the JS for the #purchase_mail directly under your #validate_mail submit function in the same way as I described and it will work when you ajax your form into the page.
The script you are pulling in with Ajax will not work unless you evaluate eval() it somehow but doing that will open your script up to potential security vulnerabilities.
Hope that helps dude

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