I'm trying to POST multiple AJAX data to update.php. This is my code at the moment:
$.ajax({
url:"update.php",
method:"POST",
data: $('#update_form').serialize(),
beforeSend:function(){
$('#update').val("Geupdate!");
},
success:function(data){
$('#update_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
However I also want to sent an ID within the data. This is the form that I'm using.
<form method="post" id="update_form">
<label>Notitie:</label>
<input type="text" name="name" id="' . $row["id"] . '" class="form-control" value='.$row["name"].' width="100%">
<br />
<input type="submit" name="update" id="update" value="Opslaan" class="btn btn-success" />
</form>
How can I combine data: $('#update_form').serialize() and id="' . $row["id"] . '" together?
I tried a few combinations but I can't find the correct answer. Here is what I've tried:
data: $('#update_form').serialize(), id: <?php echo $row["id"] ?>
One simple way is add a hidden input to the form so serialize() will include the id
<form method="post" id="update_form">
<input type="hidden" name="id" value="' . $row["id"] . '" >
<label>Notitie:</label>
<input type="text" name="name" id="' . $row["id"] . '" class="form-control" value='.$row["name"].' width="100%">
<br />
<input type="submit" name="update" id="update" value="Opslaan" class="btn btn-success" />
</form>
You are serializing entire form, which includes your textbox data as well. So, you don't need to explicitly add each element of form.
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls, such as <input>, <textarea>, and <select>: $("input, textarea, select" ).serialize();
So, whatever element added in form (<input>, <textarea>, and <select>) gets serialized implicitly. So, in case, you wanted to pass additional data along with form, then you can create a hidden field inside your form.
I don't use jQuery so this is a bit of a "stab in the dark" but you could alternatively use a FormData object and append a new parameter & value to it like this perhaps.
$.ajax({
var form=$('#update_form');
var fd=new FormData( form[0] );
fd.append('id', document.querySelector('input[name="name"]').id );
url:'update.php',
method:'POST',
data: fd,
beforeSend:function(){
$('#update').val('Geupdate!');
},
success:function(data){
form[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
Related
From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>
Given is:
<input type='text' name='firstname' id='firstname'>
<input type='text' name='lastname' id='lastname'>
<input type='text' name='username' id='username'>
<input id='pw' name='pw' type='password'>
I try to submit the data with an ajax-post-request like this:
var myData = "firstname="+ $('#firstname').val() + "&lastname="+ $('#lastname').val() + "&username="+ $('#username').val() + "&pw="+ $('#pw').val();
$.ajax({
type: "POST",
url: "php/register.php",
dataType:"text",
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
}
How to submit this data in a kind of this way correctly tho the php-file which corresponds to the database? Is a <form> needed for submitting with a button?
There are many solutions to this problem as many have mentioned. Easiest from my point of view is to wrap the fields in a form.
Bind a submit event which fires a callback when your form is submitted.
Serialize the form using .serialize() creating a text string in standard URL-encoded notation of all valid input fields and their values (so you don't have to build this query string yourself)
Post your data using $.post and handle the response using the success callback
Below is a fully functional snippet. You can see the data sent to PostBin here.
// PostBin CORS
$.ajaxSetup({crossDomain:true})
// Submit handler
$('form').on('submit', function(event) {
event.preventDefault();
var $form = $(this)
$.post(
'http://postb.in/ADC3a3Vm',// replace with php/register.php
$(this).serialize(),
function(response){
$("#response").append(response);
$form[0].reset()
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="firstname" placeholder="First Name">
<input type="text" name="lastname" placeholder="Last Name">
<input type="text" name="username" placeholder="Username">
<input type="password" name="pw" placeholder="Password">
<button type="submit">Submit</button>
</form>
<div id="response"></div>
you can use serialize() jQuery function
var myData = $("form").serialize();
in this case <form> is required
Read here
I am try to post a data from a from I have this code on my html.
<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
e.preventDefault();
var testData = $("#test").serialize();
$.ajax({
type: "POST",
url: "ajaxSurvey.php",
data: {survey:testData}
});
});
})
</javascript>
and my form
<form id="test" name="test" method="POST">
<input name="surveyperiod" id="surveyperiod" type="date">
<input name="deadline" id="deadline" type="date" >
<input type="submit" id="btnsubmit"name="btnsubmit" value=" Update ">
</form>
and my php page
if(isset($_POST['survey']){
$myDate = $_POST['survey'];
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES (????????)');
}
Now how can I deserialize $myDate which is look like below
surveyperiod=2014-02-25&deadline=2014-02-18
Tricky method is use parse_str()
// Access as Variable
if( isset($_POST['survey']) ){
// surveyperiod=2014-02-25&deadline=2014-02-18
parse_str($_POST['survey']);
$S_Period = $surveyperiod;
$S_Deadline = $deadline;
// do whatever you want
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ( "'.$S_Period.'", "'.$S_Deadline.'" )');
}
Explanation:
In you Ajax Request you send the data via POST method( data: {survey:testData} ) and assigned a POST variable that is survey and this POST variables contains the data string surveyperiod=2014-02-25&deadline=2014-02-18 as you assigned in your javascript testData. Now what we have to do is, Now we have to parse string into variables and parse_str() inbuilt function do it for you. That's it :)
You do not need to deserialize, you can do that in different way by putting hidden field like;
HTML:
<form id="test" name="test" method="POST">
<input name="survey" type="hidden" value="true"/>
<input name="surveyperiod" id="surveyperiod" type="date">
<input name="deadline" id="deadline" type="date" >
<input type="submit" id="btnsubmit"name="btnsubmit" value=" Update ">
</form>
PHP:
if(isset($_POST['survey']){
$myDate = $_POST['survey'];
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ($_POST["surveyperiod"], $_POST["deadline"])');
}
JS:
<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
e.preventDefault();
var testData = $("#test").serialize();
$.ajax({
type: "POST",
url: "ajaxSurvey.php",
data: testData
});
});
})
</javascript>
By doing this, you dont neede to post data like {survey:testData}. Simply add,
<input name="survey" type="hidden" value="true"/>
html and check hidden field on php side. If a field with name survey exists, then run your code
I have a problem, and i don't know how to get an id of a specific form when in the same page there is several form. Each form has a different id :
HTML :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
And this is the ajax
Jquery :
$('[id^=acheter]').submit(function() {
var CurrenID = $(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: $('#'+CurrenID).serialize(),
success: function(data) {
Method();
}
});
return false;
});
$('[id^=acheter]').submit(function() {
var data = $(this).serialize()+"&form_id="+$(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: data,
success: function(data) {
Method();
}
});
return false;
});
That will add your ID to the form post data?
in this line:
$('[id^=acheter]').submit(function() {
change to
$('#acheter').submit(function() {
Note that the id must be unique if you want to get more than one value from diferent tags use name or class.
to check the forms using the id just make a input button instead input submit, each one with a diferent variable to the jquery and submit .
example :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="button" id="addToCart1" name="addToCart" onclick="submitF('1')">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="button" id="addToCart2" name="addToCart" onclick="submitF('2')">Add</button>
</form>
Then use jquery/javascript to check what button was clicked
function submitF(var)
{
if (var == 1)
{
...
/*do what you want knowing that the first form was clicked,
submit form with jquery if you want*/
...
}
if (var == 2)
{
...
/*do what you want knowing that the second form was clicked,
submit form with jquery if you want*/
...
}
}
I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });