I am creating a popup dialog box where I need to put a set of values in hidden format, but when I am getting the value in AJAX post, I am getting only last value.
this is the PHP part:
$plan_ids=array();
foreach($test_plan as $plan)
{
$plan_ids[]=$plan['plan_id'];
}
?>
<?php
foreach($plan_ids as $id)
{
echo "<input type='hidden' id='plan_id' value='$id'>";
}
//var_dump($plan_ids);
// echo $plan['plan_id'];
?>
In the AJAX part I am doing:
$("#save").click(function () {
var name = $('#name').val();
var id = $('#release_id').val();
var plan_id = $('#plan_id').val();
//alert('hello');
$.ajax({
type: 'POST',
url: '/api/api.php?action=put_iteration&name=' + name + '&id=' + id + '&plan_id=' + plan_id,
data: "name=" + name + "&id=" + id + "&plan_id=" + plan_id,
success: function () {
$('#save').hide(function () {
$('div.success').fadeIn();
});
}
});
});
I'm clueless about HTML hidden fields.
Not a PHP guy, But some thoughts . Forgive me for syntax errors.
In the loop You are creating hidden element with the same ID. That is not good. Change the code sot hat the Id's will be ( SHOULD BE ALWAYS ) Unique.
<div>
foreach($plan_ids as $id)
{
echo "<input type='hidden' id='plan-$id' value='$id' class='myHidden'>";
}
Now in your script, use jQuery selectors based on the hidden item
var hiddenItems=$("input[type='hidden']");
may be now you can loop thru this
var items
$.each(hiddenItems,function(item,index){
items+= hiddenItems[index];
});
Or you can map function like this so that it will give a list of values of hidden fields comma seperated.
var itemsJoined=$("input[type='hidden']").map(function () {
return this.value;
}).get().join(',');
you can name all your hidden fields like an array name="plan_id[]"
And instead of passing it as a string you can have a wrapping FORM around hidden fields and then use jquery serialize function to POST it
Now you will get all the plan_id in the form of an array in the POST variable
Adding an example
<?php
echo '<form name="planidform" id="planidform">';
foreach($plan_ids as $id)
{
echo "<input type='hidden' name="plan_id[]" value='$id'>";
}
echo '</form>';
?>
After than in jQuery do it in following manner:
data: "name=" + name + "&id=" + id + "&"+$("#planidform").serialize(),
I think you want to change id='plan_id' to name='plan_id[]' for a start.... you are only allowed to have one element with a given id (i.e. id is required to be unique across elements in a given page).
you should put diffrent names / ids to the hidden fields.
if u want to submit them all at once u can store them in an array.
for example:
$i=0;
foreach($plan_ids as $id){
$i++;
echo "<input type='hidden' id='plan_id_$i' value='$id'>";}
then u can address or group them in JS.
Related
I entered checkbox values into the database using the code below. When a user wants to view the checked boxes at a later time, how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?
From the code below the data gets entered like this: DATA1|DATA2|DATA3|
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
checkbox_value += $(this).val() + "|";
}
});
Now how to I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
Here is how I'm getting other data and re-displaying it from normal input text boxes:
$.ajax({
url: 'ajax/example/example.php',
data: "findval="+carrier+"&column="+column,
dataType: 'json',
success: function(data)
{
var auto_id = data['id'];
var auto_name = data['name'];
var auto_address = data['address'];
var auto_trailer_types = data['trailer_types'];
$('#output_autocomplete_forms').html("<form id='example' class='form-horizontal'><input type='hidden' name='auto_id' id='auto_id' class='form-control' value="+auto_id+">......<div class='form-group'>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA1'>DATA1</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA2'>DATA2</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA3'>DATA3</label></div>
var auto_trailer_types = data['trailer_types'];
Now how do I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
So, I am guessing that the string stored in the database is something like 0|0|1|0, and you need to restore the checkboxes to that state.
As has been said, you can use AJAX for that. First, you need a trigger to launch the AJAX routine -- a button click, usually:
<button id="mybutt">Update Checkboxes</button>
Your AJAX routine will look something like this:
var rowID = $(this).closest('tr').attr('id');
alert(rowID); //this datum must allow you to identify the row in the database
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'id=' +rowID,
success: function(recd){
var arrCB = recd.split('|');
for (var n=0; n<arrCB.length; n++){
var z = n+1;
$('#cb'+ z).val( arrCB[n] );
}
}
});
another_php_file.php:
<?php
$id = $_POST['id'];
$pseudo_query = "SELECT `field_name` FROM `table_name` WHERE `id` = '$id' ";
echo $pseudo_query_result;
The pseudo_query_result that you echo should be your original 0|0|1|0. The PHP echo sends that datum back to the jQuery AJAX routine's success function. Important: the received data is not available outside that success function. You must do what you want with that data inside the success function, as shown in above example.
In above code, .split() was used to turn the 0|0|1|0 string into an array, and then we use a for loop (or even just manually code each checkbox update individually).
Use ajax to resolve this issue. But before try to encode your php query response in JSON
$.ajax({
url: "test.php" //Your request URI
}).done(function(data) {
//data (you can name it whatever you want) is the data that you get from your request.
//eg. if(data.checkbock){ //do something }
});
More informations here
I have a table that creates rows when you press the Add Order Item It runs a function that appends this:
function Add() {
$('#table-order').append(
"<tr>" +
"<td><input type='text' class='order-qty'/></td>" +
"<td><input type='text' class='order-desc'/></td>" +
"<td><input type='text' class='order-options'/></td>" +
"<td><input type='text' class='order-price'/></td>" +
"<td><span class='btn-save'>Save</span>|<span class='btn-delete'>Delete</span></td>" +
"</tr>"
);
$(".btn-save").bind("click", Save);
$(".btn-delete").bind("click", Delete);
}
I am looking at some way to get all the input values (excluding the last TD cell).
The idea is: get all the values in an object or an array, split each line as the order willl have multiple rows.
Pass the object as a $_POST to php to then send to mongoDB
You can iterate through inputs and post collected values when click save button like;
var params = [];
$("input").each(function() {
params.push($(this).attr("class") + "=" + $(this).val())
});
$.ajax({
url:"your url",
method: "POST",
data: params.join("&"),
success: function(response) {
//handle response
}
});
You can see sample demo here: http://jsfiddle.net/9pFq4/
I have the following script :
<script type="text/javascript" >
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val();
var first_lastname = $(".first_lastname", this).val();
var second_firstname = $(".second_firstname", this).val();
var second_lastname = $(".second_lastname", this).val();
var TeamName = $(".TeamName", this).val();
var dataString = 'first_firstname='+ first_firstname + '&first_lastname=' + first_lastname +
'&second_firstname=' + second_firstname + '&second_lastname=' + second_lastname + '&TeamName=' + TeamName;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
success: function(){
window.setTimeout(function(data)
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
});
</script>
And the following php that generates a number of forms on a page using mysql database
<?php
echo '<table class="greensmalltbl" cellspacing="10px" cellpadding="5px"><div id="propspectDiv"></div>';
for ($i=1, $o=$totalEntrants; $i<=$half; $i++, $o=$o-1) {
$formid = $i;
echo "<div style='border:3px;'><form action='' method='post'>
<tr><td><input type='text' name='first_firstname' id='first_firstname' value='$firstName[$i]' />
<input type='text' name='first_lastname' id='first_lastname' value='$lastName[$i]' />
Skill Level : ".$skill[$i]."</td></tr>";
echo "<tr><td>WITH</td></tr>";
echo "<tr><td><input type='text' name='second_firstname' id='second_firstname' value='$firstName[$o]' />
<input type='text' name='second_lastname' id='second_lastname' value='$lastName[$o]' /> Skill Level ".$skill[$o]."</td></tr>";
echo "<tr><td>Enter Team Name : <input type='text' name='TeamName' id='TeamName' value='' />
<input type='submit' name='submit' value='Submit'></form></td></tr>";
}
echo '</table>';
?>
I want to update the db table with the TEAM NAME in each form
The problem is only the first forms input is passed all other forms do nothing
I have tried a number of variations to the ajax code but none have worked.
Can anyone find the problem here
This line will not return the form.
var parent = $(this).parent('form');
because your submit button is wrapped inside tr and td tags. Either get rid of those tags (they are invallid anyway, because your are not using them in a table), or update your code to:
var parent = $(this).closest('form');
closest() searches its way up to all the ancestors of an element, and will return the first match of the selector.
Check out the documentation here: http://api.jquery.com/closest/
Or, if you only have a single form in your page, you could just go:
var parent = $('form');
:: EDIT ::
OK. Forget all of the above. Seems like you are not even using the parent variable later in the code.
A more important problem is that even though you are catching the Click event on the form submit button, what you probably really want to do is catch the submit-event of the form.
So change your first line of code to this:
$('form').on('submit', function() {
Also, in your HTML, your code is invalid.
<form action'' method='post' id='$formid'>
action'' should be action = ''
Chances are this doesn't really fix your problem, because there might be more errors. Next time, try to validate your code before posting a question.
:: EDIT ::
Last edit, I promise. I quickly went trough your code again, and it seems you will have multiple forms. this means, that you will get elements in different forms with the same id's. An id should be unique for troughout the page. So when you try to get a value like this $("#second_firstname").val(); that won't work. because jQuery doesn't know what element you mean, so all elements that can appear multiple times in a page need to have a class and CAN NOT have an id.
You could then loop trough your forms by changing things to:
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val(); // . instead of # and use 'this' as context
// and so on..
// the rest of your code here.
}
});
table with forms can be seen here
I´m trying to build a shopping cart in jQuery and PHP but cannot read values from form list.
When trying to get value from the form that is submitted i only get values from
the first form in the list view.
Please look at behaviour here:
http://www.adlertz.se/index.php?op=prodlist&katID=9&sidemenu=menushop
Click buy on ex. the middle, you get value from first.
Please help me with this, i have benn looking for solution for three days.
Probably a simple problem but i cant find the answer anywhere :| !!!.
Many thanks in advance!
function prodlist(){
$katID = $_GET['katID'];
$sql = mysql_query("SELECT * FROM shop_prod WHERE kategoriID=$katID");
while ($rad=mysql_fetch_array($sql)) {
echo "<div class=\"shop_prod_list\">";
echo "<div class=\"shop_prod_list_tmb\"><img src=\"shop/images/prod_images_tmb/".$rad['prodID'].".png\" alt=\"\"></div>";
echo "<form id=\"addcartform\" class=\"addcartform\" method=\"post\">";
echo "<input type=\"hidden\" name=\"prodID\" id=\"prodID\" value=\"".$rad['prodID']."\" />";
echo "<input type=\"submit\" class=\"shop_prod_list_kundvagn\" value=\"\" id=\"addcart\"/>";
echo "</form>";
echo "</div>";
}
echo "<div id=\"search_results\"></div>";
}
$(document).ready(function(){
$(".addcartform").click(function(e){
e.preventDefault();
addcart();
});
});
function addcart(){
var prodID=(this).document.getElementById('prodID').value; <-(Reads value but only the first)
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
}
<?php
include "db_config.php";
include "db_connect.php";
$prodID = strip_tags(substr($_POST['prodID'],0, 100));
$prodID = mysql_escape_string($prodID);
echo $prodID ." is added.";
?>
Use class instead of id
echo "<input type=\"hidden\" name=\"prodID\" class=\"prodID\" value=\"".$rad['prodID']."\" />";
Send the element which was clicked to your function
$(".addcartform").click(function(e){
e.preventDefault();
addcart(this); //this line
});
Then use that element to find the input with your class
function addcart(element){
var prodID = $(element).find('.prodID').val(); //Get val of clicked item
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
Although i would use only one button, without a form like this.
Php:
echo "<button name='prodID' class='shop_prod_list_kundvagn addcart' data-prodid='".$rad['prodID']."' value='Add' />";
Javascript:
$(".addcart").click(function(e){
e.preventDefault();
var prodID = $(this).data('prodid');
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
});
});
The code you use to pick out the value is not correct.
In theory you are supposed to have unique id's - so thats your first issue to resolve.
Secondly you need to find a better way to locate the value you are interested in.
My suggestion would be to add a button within each form and call it 'submit'.
On this button you add a data attribute that contains the product id.
With an onclick handler on this button you'll be able to get the data attribute directly.
Example which is not tested:
<button data-prodid="XYZ" onlcick="handleclick()">submit</button>
Javascript:
$(this).data('prodid')
Please note that you should not have duplicate IDs on the same page.
In this case, all three of your products have the id of "prodID". So in your JavaScript, when you getElementById, you will always get the first ID with that name.
There are many solutions for this. For example, you could add the product ID to the ID of the button, like 'id="addcart_' . $rad['prodID'] . '"'
You'd then parse that ID upon form submit to determine which product was selected.
I found another solution here: http://api.jquery.com/serialize/ - to pass hidden values.
But your solution is much simpler :)
I use jquery to post data to mysql.
**In settings.php i have this short JS code:**
$("form#submit").submit(function() {
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "settings.php",
data: "fname="+ fname +"& lname="+ lname,
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
return false;
});
**And this short php:**
if (isset($_POST['fname'])){
$fname = htmlspecialchars(trim($_POST['fname']));
DO SOMETHING....
}
This is the code where the FNAME comes from: (after hit ADD image-button then posted the fname value..)
echo "......
<form id='submit$i' method='post'><input type='hidden' name='fname' id='fname' class='text' value='$fm_linkaz'></div><input name='add'type='image' id='add' value='$fm_linkaz' src='s.png'/></form>..........";
This is work well. But i need a SELECT element, so i changed the code to:
......
echo "<select name=dropdown_list id='**ONAME**'><option value''>test</option>";
for($i=0; $i < count($myarray); $i++){
echo "<option value='$myarray[$i]'>$myarray[$i]</option>";}echo "</select>";
......</form>";
This is work well, but i dont know how can i modify the JS code, to post the selected value too.
Thank u for your help.
First of all the javascript code needs a few updates:
$('#fname').val() is better than $('#fname').attr('value') -- .val() will work on selects/checkboxes as well - where .attr('value') won't be reliable.
Second: the data parameter to your $.ajax() call can take a json object (which it will convert to the form string)
$.ajax({
type: "POST",
url: "settings.php",
data: {
'fname': $('#fname').val(),
'lname': $('#lname').val(),
'oname': $('#oname').val()
},
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
There is a plugin that makes this much easier:
$("form").ajaxForm({
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
UPDATED:
Also - the <select> element was named "dropdown_list" - perhaps you wanted it to be submitting data as "oname" instead. Form elements use the "name" property to submit, the id property only makes css/js selectors easier to code.
To get a selected value for use
jQuery('#**ONAME**').val();
Although I'm not sure if **ONAME** is valid ID, try removing the **
To get the value use the
$('select[name=dropdown_list]').val();
You could also use and ID, but I think you have some invalid chars in it and I doubt this will work:
$('select#**ONAME**').val();
Anyway .val() is what you are looking for. I also suggest using val() instead of attr('value').