Syntax to get PHP variables into jQuery Ajax - php

I have a php function:
<?php
function send_message($userid, $projectid, $message) {
//some code
}
$userid = '1';
$projectid = '2';
$message = 'hello';
?>
<form id="myform" method="post" action="">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
</form>
I want the submit button to do jQuery Ajax so my page won't refresh:
js:
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: //my valid url,
type: 'post',
dataType : 'json',
data: {
action: 'send_message', //this is the PHP function
projectid: projectid //how do I write this?,
userid: userid //how do I write this?,
message: message//how do I write this?'
},
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
On my error.log, I get NULL for the 3 parameters because I'm not sure how to access them from my PHP. How do you access the PHP variables from jQuery?

Put your PHP variables into hidden inputs so they'll be automatically sent when it is submitted.
For example : <input type="hidden" name="userid" value="1">
Serialize the form data : var formData = $(form).serialize();
On submit attach your form data :
$.ajax({
url: admin_ajax.ajax_url,
type: 'POST',
data: formData
})
Access it from PHP with a classic way : $_POST['userid']

<form id="insert_form">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" id="send" value="send message">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid= '1'; ?>">
<input type="hidden" name="projectid" id="projectid" value="<?php echo $projectid='2'; ?>">
<input type="hidden" name="message" id="message" value="<?php echo $message=
'hello'; ?>">
</form>
var project-message=document.getElementById('project-message').value;
var send=document.getElementById('send').value;
var userid=document.getElementById('userid').value;
var projectid=document.getElementById('projectid').value;
var message=document.getElementById('message').value;
$.ajax({
url:"your_url.php",
type:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
}
})

You can get all the values of the form, and submit it.
Also you can set other the values in the form as hidden.
<form id="myform" method="post" action="" id='form1'>
<textarea name="projectMessage" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
<?php print "<input type='hidden' value='$userid' > "; name='userid' ?>
<?php print "<input type='hidden' value='$projectid' > "; name='projectid' ?>
<?php print "<input type='hidden' value='$message' > "; name='message' ?>
</form>
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
dataType:'json',
data: $("#form1").serialize(),
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
I like this approach because I can reuse the ajax multiple times or even create a generic function to submit the form on the background with ajax. Also I can fill the form using a for each loop in php, having all the values in an array (like a database result)
ex.
<?php
foreach($values as $k=>$v}{
print "<input name='$key' value='$v'>\n";
}
?>

Related

Ajax POST multiple forms with multiple PHP destinations

I have a page with two forms and each form uses a different PHP page for its post. I can only find examples / documentation on using multiple forms with the same PHP post script. I am struggling to get this to work, can any help ?
This is the JQUERY, that works if i use one form, I've tried to add an ID tag but it didn't seem to work:
$(function () {
$('form').on('submit', function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Suppiler Amended!');
}
});
});
});
</script>
</head>
<body>
<?php
echo "<div class='table1'>";
echo "<div class='datagrid'>";
echo "<table id='tblData2'><thead><tr><th>Notes</th><th>Updated By</th><th></th></thead></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
?>
<tbody><tr>
<td><FONT COLOR='#000'><b><?php echo "".$row["notes"].""?></td>
<td><FONT COLOR='#000'><b><?php echo "".$row["enteredby"].""?></td>
<td><FONT COLOR='#000'><b><a href="edit.php">
<form name="edit" action="script1.php" method="post">
<input type="hidden" name="notes" value="<?php echo"".$row["notes"]."";?>">
<input type="hidden" name="noteid" value="<?php echo"".$row["noteid"]."";?>">
<input type="submit" value="EDIT">
</form>
</a></td>
</tr></tbody>
<?php
$companyid = "".$row['id']."";
}
?>
</table>
</div>
<br>
<form name="notes" action="add-note.php" method="post">
ADD NEW NOTE:<br>
<input type="text" name="newnote" style="height:120px;width:200px;"><br>
<input type="hidden" name="companyid" value="<?php echo"".$companyid."";?>">
<input type="hidden" name="user" value="<?php echo"".$user."";?>">
<br>
<input type="submit" value="ADD NOTE">
</form>
You have to loop over your forms:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$('form').each(function(i, form) {
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Note has been edited!');
}
});
})
});
});
What you need to do is to simply get the action attribute dynamically. You can do that easily with form.attr('action'); inside the function. See bellow -
$(function () {
$('form').on('submit', function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Note has been edited!');
}
});
});
});
Update:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<body>
<form name="edit" action="script1.php" method="post">
<input type="hidden" name="notes" value="1">
<input type="hidden" name="noteid" value="2">
<input type="submit" value="s1">
</form>
<form name="edit" action="script2.php" method="post">
<input type="hidden" name="notes" value="1">
<input type="hidden" name="noteid" value="2">
<input type="submit" value="s2">
</form>
<script type="text/javascript">
$(function () {
$('form').on('submit', function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Note has been edited!');
}
});
});
});
</script>
</body>
</html>

How to retrieve data from serialized jQuery string

How to retrieve data when post using AJAX my function is that
jQuery("#wp_pass_reset").submit(function() {
var url = document.getElementById('imgurl').innerHTML;
var url2 = document.getElementById('adminurl').innerHTML;
jQuery('#result').html('<span class="loading"><img src="' + url + '/img/load.gif" /></span>').fadeIn();
var input_data = jQuery('#wp_pass_reset').serialize();
jQuery.ajax({
type: "POST",
url: url2 + 'admin-ajax.php',
data: {
action: 'resetpass_process',
value: input_data,
},
success: function(msg){
jQuery('.loading').remove();
jQuery('<div>').html(msg).appendTo('div#result').hide().fadeIn('slow');
}
});
return false;
});
This is the form:
<form class="user_form" id="wp_pass_reset" action="" method="post" name="wp_pass_reset">
<h1>
Enter Your Email or Username
</h1>
<input type="text" class="text" name="user_input" value=""><br>
<input type="hidden" name="action" value="tg_pwd_reset">
<a class="close">X</a>
<input type="hidden" name="tg_pwd_nonce" value="'.wp_create_nonce(">
<input type="submit" id="submitbtn" class="reset_password btn" name="submit" value="Reset Password">
</form>
When I retrieve data using $_POST['value'] all of my data show but when I use $_POST['user_input'] an error happens.
What can I do?
Here, you are submitting form by ajax then you have to pass it in data like,
data: {
action: 'resetpass_process',
value: input_data,
user_input : $('input[name="user_input"]').val(),
// add more parmeters which you need
},
Add user_input from your form field name to data object:
...
data: {
action: 'resetpass_process',
value: input_data,
user_input: $('input[name="user_input"]').val()
},
...

Get the textbox Text using ajax on button click

I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});​
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});​
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()

Submiting form with jquery

I have a form and I need to add some data from database before submiting it.
My html code is:
<form action="https://91.199.226.106/services/authorize.php" id="arca" method="POST">
<input type="hidden" name="hostID" id="hostID"/>
<input type="hidden" name="mid" id="mid" />
<input type="hidden" name="tid" id="tid" />
<input type="hidden" name="additionalURL" id="additionalURL" />
<input type="hidden" name="orderID" id="orderID" />
<input type="hidden" name="currency" id="currency" />
<input type="hidden" name="opaque" />
amount<input type="text" name="amount" id="amount" value="" /><br>
<input type="submit" value="submit" />
</form>
<div id="script_area"></div>
<div id="error_area"></div>
And I have an event handler for form submit. Here is the code:
$("#arca").submit(function(e){
e.preventDefault();
var data="amount="+$("#amount").val()+"&&lang=eng";
$.ajax({
url: "ajax/get_arca_submit_params.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
var splited=html.split("|",2);
if(splited[0]=="0")
{
$("#error_area").html(splited[1]);
}
else
{
$("#script_area").html(splited[1]);
$("#arca").submit();
//alert("aaaaa");
}
}
});
});
The PHP returns
"0|error message" or "1|script that sets fields values" that I place
in the div with id="script_area"
. The problem is that $("#arca").submit(); line ceeps on submiting the form on and on. How can I solve this problem? Thanks for help.
Replace $("#arca").submit(); with $("#arca")[0].submit();. This way you are calling the submit event on the underlying DOM element which won't trigger your callback and avoid the infinite loop.
You could change to bind a click event to submit button instead.
$("#arca").find('input[type="submit"]').click(function (e) {
e.preventDefault();
var data = "amount=" + $("#amount").val() + "&&lang=eng";
$.ajax({
url: "ajax/get_arca_submit_params.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
var splited = html.split("|", 2);
if (splited[0] == "0") {
$("#error_area").html(splited[1]);
} else {
$("#script_area").html(splited[1]);
$("#arca").submit();
//alert("aaaaa");
}
}
});
});

submitting two forms via javascript without click

i am using the following code to auto-submit a form
<script type="text/javascript">
$(function () {
$('#submit').click();
});
</script>
<div style="display:none">
<form method="post" action="http://mydomain/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form>
</div>
i want to submit the same data to two urls ...
http://mydomain/texting/register.php?list_id=15
http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>
how can edit my code to submit same form data automatically?
i tried this code
<script type="text/javascript">
function submitTwice(f){
f.action = 'http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>';
f.target='ifr1';
f.submit();
f.action = 'http://mydomain.com/texting/register.php?list_id=15';
f.target='ifr2';
f.submit();
}
</script>
*/
<script type="text/javascript">
$(function () {
$('submitTwice(f)').click();
});
</script>
<div style="display:none">
<iframe name="ifr1" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
<div style="display:none"><iframe name="ifr2" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
but it is not working, any suggestion to make it happen, the same data is to be sent to both the urls automatically using javascript
You can use jQuerys ajax and send the data with post, to both the urls.
first save all data you want to send in an valid data array. if you want it automated, you can do something like this:
var sendData = {};
$("#formId").find("input").each(function(i, item){
sendData[item.name] = item.value;
});
or as a simple string:
var sendData = "name=value&email=value";
then send the form data to both urls with ajax, as post type:
$.ajax({ url: "http://url1/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
$.ajax({ url: "http://url2/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
Note: make sure to return false to the button or sending form, you can do that something like:
$("formId").submit(function(){
// do ajax send data
return false;
}
EDIT: added unchecked code for this, with comments
$(document).ready(function(){
// grab the form and bind the submit event
$("#formId").submit(function(){
// collect all the data you want to post
var sendData = {};
this.find("input").each(function(i, item){
sendData[item.name] = item.value;
});
// send the request to both urls with ajax
$.ajax({ url: "url1", type: "POST", data: sendData,
success: function(response){
// handle response from url1
alert(response);
}
});
$.ajax({ url: "url2", type: "POST", data: sendData,
success: function(response){
// handle response from url2
alert(response);
}
});
// return false, to disable default submit event
return false;
});
});
just send name and email to the server script in a regular form,
then do two requests from within your register.php with something like HttpRequest or the like...
some freehand code:
client:
<form id="autoSubmitForm" method="post" action="/register.php?list_id=15">
<input type="hidden" name="name" value="<?php data['name2']; ?>" />
<input type="hidden" name="email" value="<?php data['email2']; ?>" />
<input type="submit" name="submit" value="Sign Up" style="visibility:hidden;" />
</form>
<script>
$(document).ready(function(){
$('#autoSubmitForm').submit();
});
</script>
server:
<?php
$name = $_POST["name2"];
$email = $_POST["email2"];
$url1 = 'http://lala'; //or relative to server root: '/lala'
$url2 = 'http://other';
sendRequest($url1, $name, $email);
sendRequest($url2, $name, $email);
?>
The implementation of sendRequest is worth another question (or reading the documentation of HttpRequest mentioned above)
Good luck, I see your duplicate question got closed...

Categories