jquery get element replaced by text - php

jQuery.ajaxSettings.traditional = true;
$(document).ready(function(){
$(".wijstoe").change(function(){
var id = $(this).children('#test').map(function() {
return $(this).text();
}).get();
var mw = $("option").val();
var opg = "Opgeslagen !";
$("#loading").css("display","block");
$.post("wijstoe.php",
{mw:mw, id:id},
function(data,status)
{
$("#loading").css("display","none");
$(this).children('#tester').html(opg);
});
});
});
HTML / PHP :
echo "<td>$row[2]</td>";
echo "<td id='test1'>";
echo "<div class='wijstoe'>";
echo "<div id='test' style='display:none;'>".$row[0]."</div>";
echo "<form><select>";
if($_SESSION['uname'] == 'admin') {
$querya="select uname from users";
$resulta = mysql_query($querya);
while ($rowa = mysql_fetch_row($resulta)) {
echo "<option>".$rowa[0]."</option>";
}
echo "</select></form>";
echo "<div id='tester'>DIDI</div>";
echo "</div>";
echo "</td>";
}
This does not get the text from id tester (DIDI) replaced by the text opgeslagen.
When I don't use $(this) it works but then it works for every div with id tester, i just want this specific div to have the text replaced.
So this works :
$(this).children('#tester').html(opg);
This does not work :
$('#tester').html(opg);

$.post("wijstoe.php",
{mw:mw, id:id},
function(data,status)
{
$("#loading").css("display","none");
$(this).children('#tester').html(opg);
});
The $(this) at the location listed will be the POST method.
Having multiple elements with the same ID is not a good practice. Change to a class when using on multiple elements.
var tester = $(this).find('.tester');
$.post("wijstoe.php",
{mw:mw, id:id},
function(data,status)
{
$("#loading").css("display","none");
$(tester).html(opg);
});

try
$(this).find('#tester').html(opg);

Related

Calling an Ajax function based on button class name click

I have created several image buttons in php. I have assigned a common class to all of them. When I call a jquery function based on button class name click. This works fine but when I try calling an ajax function it doesn't work. There is no error seen.
PHP to create a button
function printpic($name, $picpath, $category, $pic)
{
$style = " margin=0px; background-color=transparent; border=none;";
//$functionname= "selectedpic(this.id)";
$functionname= "myCall(this.id);";
$styleimage = "HEIGHT= 120 WIDTH= 120 BORDER=0";
$eventimage1= "zoomin(this)";
$eventimage2= "zoomout(this)";
$btnclass="btnclass";
$j=0;
$spa=0;
$i=0;
for($k=0; $k<4; $k++)
{
echo "<tr>";
for($j=0; $j<4; $j++)
{
echo"<td>";
$btn= "btn".$category[$i];
echo "<span id='" . $spa. "'>";
echo "<button name='" . $btn. "'
margin ='".$style."'
class='".$btnclass."'
onClick='".$functionname."'
>";
echo "<img src='". $picpath[$i]."/".$name[$i]."'
id ='".$pic[$i]."'
alt ='".$name[$i]."'
.$styleimage.
onMouseMove='".$eventimage1."'
onMouseOut='".$eventimage2."'
>";
echo "</button >";
$spa++;
echo"</span>";
echo"</td>";
$i++;
} // wfor
echo "</tr>";
}// for
} // end function
?>
Jquery + Ajax
$(document).ready(function(e) {
$('.btnclass').click(function() {
event = event || window.event;
var target = event.target || event.srcElement;
var id = target.id;
var but = document.getElementById(id).parentNode.name;
var datastring = '&id='+ id;
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
success: function(responseText) { // get the response
if(responseText == 1) { alert ("hi");}
else { alert (datastring); }
} // end success
}); // ajax end
});
});
indexverification.php
<?php
session_start();
$picno=$_SESSION['picno']; // picno from db
$answer=$_SESSION['answer']; // answer from db
$id=$_POST['id']; // id of picture clicked
$ans=$_SESSION['ans']; // answer type
if (($id==$picno) && ($answer==$ans))
{
echo '1';
}
else
{
echo '2';
}
?>
I think you use the wrong syntax. Try this:
//AJAX request
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
})
//Success action
.success(function( html ) {
if(responseText == 1) { alert ("hi");}
else { alert (datastring); };
})
//Error action
.fail(function() {
alert("Request failed.");
});

Javascript function response in Jquery not working

I have a form that using ajax to post the comment to video_comment.php then show up the comment live on video page.
This is my jquery code:
$("input[id*='post_video_playallcomment_']").livequery('click', function(event) {
event.preventDefault();
var video_msg = $("#post_message");
var input_id = $(this).attr('id');
var id_split = input_id.split('_');
var video_id = id_split[3];
var comment = $("textarea[id='video_comment']").val();
var response_messages = '#video_response';
if ( comment == '' ) {
video_msg.fadeIn();
return false;
}
video_msg.hide();
user_posting(response_messages, '<?php echo $lang['600']; ?>', 1);
reset_chars_counter();
$.post(base_url + '/video_comment.php', { video_id: video_id, comment: comment },
function(response) {
if ( response.msg != '' ) {
$(response_messages).hide();
user_posting(response_messages, response.msg);
$("textarea[id='video_comment']").val('');
} else {
$(response_messages).hide();
user_response(response_messages, '<?php echo $lang['587']; ?>');
$(".no_comments").hide();
$("textarea[id='video_comment']").val('');
var bDIV = $("#comments_delimiter");
var cDIV = document.createElement("div");
$(cDIV).html(response.code);
$(bDIV).after(cDIV);
}
}, "json");
});
On video_comment.php, this is the response.code to show up the comment live on video page.
echo 'text...
echo '<div id="commentplayer"></div>';
echo '<script type="text/javascript">';
echo 'jwplayer("commentplayer").setup({';
echo 'file: "...url",';
echo 'width: "300",';
echo 'height: "225",';
echo 'provider: "http",';
echo 'startparam: "start",';
echo 'wmode: "transparent",';
echo 'controls: "true",';
echo 'stretching: "uniform",';
echo 'primary: "flash",';
echo 'autostart: "false",';
echo 'ga: {}';
echo '});';
echo '</script>';
echo 'text...
I have no problem to get 'text...', but i can't get '<script type="text/javascript">function...</script>' to show up live on video page.
Help please...
instead of placing javascript code in the php return, why dont you place it in the .post response?
$("input[id*='post_video_comment']").click(function() {
$.post('video_comment.php', function(response) {
$('#comment').html(response.code);
//place javascript code here
}, "json");
});
or placing a onload before your js code
$str = '<div id="commentplayer"></div>
<script type="text/javascript">
window.onload=(function() {
jwplayer("commentplayer").setup({
file: "...url",
width: "300",
height: "225",
provider: "http",
startparam: "start",
wmode: "transparent",
controls: "true",
stretching: "uniform",
primary: "flash",
autostart: "false",
ga: {}
});
});
</script>';
echo $str;

send data on button click from javascript to database

So I have a php page that gets data from database and displays a table. Each td symbolises a seat in a movie theater. What i want to do is when a user clicks on one or more tds, and clicks send, the status column for each td in the database changes to 1 from 0(default). When the database is accessed next time, the td's with status=1 have a different color.
My code upto now is:
<div id="screen">SCREEN</div>
<div id="Seatings">
<?php echo "<table border='1'>
<tr>
<th>Seating</th>
</tr>";
$count=0;
echo "<tr>";
echo"<td id='Seat_rn'>A</td>";
while($row = mysql_fetch_array($sql))
{
if($count<10){
echo "<td id='Seat_A' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo "</tr>";
$sql=mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
echo "<tr>";
echo"<td id='Seat_rn'>B</td>";
while($row = mysql_fetch_array($sql))
{
if($count>=10){
echo "<td id='Seat_B' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo"</tr>";
echo "</table>";
?>
</div>
<input type="button" value="Done" name="done" onclick="window.close()">
My jquery code is:
$("td #Seat_A").click(function(){
$(this).css("background", "red");
});
$("td #Seat_B").click(function(){
$(this).css("background", "red");
});
$(document."done").click(function(){
alert(price:750 Baht);
})
I am nowhere near what i want and I'm sorry if any of my code is "amatuer-ish" but I am new to this and I have been trying very hard. Would appreciate any help that I can get.
First of all you have to add an ID to every TD on your table, i.e. Seat ID, For example:
echo "<td id='Seat_A' data-seat='". $row['id'] ."'class='count'>" . $row['Seat'] . "</td>";
Then send this ID to your PHP script with Ajax:
$("td #Seat_A").click(function(){
var seat_number = $(this).data("seat");
$.ajax({
type: 'POST',
url: "/take_a_seat.php",
data: 'seat_number='+seat_number,
success: function(data){
$(this).css("background", "red");
}
dataType: "json"
});
});
On the PHP script you have to do what you want to the seat with this ID and return true or false as a result. Let's suppose you have a field named reserved in your database table. You can get the unique ID and update that row to reserved = 1 for example.
Try this easy to use ajax script to accomplish your task
Features: you can show an gif img before send data to db in beforeSend section get response from php file in success section hide img after data inset in db in complete section and show successful or not success msg
var myVar = 'your desire data you want to send to db';
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"myVar="+myVar,
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
Javascript is client side. Your database is server side.. So you have to use php to change your database entries.
In short, if you want to execute PHP stuff without reloading page, than use AJAX. You can use it with your favorite JQuery.
This is an overview. For existing records you should some thing like this
<?php
$count=1;
$res = mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
while($row = mysql_fetch_array($sql)) {
if($row['status']==1) {
$tdcolor = 'red';
} else {
$tdcolor = 'blue';
}
?>
<td id="td-<?php echo $count;?>" sytle="background-color:<?php echo $tdcolor; ?>" onclick="reserveseat(<?php echo $count; ?>);" >
<?php
$count++;
}
?>
For changing after page load you will do ajax operation
<script type="text/javascript" language="javascript">
function reserveseat(count) {
$.ajax({
type: 'POST',
url: "bookseat.php",
data: '',
success: function(data){
$("#td-"+count).css("background-color", "red");
}
});
}
</script>
In bookseat.php you will change the status ... :-) Read about ajax from here . :-)

Make <tr> rows clickable and load result in div using jQuery

I have two questions:1. How can I make my table rows clickable and still load ajax content in the div ajaxContent? 2. How can I add a loading-animation in the <div id='ajaxContent'>
this is students.php
<?php
echo "<table id='tblStudents'>\n";
echo "<thead><tr>\n";
echo "<td>Namn</td>\n";
echo "<td>Personnummer</td>\n";
echo "<td>Startdatum</td>\n";
echo "<td>Slutdatum</td>\n";
echo "</tr></thead>\n";
echo "<tbody>\n";
while ($row = mysql_fetch_assoc($list_students)) {
$count = ($count + 1) % 2; //will generate 0 or 1 and is used to alternatve the css classes row0 and row1 in the loop result
echo "<tr class='row$count'>\n";
echo "<td><a class='ajaxCall' href='#' rel='".$row['student_id']."'>" . $row['student_firstname'] . "</a> " . $row['student_lastname'] . "</td>\n";
echo "<td>" . $row['student_socialnr'] . "</td>\n";
echo "<td>" . $row['student_startdate'] . "</td>\n";
echo "<td>" . $row['student_enddate'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
?>
<div id='ajaxContent'></div>
<script src="js/jfunc.js"></script>
This is jfunc.js
$('a.ajaxCall').click(function() {
var rowId = $(this).attr('rel');
$.ajax({
type: "get",
url: '/page/editstudent.php',
data: { student_id: rowId },
success: function(data) {
$('#ajaxContent').html(data);
}
});
});
Use event-delegation and listen for all clicks on the table.
$("#tblStudents").on("click", "tr", function(e){
var row_id = $("td:first a.ajaxCall", this).attr("rel");
$("#ajaxContent").html("Loading...");
$.ajax({
url: "/page/editstudent.php",
data: { 'student_id':row_id },
success: function(data){
$("#ajaxContent").html(data);
}
});
});
Side-issues
You don't need to add a classname of 0 or 1 to each table-row. With pure CSS you can target even and odd rows to style them differently:
#tblStudents tr:nth-child(even) {
background: #f1f1f1;
color: #999;
}
Additionally, I would encourage you to store the student id on a data attribute instead of the rel attribute. This is what the data attributes exist for. You could even store them on the <tr> itself. More about those at http://api.jquery.com/data/#data-html5.
1 a add a click event on each tr
$('#tblStudents').on('click', 'tr', function(e) {
// do something
]);
1 b prevent the click event bubling on ajaxCall
$('a.ajaxCall').click(function(e) {
e.preventDefault();
e.stopPropagation();
var rowId = $(this).attr('rel');
$.ajax({
type: "get",
url: '/page/editstudent.php',
data: { student_id: rowId },
success: function(data) {
$('#ajaxContent').html(data);
}
});
2 before requesting the ajax url, insert an image into ajaxContent. once the request has been completed the image will be overwritten with the new html

Turn Regular Javascript Into jQuery

I have some code that involves clicking on a button and either you are logged in and you go to the next page or you are logged out and you get an alert. I have never liked onClick inside HTML and so I would like to turn this around into clicking on the id and having the jQuery do its magic.
I understand the click function of jQuery, but I don't know how to put do_bid(".$val["id"]."); down with the rest of the Javascript. If I haven't given enough information or if there is an official resource for this then let me know.
<li class='btn bid' onclick='do_bid(".$val["id"].");'> Bid </li>
<script>
//Some other Javascript above this
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
</script>
UPDATE: This is the entirety of the Javascript code. I think none of the answers have worked so far because the answers don't fit the rest of my Javascript. I hope this helps
<script language="JavaScript">
$(document).ready(function(){
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "" + s + "";
}
function CountBack() {
<?
for($i=0; $i<$total_elements; $i++){
echo "myTimeArray[".$i."] = myTimeArray[".$i."] + CountStepper;";
}
for($i=0; $i<$total_elements; $i++){
echo "secs = myTimeArray[".$i."];";
echo "DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,1000000));";
echo "DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));";
echo "DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));";
echo "DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));";
echo "if(secs < 0){
if(document.getElementById('el_type_".$i."').value == '1'){
document.getElementById('el_".$i."').innerHTML = FinishMessage1;
}else{
document.getElementById('el_".$i."').innerHTML = FinishMessage2;";
echo " }";
echo "}else{";
echo " document.getElementById('el_".$i."').innerHTML = DisplayStr;";
echo "}";
}
?>
if (CountActive) setTimeout("CountBack()", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor, id) {
document.write("<span id='"+ id +"' style='background-color:" + backcolor + "; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined") BackColor = "white";
if (typeof(ForeColor)=="undefined") ForeColor= "black";
if (typeof(TargetDate)=="undefined") TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%%d, %%H%%h, %%M%%m, %%S%%s.";
if (typeof(CountActive)=="undefined") CountActive = true;
if (typeof(FinishMessage)=="undefined") FinishMessage = "";
if (typeof(CountStepper)!="number") CountStepper = -1;
if (typeof(LeadingZero)=="undefined") LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0) CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
var myTimeArray = new Array();
<? for($i=0; $i<$total_elements; $i++){?>
ddiff=document.getElementById('el_sec_'+<?=$i;?>).value;
myTimeArray[<?=$i;?>]=Number(ddiff);
<? } ?>
CountBack();
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
}</script>
If you want to attach click event handler using jQuery. You need to first include jQuery library into your page and then try the below code.
You should not have 2 class attributes in an element. Move both btn and bid class into one class attribute.
Markup change. Here I am rendering the session variable into a data attribute to be used later inside the click event handler using jQuery data method.
PHP/HTML:
echo "<li class='btn bid' data-bid='".$val["id"]."'>Bid</li>";
JS:
$('.btn.bid').click(function(){
do_bid($(this).data('bid'));
});
If you don't want to use data attribute and render the id into a JS variable then you can use the below code.
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
$('.btn.bid').click(function(){
if(!loged_in){
alert('You must log in to bid!');
}
else{
do_bid(loged_in);
}
});
First, you need to make the <li> have the data you need to send, which I would recommend using the data attributes. For example:
echo "<li class=\"btn bid\" data-bid=\"{$val['id']}\">Bid</li>";
Next, you need to bind the click and have it call the javascript method do_bid which can be done using:
function do_bid(bid){
//bid code
}
$(function(){
// when you click on the LI
$('li.btn.bid').click(function(){
// grab the ID we're bidding on
var bid = $(this).data('bid');
// then call the function with the parameter
window.do_bid(bid);
});
});
Assuming that you have multiple of these buttons, you could use the data attribute to store the ID:
<li class='btn' class='bid' data-id='<?php echo $val["id"]; ?>'>
jQuery:
var clicked_id = $(this).data('id'); // assuming this is the element that is clicked on
I would add the id value your trying to append as a data attribute:
Something like:
<li class='btn' class='bid' data-id='.$val["id"].'>
Then bind the event like this:
$('.bid').click(function(){
var dataId = $(this).attr('data-id');
doBid(dataId);
});
You can store the Id in a data- attribute, then use jQuery's .click method.
<li class='btn' class='bid' data-id='".$val["id"]."'>
Bid
</li>
<script>
$(document).ready(function(){
$("li.bid").click(function(){
if ("" === "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>") {
alert('You must log in to bid!');
}
else {
document.location.href="item.php?id=" + $(this).data("id");
}
});
});
</script>
If you are still searching for an answer to this, I put a workaround.
If data is not working for you, try the html id.
A working example is here: http://jsfiddle.net/aVLk9/

Categories