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)
Related
I'm using jquery autocomplete on an input form 'city' but i would like the query in my 'autocity.php' file to only suggest cities in the pre selected country i.e. WHERE City LIKE '%$term%'" AND CountryID = '%$country%'. The form action submit uses a separate PHP file (create-business.php) for inserting the form data to the database so the usual $_POST['Countries_CountryId'] wouldn't work in the autocity.php. that's why i'm now using AJAX to post 'country' to autocity.php. Also it would be great to have a way to echo/alert/print_r from the the autocity.php file so i can confirm that the $_POST['$country'] from the ajax post reaches the autocity.php file.
I have two input boxes in the form
<pre>`
<form id="input" action="php/create-business.php" method="post">
<select name="Countries_CountryId" id="country">
<input type="text" id="city" name="City">`
</pre>
Here is the script from the form
<script>
$(function () {
var country = $("#country").val();
$.ajax({
type:"POST", url:"autocomplete/autocity.php", data:"country",
beforeSend:function () {
// alert(country);
}, complete:function () { // is there any need for this?
}, success:function (html) { // is there any need for this too?
}
});
$("#city").autocomplete(
{
source:'autocomplete/autocity.php'
})
});
</script>
And here is autocity.php
`
//database connection works fine and autocomplete
//suggestion works without the AND CountryID = '%$country%' part.
$country = "";
if (isset($_POST['country'])) {
$country = trim($_POST['country']);}
echo "window.alert($country);"; //This did nothing no alert
$term = $_REQUEST['term'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>`
So the question is basically:
1 - how can i use a text input from a form using AJAX in a .php file that queries a MySQL db that is not the submit form action .php file
2 - how can i alert the post variable from the PHP file when ajax is used to show that the php file recieves my ajax post. In my brief experience echo and print_r only work on form submit when the web page changes showing the result of my form submit ont the form action.
3- how is my syntax?
Thank you very much in advance for helping this novice out :D
Ok here is my update on things i've tried. I think i'm close. i'm using Jquery UI -
//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js
here is the script method 1:
$(document).ready(function () {
var country = $('#country').value();
alert(country + " complete");
$("#city").autocomplete(
{
source:'autocomplete/autocity.php?country='+country,
minLength:1
});
});
here is the script method 2:
$(document).ready(function () {
$('#city').autocomplete({
// source: function() { return "GetState.php?country=" + $('#Country').val();},
source:function (request, response) {
$.ajax({
url:"autocomplete/autocity.php",
//dataType:"json",
data:{
term:request.term,
country:$('#country').val()
},
success:function (data) {
response(data);
}
});
},
minLength:2
});
});
I like method 2 more since it will allow me to add more than one parameter.
Finally here is my latest autocity.php code
<?php
$term = $_REQUEST['term'];
$country = $_REQUEST['country'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%' ";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>
I'm still totally stuck though. can anybody see the problem with the code? Ive looked everywhere online for the right syntax. Thanks again
For the first problem, your approach is essentially correct. You can bind to the blur event for a particular field and use your function to get that field's value and submit to the php script much in the manner that you are doing so. $.blur() is what you're looking for.
For the second problem the error_log function will write stuff to php's error log. IF you use print_r to dump variables to this log, make sure to set print_r's second argument to true to output the result as the return value.
I am trying to iterate through a number of selects in a cell of a table (they are not in a form). I have a submit button when pressed is supposed to retrieve the values and id of each select list which I will pass to the server via AJAX and PHP. My table is a table of students of a course. The table contains the students name and their attendance for a lesson in the course.
This is my table on Pastebin and jsFiddle. http://pastebin.com/NvRAbC7m and http://jsfiddle.net/4UheA/
Please note that this table is entirely dynamic. The no. of rows and the info in them is dynamically driven.
This is what I'm trying to do right now with jQuery. Please excuse the logic or the complete nonsense that is my JavaScript skills. I don't actually know what I'm doing. I'm just doing trial and error.
$('#saveAttendances').live('click', function()
{
var attendSelect = $('.attendSelect');
var students = new Array();
//get select list values and id.
for(var i in attendSelect)
{
students['student_id'] += attendSelect[i].id;
students['student_id']['attedance'] += attendSelect[i].value;
console.log(students['student_id']);
}
//after retrieving values, post them through ajax
// and update the attendances of students in PHP
$.post("",{ data: array }, function(msg)
{
alert(msg);
});
});
How do I get the values and id's of each select list and pass it to AJAX?
Edit
If you insist on going against jQuery's grain and using invalid HTML, here's a suitable solution for you:
$(function() {
$('button').click(function(){
var data = $(".attendSelect").wrap('<form/>').serialize();
$.post('process.php', data, function(response){ ... });
return false;
});
});
Worth mentioning, this example does not rely on fanciful .on() or .live() calls. However, this requires you to have the proper name attribute set on your <select> elements as described below. This also resolves your invalid numeric id attributes issue.
See it working here on jsFiddle
Original Answer
First off, some minor changes to your HTML. You need to wrap your <select> elements in a <form> tag. Using the form tag will give you access to jQuery's .serialize() method which is the exact functionality you're looking for. Personally, I'd recommend doing things the jQuery Way™ instead of implementing your own form a serialization. Why reinvent the wheel?
Next, your td have non-unique IDs. Let's update those to use a class attribute instead of an id. E.g.,
<td class="studentName">Aaron Colman</td>
Secondly, your <select> elements could benefit from a name attribute to make form processing way easier.
<select class="attendSelect" name="students[241]">
...
<select class="attendSelect" name="students[270]">
...
<select class="attendSelect" name="students[317]">
...
Lastly, jQuery's .serialize() is going to be your winning ticket.
$(function() {
$('form').submit(function(){
$.post('process.php', $(this).serialize(), function(response){ ... });
return false;
});
});
Upon submit, the serialized string will look something like
students[241]=Late&students[270]=Absent&students[317]=default
See it working here on jsFiddle
live() is deprecated as of jQuery 1.7, use on() instead
http://api.jquery.com/on/
students is an array, so I don't think you can do students['student_id'], if you would like to push an array of student, you can:
$('#saveAttendances').on('click', function() {
var students = [];
// iterate through <select>'s and grab key => values
$('.attendSelect').function() {
students.push({'id':$(this).attr('id'), 'val':$(this).val()});
});
$.post('/url.php', {data: students}, function() { // do stuff });
});
in your php:
var_dump($_POST); // see what's inside :)
As #nathan mentioned in comment, avoid using number as the first character of an ID, you can use 'student_<?php echo $id ?>' instead and in your .each() loop:
students.push({'id':$(this).attr('id').replace('student_', ''), 'val':$(this).val()});
Here's jQuery that will build an object you can pass to your script:
$('button').click(function() {
var attendance = new Object;
$('select').each(function() {
attendance[$(this).attr('id')] = $(':selected', this).text();
})
});
jsFiddle example.
This results in: {241:"Late",270:"Absent",317:"Late"}
Edit: Updated to iterate over select instead of tr.
Perhaps you want something like below,
DEMO
var $attendSelect = $('#tutorTable tbody tr select');
var students = {};
$attendSelect.each (function () { //each row corresponds to a student
students[$(this).attr('id')] = $(this).val();
});
This would give you an object like below,
students = { '241': 'Late', '270': 'Absent', '317': 'default' };
If the above is not the desired structure then modify the .each function in the code.
For ex: For a structure like below,
students = [{ '241': 'Late'}, {'270': 'Absent'}, {'317': 'default'}];
You need to change the code a little,
var students = [];
...
...
students.push({$dd.attr('id'): $dd.val()});
var $select = $('.attendSelect'),
students = [];
$('body').on('click', '#saveAttendances', function() {
$select.each(function(k, v) {
students[k] = {
student_id : $(this).attr('id'),
attedance : $(this).val()
};
});
console.log(students);
});
I'm trying to sort images using: http://jqueryui.com/demos/sortable/display-grid.html
And then somehow submit the newly sorted array/results into a MySQL Database using PHP?
I'm having difficulty figuring this out (newby alert), so if anyone can shed some light on this, I'll be dishing out hi-5s like there's no tomorrow.
Cheers
In particular you need to look at attaching an event to the sortable
http://jqueryui.com/demos/sortable/#event-update
and serialize for getting the relevant content http://jqueryui.com/demos/sortable/#method-serialize
EDIT
This is a primitive version of what you need to do.
<script>
$(function() {
var arrayOfIds = [];
$( "#sortable" ).sortable({
update: function(event, ui) {
$.each($(this).sortable('toArray'), function(key, value) {
arrayOfIds.push(value.replace('el-',''))
});
var jqxhr = $.ajax({
url: "order.php?order="+encodeURIComponent(arrayOfIds),
})
.success(function(response) { console.log("success" + response ); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete "); });
}
});
$( "#sortable" ).disableSelection();
});
</script>
Each li element than needs an id that your DB can understand
<li class="ui-state-default" id="el-1">1</li>
the "1" in id="el-1" should relate to an id in your DB table. When you reorder, the update event fires, goes through the new order, grabs all the ids and passes that to an ajax request which a php file then can pick up. the order.php script then go split the numbers by the "," and update your table one by one.
e.g.
$itemOrders = explode(',',$_POST['order']);
$sizeOfList = sizeof($itemOrders);for($i=0; $i<$sizeOfList; $i++)
{
$itemId = intval($itemOrders[$i]);
$query = "UPDATE your_table_name SET order_no = '".$i."' WHERE id = '".$itemId."' ";
if ($result = $msHandle->query($query))
{
$message = 'success';
}
else
{
$message = 'fail ';
}
}
There will be a callback function on the sorting event which you can use to send an AJAX request to a PHP script which updates a database. Think of it as after you've made a sorting action (i.e. moving one item around), you send the values (i.e. the ordered list) to a PHP script that takes those values and updates the database. I'll assume you have experience in MySQL as you seem to know the fundamentals of the problem.
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);
});
});
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.