I have a main-page.php with a simple form (id=search) that performs a live search in a MySQL database and returns results in a list like this:
echo "<ul style=\"list-style-type: none;\">";
while($row = mysql_fetch_assoc($sql)) {
echo "<li>".$row['Long_Desc']."";
}
echo "</ul>";
What I need is a JQuery function to allow me to click on any of the returned list items from the above list, but instead of being directed to next-step.php, I would like to stay on main-page.php, and have the div "results" on this page updated with the contents of the next-step.php script.
Of note, next-step.php performs another SQL search and returns results as a form element with radio buttons that are built with an echo command - something like this:
echo "<form id=choices>"
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<input type=RADIO name=\"food_quantity\" value=\"$line[Gm_Wgt]\">";
echo "<b>$line[Amount] $line[Msre_Desc]</b> ($line[Gm_Wgt] grams)";
}
echo "<INPUT type=RADIO name=quantity>";
echo "<INPUT type=text NAME=my_quantity SIZE=4 value=\"\"> <b>grams</b>";
echo "<input type=submit name=Submit value=\"Submit\">";
echo "</form>";
Finally, what I'd like to be able to do with the form "choices" is to check a radio button option, send the selection to an external php page (let's call it last.php), where yet another SQL search is performed, the results of which should then be returned as a blcok of formatted HTML into the original "results" div of main-page.php.
Thank you for your help!
Here are the simple and easy 4 steps that i would recommend you and you shall customize it to your need
Step 1 : Write a Jquery function onclick()
<script>
$( "#yourID" ).click(function() {
$( this ).slideUp();
});
</script>
Step 2 : Do an ajax call and send value to the Server
$.post( "yourServer.php", { data: "yourData" })
.done(function( data ) {
});
Step 3 : Get the value in server side
$data = $_POST['data'];
#Do some process and get the result
Step 3 : Send the Results
echo json_encode($yourData)
Step 4 : Get the results in JQuery success event & Show in the div that you need to update
if(success.data==1)
{
$('#yourResult').html(data.name);
}
else
{
$('#yourResult').html(data.error);
}
Hope this helps you !
Related
I already have implemented an ajax that send a tr and td to a html table every time that a element from the table of the DB is updated, i'll like to send the ajax html data to a append and send it from there to the body and not directly from ajax to the body, any one knows hoy?
this is my php:
<?php if($total>0 && $search!='')
{
do {
echo "<tr><form method='post' action='modifystatusdown.php'>
<td style='width:20%; '><input type='text'><input type='hidden'>";
echo $fila['nombre'];
echo "</td><td style='width:20%;'>";
echo $fila['telefono'];
echo "</td><td style='width:20%;'>";
echo "<input type='Submit' name='delete' value='Atendido'></td></form></tr>";
}
while ($fila=mysqli_fetch_assoc($resultado));
} ?>
this is send it to this ajax:
$(document).ready(function()
{
function actualizar()
{
value = $('#value').html();
$.ajax(
{
type: "POST",
url: "../solicitudes/buscador.php",
success: function(data)
{
$('#value').html(data);
}
})
}
setInterval(actualizar, 3000);
})
finaly from ajax its send it to a table inside a div:
<div class="container">
<table id="value">
</table>
</div>
how could i send it to the append and then to the table? instead directly from ajax?
the idea is something like this, in a table of the database I have a status column which is initialized to 0 and every time someone requests a service from an application android status is changed to 1, that I mentioned above is working, I want to achieve is that every time status is equal to 1, then appears in a html page , just as already appears in the html page, the problem is that assigned an input field where you can type in the text field the service to be assigned to the user requesting and as the table where they are inserted into the html refreshes every 5 seconds and you can not write in the text because it cleared everytime refreshes the table automatically ,
You can combine both $.post and $.get
ie $.post('url', {datatoappend: 'append'}, function(data){
$.get('urlwithsentdata', function(data){
});
});
this works nicely
I have a PHP script that calls the Twitter 1.1 API, and returns 50 ID numbers. Then I am using a Foreach argument to print the results individualy on to the page. I want to store each different ID number inside a button as a hidden value, and then use JQuery Ajax to post that value to a different PHP page for further processing without leaving or refreshing the page of 50 ID numbers.
If I use this Foreach argument, the 50 ID numbers are ALL the first result in the array, rather than being 50 individual ID numbers which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='RT' onsubmit='return submitForm();'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>
");
}
But, If I remove this section from the Foreach argument, 50 individual ID numbers are printed into into hidden values of the forms:
onsubmit='return submitForm();'
The problem is my JQuery script is listening for submitForm and without that line above the JQuery will not run. Here is my JQuery script:
<script>
function submitForm() {
$.ajax({type: 'POST', url: 'results.php', data: $('#RT').serialize()});
return false;
}
</script>
I know that removing onsubmit='return submitForm();' gives me 50 unique ID numbers from the Foreach, because this code will print 50 buttons which will each contain individual values. But because there is no JQuery script listening for submitForm I have to add method='post' action='results.php in order to POST the value of the button but this means the page results.php loads which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='form' method='post' action='results.php'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>");
}
So, I want the foreach to print 50 unique ID numbers, while also letting me use the JQuery Ajax script. I hope this is clear, I don't know how else to describe what I want to do :D
Okay, now I understand what you're trying to do. I would do it like this.
PHP:
<?php
foreach ($results as $arrResult) {
$tweetId = $arrResult['id_str'];
print('<button type="button" class="mark-tweet" data-tweet-id="' . $tweetId . '"><br/><br/>');
}
JavaScript:
$(function() {
$('.mark-tweet').click(function() {
var id = $(this).attr('data-tweet-id');
$.ajax({
type: 'POST',
url: 'results.php',
data: {tweetId : id}
});
})
.done(function() {
alert('The tweet has been deleted');
})
.fail(function() {
alert('Oops, something went wrong! Please try again.');
});
});
NOTE: I am not capitalizing the 'r' in $Results as you did. Only class names should start in capital letters (class as in OOP, not CSS)
OK, we've got you now. You're on the right track to use an ID, and this is straight-forward.
What you need to render are 50 buttons with onclick that will call your markTweet() JS function & pass it the ID -- and that can do the AJAX post. No form required.
Alternatively, you can render 50 forms with separate IDs ('form'.$tweetId), each with a hidden input & submit button (or just a <button>, since the BUTTON element can have a name & value distinct from its content), and an onclick that calls `postTweetForm('form${tweetId})' -- thus passing the ID of the selected form to your JS function.
Really, since you're doing it in JS, keeping the UI simple & letting JS do the work is easiest. Here's an example to get started. PHP:
foreach ($Results as $arrResult) {
$tweetId = $arrResult['id_str'];
print("<button type='button' onclick='markTweet('".$tweetId."');'><br>\n");
}
Javascript:
function markTweet (tweetId) {
$.post({
url: 'results.php',
data: {'tweetId': tweetId}
);
}
You should also put in a success handler into your AJAX post.. fade in a little green tick or something so the user knows it's worked, because it doesn't always. (I'll let you play with that.)
Try that.. and keep the question up. It's much improved now & may be able to help someone else.
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 am having trouble trying to get a value from a drop-down list and multiplying the value by a number in the 'ticket' table. I've been trying to implement this calculation in both PHP and javascript but having no luck :(
Here is the form (which is returned to the homepage by AJAX):
$pcSearch = $_POST['postcodeSearch'];
$postCodeSQL = "SELECT * FROM ticket WHERE locationID IN (SELECT locationID FROM location WHERE postCode LIKE '$pcSearch') ";
$postCoderesult = mysql_query($postCodeSQL) or die(mysql_error());
while ($pcRow = mysql_fetch_assoc($postCoderesult)) {
$venue = $pcRow['venue'];
$ticketPrice = $pcRow['tPrice'];
$date = $pcRow['date'];
$time= $pcRow['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>£$ticketPrice</td>\n";
echo "<td><form id=\"quantity\" method=\"post\" name=\"ticketQuantity\">
<select name =\"showQuantity\" id=\"showQuantity\" class =\"showQuantity\" >
<option value=\"1\">1</option>
<option value=\"2\">2</option>
<option value=\"3\">3</option>
<option value=\"4\">4</option>
<option value=\"5\">5</option>
</select>
</form>
</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td><form name=\"buyTicket\" class=\"buyTicket\" id=\"buyTicket\" >
<input type= \"button\" id= \"buyMe\" class= \"buyMe\" value= \"Buy\" name=\"buyMe\">
</form>
</td>\n";
echo "</tr>\n";
}
Basically, what I wanting to do is when a user clicks and choose the quantity of tickets they want i.e. 3, this number will be multiplied by the price of the ticket ('tPrice'). Is there a way of getting both these values and multiplying them together in PHP?
I've tried adding jQuery to listen for the button click function but to no avail...I even tried debugging it but for some strange reason it won't output the alert:
$(document).ready(function() {
$(".buyMe").click(function() {
alert('click');
});
});
However if I were to use jQuery, how would I even get the value of 'tPrice' from the form?
Thanks very much for any help :)
The first thing i would do is add a class to the ticket price td :
echo "<td class=\"ticketPrice\">£$ticketPrice</td>\n";
What that does it make it a lot easier to get the price using jQuery.
So now .. you can do this :
$(".buyMe").click(function() {
var priceForOne = $(this).siblings('.ticketPrice').text().substr(1);
});
Infact as you have access to the source of the HTML a better way would probably using data() :
echo '<input type="button" class="buyMe" value="Buy" data-ticket-price="'.$ticketPrice.'"/>';
then you can change your click to be :
$(".buyMe").click(function() {
var priceForOne = $(this).data('ticketPrice');
});
A couple of other points ..
remove the id attribute from here :
<input type= \"button\" id= \"buyMe\" class= \"buyMe\" value= \"Buy\" name=\"buyMe\">
there is no need for a form around the select list as its doing nothing ... similarly the form around the button is doing nothing either !
Updated
The click method won't work for DOM elements added after the document has been loaded (ie via AJAX) ... you need to use the on() method :
$(document).on('click','.buyMe',function() {
// handle the click here
});
the $(document) above needs to be a parent element of the buyMe element and present on the DOM at load, in your case you could replace $(document) with $('#idOfYourTable')
Docs for data() and Docs for on()
You're referencing a non-existent class name instead of the id. Change .buyme to #buyme
$(document).ready(function() {
$("#buyMe").click(function() {
alert('click');
});
});
Edit missed that the class is on there too. However since you're just referencing a single element you should use the ID anyway.
Hi again :)
I'm using jQuery script to show/hide some content:
<script type="text/javascript">
$('.toggleButton').click(function() {
var id = this.id.replace('toggleButton', '');
$('#content' + id).toggle();
});
</script>
Since I'm using PHP, I am iterating through few items and each of them has a button to show/hide its content. My content is actually a form with few input fields. In each item, first field of my form has a same name (let's say 'line1').
What I would like to do is when I click on an item and open its content, to take a focus on input field 'line1'. When I click on other item to take a focus on its 'line1' field, and so on...
Preferably with jQuery because I suppose it would be simpler, but javascript solution would be also great :)
Thanks for any help!
EDIT: I will attach a part of code which is that I need to show and hide... Maybe it will be of some help... I am using codeigniter, so not to be confused by some functions :)
echo "<div class=\"toggleButton\" id=\"toggleButton".$item['id']."\">CLICK TO OPEN</div>";
echo "<div class=\"content\" id=\"content".$item['id']."\" style=\"display:none;\">";
echo form_open('title/add'); // codeigniter's open form
for ($i = 1; $i <= $item['rows']; $i++) {
echo "<input type=\"text\" class=\"line\" id=\"line".($i)."\">".br();
}
echo form_submit('submit', 'submit'); // codeigniter's submit for button
echo "</form>";
echo "</div>";
Change your last line to:
$('#content' + id).toggle().find('input').first().focus()
did you try giving common class name and call function based on class name