Jquery, add value to array in each loop - php

I have a jQuery app where the user can add items to a list from an input field.
I want to put all items in an array when you submit the form so I can manipulate them with php later. Is this the right way to do it?
jQuery:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});
PHP:
$items = $_POST["items"];
foreach($items as $item){
//Something here
}

The idea is sound. What it not very clear is that your example populates items now, but the submit handler will of course be called at some point in the future. Is it possible that the list items may have changed by that time?
If so, you need to move the "pack the items" code inside the submit handler, e.g.:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});

Related

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

Store li order in Mysql DB with Jquery sortable

I have a sortable list in my site which saves the order of the list items with an ajax request to a php page.
The problem is when the id of the LI (which is generated by the database) gets above 999 or so it begins to error as the array I'm sending to the PHP page becomes too long.
Is there a better way of doing this?
Currently my Jquery/ ajax is:
$(function() {
$('#sortable').sortable({
update: function(event, ui) {
var order = [];
$('#sortable li').each( function(e) {
order[ $(this).attr('id') ] = $(this).index() + 1;
});
var request = $.ajax({
url: "ajax/save_order.php",
type: "POST",
data: {positions : order},
dataType: "json"
});
}
});
});
My PHP page is:
$positions = $_POST['positions'];
foreach ($positions as $id_section => $order)
{
$sql = sprintf("
UPDATE section_order
SET id_order = %d
WHERE id_section = %d
",
$order,
$id_section
);
$result = mysql_query($sql);
}
I've been trying to work out how to get the data from the sortable into a multidimensional array in jquery, but currently am drawing a blank.
OK I see. Seems a bit unwieldy for a user to manually drag and drop items in a list of over 1000 items. But I don't know how/why you are doing this so will assume it works for your application.
The below solution is actually from this SO question jQuery UI Sortable, then write order into a database
jQuery Sortable has a serialize function that takes care getting the order for you. Use it like below:
$('#sortable').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'save_order.php'
});
}
});
And in the save_order.php file, just check what the posted data looks like and loop though it, should be able to do something like:
<?php
foreach ($_POST['each_item_whatever...'] as $value) {
// Database stuff
}
?>

How to get the textarea ID using jQuery

Ive got textarea area on each table row with unique ID .
How to retrieve that unique id with javascript?
PHP:
$query = $db->query("SELECT * FROM bs_events WHERE eventDate = '".$date."'");
while($row = $query->fetch_array(MYSQLI_ASSOC)){
echo '<textarea id=\"att_name_" . $row['id'] . "\" style=\"width:300px\"></textarea>";'
}
PHP OUTPUT:
<textarea id="att_name_1" style="width:300px">
<textarea id="att_name_2" style="width:300px">
<textarea id="att_name_3" style="width:300px">
jQuery:
$(document).ready(function(){
$("#book_event").submit(function(){
id = event.target.id.replace('att_name_','');
$.post("Scripts/book_event.php", {
att_name: $("att_name_"+id).val(),
}, function(data){
if(data.success) {
$("#err").text(data.message).fadeIn("slow");
}
}, "json");
});
});
It looks to me like you're naming your textareas to correlate to the database entries, then trying to make updates and pass those values back. Assuming the textareas are in the form you're submitting, you can use:
$('#myform').submit(function(e){
// find each of those text areas
$(this).find('textarea[id^=att_name]').each(function(i,e){
//
// from here-in, e now represents one of those textareas
//
// now submit the update
$.post('Scripts/book_event.php',{
att_name: $(e).val()
},function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
},'json');
});
e.preventDefault();
});
Ideally though, if you're looking to use AJAX to push updates/changes back to the server, you may look in to .serialize() and push all forms back. Then, on the server-side you'll get the standard $_POST['att_name_1'] values that you can use for your actual updating. e.g.
// .serialize() example
$('#myform').submit(function(e){
$.post('Scripts/book_event.php',$(this).serialize(),function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
});
e.preventDefault();
});
To solve your problem, you can use each()
$(function()
{
$("textarea").each(function()
{
var textarea_id = $(this).attr('id');
});
});
I don't fully understand the question.
If you want a list of the ids, how about something like:
$(document).ready( function ( ) {
var textareas = new Array();
// Run through each textbox and add the id to an array
$("textarea").each( function( ) {
textareas.push( $(this).attr("id") );
});
// Print out each id in the array
textareas.forEach( function(i) { alert(i); });
});
(that's untested and probably not the quickest way - I'm a bit out of practice)

Print the value in loop in Jquery ready function

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all
I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});
You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.
Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.
What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

How to preload a div combobox in jquery

I have code as follows:
$("#item_select").change(function()
{
var params = $("#item_select option:selected").val();
$.post('/account/ar_form.php', {idata: params}, function(data){
$("#message_display" ).html(data);
});
});
This is a dropdown that uses /account/ar_form.php to display html in the div correctly.
But it only displays on the change event. I'd like it to preload the data. When I use a load event, it will display the html, but on change, it displays it twice.
$("#item_select").change(function(){
var params = $("#item_select option:selected").val();
$.post('/account/ar_form.php', {idata: params}, function(data){
$("#message_display" ).html(data);
});
}).triggerHandler("change");
It depends a bit... what does your ar_form.php return with blank params?
You could do a hackish way (at fear of being downvoted) by calling
$("#item_select").change();

Categories