Here i am trying to send multiple variable values to php page through ajax.
here i am calling javascript function to get the values from form and submit the values to ajax. in the javascript i am getting multiple values from form. now i want to pass all these values to php page.
how can i achieve that?
here is what i have done.
function sendInvite(){
var from_name = document.getElementById('invite_username').value;
var name_string = 'invitename='+ from_name;
var email = document.getElementById('friendemail').value;
var mail_string = 'friendemail='+ email;
var product_name = document.getElementById('invite_productname').value;
var product_string = 'invite-product-name='+ product_name;
var product_link = document.getElementById('invite_url').value;
var link_string = 'invite-url='+ product_link ;
$.ajax({
type : "post",
url : "legoland.php",
data: name_string,mail_string,
cache:false,
success : function(html){
$('.mail-message').html(html);
}
});
}
Html:
<form name="invite-form">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" id="invite_username" name="invitename" value="' . $_SESSION["user_name"] . '">' ;
echo '<input type="hidden" id="invite_url" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" id="invite_productname" class="invite-product" name="invite-product-name">';
?>
<input type="button" name="submit" onclick="return sendInvite();" value="Invite" class="btn btn-primary">
</div>
</form>
php:
<?php
$name = $_POST['invitename'];
$mail = $_POST['friendemail'];
$product_name = $_POST['invite-product-name'];
$product_link = $_POST['invite-url'];
echo $name;
echo $mail;
echo $product_name;
echo $product_link;
?>
From manual:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So the easiest would be change data to
data: { invitename: from_name, friendemail: email }
you can also assign values directly to data variable
data: {
invitename: document.getElementById('invite_username').value,
friendemail: document.getElementById('friendemail').value
}
etc.
Related
I am working with two forms where if user submitted first form the data is inserted using ajax to database and user is redirected to second form(Both Forms are in same file).
When user which is present on second form presses back button the value on the input type text for form1 one to be fetched from db which is stored when user submitted the first form.
My doubt is how can we pass value from ajax call to input type text
Here is my code which i have done uptill now
//Form 1
<form id="titlechange">
<div id="step1">
<input type="text" name="tbl_title" id="title" value="" class="form-control">
<input type="text" name="tbl_description" id="description" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
</div>
</form>
//Form 2
<form id="detailsubmit">
<div id="step2">
<div class = "data"> //input type hidden retreived after submitting from 1 inside class data
<input type="hidden" value="<?php echo $insertData ?>" class="form-control">
</div>
<input type="text" name="city" id="city" value="" class="form-control">
<input type="text" name="state" id="state" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
<button type="button" onclick="editModeForStep1()" name="firstsubmit" class="update-btn" >Back</button>
</div>
</form>
Ajax Call for back button
function editModeForStep1()
{
var formData = new FormData($('#detailsubmit')[0]);
formData.append('action', 'retreive');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'ClientData.php',
data: formData,
success:function(msg){
//what should be written here for displaying value received from `ClientData.php` to value attribute of input type text in form 1
$('#step1').addClass('in active');
alert('success');
}
});
}
ClientData.php
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
$slideOne = $objMaster->getSlideForEdit($insertData);
foreach($slideOne as $key=>$value)
{
echo $title = $value['title'];
echo $description = $value['description'];
}
}
First, let's change ClientData.php to return data in a more usable form.
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
//select first row of results for getSlideForEdit by adding `[0]`
$slideOne = $objMaster->getSlideForEdit($insertData)[0];
//notice array keys match form1 form elements ID
//notice there is no need for a loop here
echo json_encode(
array(
'title' => $slideOne['title'],
'description' => $slideOne['description']
)
);
//if you want to update EVERYTHING from $slideOne, you can just do
//echo json_encode($slideOne);
//instead of the above json_encode()
}
Now our return will contain JSON data instead of plain strings. We can update your success method to update those input boxes.
...
data: formData,
//set dataType to json because we are receiving json from the server
dataType: 'json',
success:function(msg){
$('#step1').addClass('in active');
//if you don't set dataType to json you can also do
//msg = JSON.parse(msg);
//loop through returned array.
$.each(msg, function(index, value) {
//select element by index e.g `#title`, set value
$('#' + index).val(value);
});
alert('success');
}
This solution will dynamically update any input on your page as long as you return a key=>value pair for it from your server.
I am trying to set up a form that allows users to input an id that they've been given. When the ID is submitted, the back-end is checked to see if that id exists and if it does it returns data
I haven't really tried anything I'm just trying to wrap my mind around how to get this done
Here is the form code:
<form action="/action_page.php">
Dealership:<br>
<input type="text" name="dealership">
<br>
Email:<br>
<input type="text" name="email">
<br><br>
Phone Number:<br>
<input type="text" name="phonenum">
<br><br>
Order ID:<br>
<input type="text" name="order_id">
<br><br>
<input type="submit">
</form>
Here is the ajax:
$(document).ready(function (){
$("#works").hide();
var $dealership = $('dealership');
var $email = $('email');
var $phonenum = $('email');
var $order_id = $('order_id');
$('.submit').click (funciton(){
var track = {
dealership : dealership.val(),
email: email.val(),
phonenum = phonenum.val(),
order_id = order_id.val(),
};
$.ajax({
type: 'GET',
url: 'http://testingapi.com/api/order-status',
data: track,
success: function() {
tracking.append();
},
sucess: funciton(itWorked) {
}
});
});
});
It may be necessary to remove the submit type button and add the button type.
Also, in your code the ID is by class $ (". Submit").
then add the class to the button too.
<button type="button" class="submit">Submit</button>
This is fairly simple. Once you've accepted the order_id from the user you can pass it along in your data dictionary like this (along with anything else you want to pass):
data: {
'id': order_id,
}
On your server side you could so something like this to retrieve the ID:
In PHP:
$id = $_GET['id'];
In Django:
id = request.GET.get('id')
Once you've done this you can just query your database and pass this id in the query to check if records match or not.
I have a form in PHP & MySQL and I want to submit it with AJAX.
I Have similar data so I have put these data in a foreach loop.
The problem is that when I try to submit the first row data it all goes well but it changes the data in all rows. and when I try to submit other data except the first row it doesn't submit at all.
I think the problem is because the submit button always gets the same id and therefore goes to the first row always.
I don't know how to get the value in Ajax.
Here goes the code:
//php form
<?php
$pid = $_GET['pid'];
include('config.php');
$timeline_query="SELECT * FROM timeline_table WHERE pid=$pid";
$result_timeline=mysqli_query($conn,$timeline_query);
if(!$result_timeline){
echo "Error: " . $conn->error;
}
$timelines=array();
while($row_timeline=mysqli_fetch_assoc($result_timeline)){
$timelines[]=$row_timeline;
}
?>
<?php
$x = 0;
foreach ($timelines as $timeline):?>
<div class="card">
<div class="card-header" id="heading<?php echo $x; ?>">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse<?php echo $x; ?>" aria-expanded="true" aria-controls="collapse<?php echo $x; ?>">
<?php echo $timeline['timeline_title'];?>
</button>
</h5>
</div>
<div id="collapse<?php echo $x; ?>" class="collapse" aria-labelledby="heading<?php echo $x; ?>" data-parent="#accordion">
<div class="card-body">
<form id="register_form">
<input type="text" id="tid" name="tid" value="<?php echo $timeline['tid']; ?>"/>
<textarea class="form-control" rows="4" id="timeline_description" name="timeline_description"><?php echo $timeline['timeline_description'];?></textarea>
<input id="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</div>
<?php $x++; endforeach;
// ajax function
$(document).ready(function(){
$("#submit").click(function(){
var timeline_description = $("#timeline_description").val();
var tid = $("#tid").val();
alert(timeline_description);
alert(tid);
// Returns successful data submission message when the entered information is stored in database.
// var dataString = 'timeline_description='+timeline_description+'&pid='+ pid + '&tid='+ tid +;
var dataString = 'timeline_description='+timeline_description;
alert(dataString);
if(timeline_description=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "process.php?tid"=+tid,
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
//process.php
<?php
include('config.php');
$tid=$_GET['tid'];
if( $_POST['timeline_description']==NULL ){ $timeline_description=''; }
else { $timeline_description=$_POST['timeline_description']; }
$query_timeline = "UPDATE timeline_table SET
timeline_description='$timeline_description' WHERE tid=$tid ";
$result=mysqli_query($conn,$query_timeline);
if(!$result){
echo "Error: " . $conn->error;
}
?>
Any idea?
Id of elements must be unique. The abnormal behaviour of your code is due to non-unique ids of your input elements.
In the case, If you cannot assign unique ids to elements you can achieve desired output by using this keyword and siblings() method in jquery.
Instead of
var timeline_description = $("#timeline_description").val();
var pid = $("#pid").val();
var tid = $("#tid").val();
try to get values in this way.
var timeline_description = $(this).siblings('#timeline_description').val();
var pid = $(this).siblings('#pid').val();
var tid = $(this).siblings('#tid').val();
I see there a problem with Yours inputs id - <input type="text" id="pid" - this is in foreach, so You have multiple elements with same id. So var pid = $("#pid").val(); will return You always a value of first found element. Try to use arrays:
<input type="text" id="pid[$pid]" name="pid[$pid]" value="<?php echo $pid ?>"/>
<input type="text" id="tid[$pid]" name="tid[$pid]" value="<?php echo $timeline['tid']; ?>"/>
Please remember one thing: id of any element in html PAGE (whole document) must be unique.
I don't appear to have any data being sent when a form is submitted through jquery
A snippet of my issue (code reduced to simplify):
head:
<script>
function dSubmit(formName, formAction, fieldsToCheck, divToHide){
// No Errors process form
var url = formAction; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#" + formName).serialize(), // serializes the form's elements.
success: function(data)
{alert(data)}
});
return false; // avoid to execute the actual submit of the form.
}
</script>
body:
<a onclick="dSubmit('treatmentDetails','treatments/processTreatments.php','','')"><img style="width:35px;" src="i/update-icon.png"/></a>
<form name="treatmentdetails" id="treatmentdetails"
action="processTreatments.php" method="POST">
<input type="text" name="treatmentName" value="<?php echo $treatment;?>"/>
<input type="text" name="treatmentId" value="<?php echo $treatmentId;?>"/><br>
</form>
php (treatments/processTreatments.php):
$table = $dbPrefix."treatmentsOptions";
$treatmentId = $_POST['treatmentId'];
$treatmentName = $_POST['treatmentName'];
$query = mysql_query("UPDATE $table SET name='$treatmentName' WHERE id='$treatmentId'");
echo "variables = id: $treatmentId name: $treatmentName"; // according to jquery submit neither variable appear
You typo treatmentDetails, fix to treatmentdetails.
$("#treatmentDetails").serialize() is return empty string.
your correct code is:
<a onclick="dSubmit('treatmentdetails','treatments/processTreatments.php','','')"><img style="width:35px;" src="i/update-icon.png"/></a>
I would like to update session variable.
Let me introduce this in simple example. We get a div with input fields printed out by PHP script, with some values etc...
Example PHP code:
echo '
<div id="few-input-fields">
<input id="Name" size="20" value="' . $_SESSION['name'] . '" />
<br />
<input id="Lastname" size="20" value="' . $_SESSION['lastname'] . '" />
</div>
<span id="save">save</span>
</div>
';
Let's say user edit this input field (id=Name) and type name "Mark" inside it and then press save text.
On click it should save/update session variable, without reloading page AND refresh input fields.
Is that possible? Perhaps with ajax / jquery? And most importantly how ?
Yes, just do a simple AJAX request. With jQuery it would be:
$("#formid").submit(function(){
$.ajax({
type: "POST",
url: "someFileToUpdateTheSession.php",
data: $(this).serialize(),
success: function(){
// Do what you want to do when the session has been updated
}
});
return false;
});
And your PHP:
<?php
session_start();
$_SESSION["name"] = $_POST["name"];
// Add the rest of the post-variables to session-variables in the same manner
?>
Note
You need to add name-attributes to your input-fields.