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.");
});
Related
I have a page with 12 check boxes one ever hr, the display OK, Trying to on change event to run on each
I can add 24 of them but looking for a better way this is what I have tried and does not work.
<script>
$(document).ready(function(e) {
var i = 0;
while ( i < 23)
{
$('#' + i).change(function(){
if( $('#'+ i).prop('checked') )
{checkboxstatus = "YES";}
else
{checkboxstatus = "NO";}
$.ajax({
type: "POST",
url: "timepost.php",
data: {checkbox: i ,user: <?php echo $iduser; ?>, checkboxstatus: checkboxstatus},
})
//.done(function(data, textStatus, jqXHR){alert(textStatus);})
//.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
i++;
}
});//end ready
</script>
<?php include 'footer.php'; ?>
</body>
</html>
<?php
function tr($row,$hr)
{
if ($row)
{
$checked = "checked";
}
else
{
$checked = "";
}
print ("<td><input type=\"checkbox\" id=\"" . $hr . "\" name=\"" . $hr . "\" " . $checked . "></td>\r\n");
}
?>
There is no need to do a while loop here, jQuery can find all elements for you. Attached code should work
<script>
$(document).ready(function(e) {
// jQuery will find all elements with class checbox-class
$('.checkbox-class').on('change', function(){
if ($(this).prop('checked')) {
checkboxstatus = "YES";
} else {
checkboxstatus = "NO";
}
$.ajax({
type: "POST",
url: "timepost.php",
data: {checkbox: $(this).attr('id') ,user: <?php echo $iduser; ?>, checkboxstatus: checkboxstatus},
})
//.done(function(data, textStatus, jqXHR){alert(textStatus);})
//.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
});//end ready
</script>
<?php include 'footer.php'; ?>
</body>
</html>
<?php
function tr($row,$hr)
{
if ($row)
{
$checked = "checked";
}
else
{
$checked = "";
}
print ("<td><input type=\"checkbox\" class=\"checkbox-class\" id=\"" . $hr . "\" name=\"" . $hr . "\" " . $checked . "></td>\r\n");
}
?>
I'm new here and I need help with a PHP code.
I want to transform a radio button into a checkbox, make it calculate the fee depending on how much checkboxes are checked, and to transmit the checked values to the predefined database.
My code only takes the one predefined value for fee an doesn't actually adds them up when I click on the other checkbox. I tried everything but with no success. Here is the original unchanged code:
<script src="<?php echo URL_FRONT_JS;?>jquery.js"></script>
<script>
function get_tutor_course_details()
{
course_slug = $('#course_slug option:selected').val();
selected_date = $('#start_date').val();
if(!course_slug || !selected_date) {
$('#fee').text('');
$('#duration').text('');
$('#days_off').text('');
$('#content_li').remove();
$('#time_slot_div').text('<?php echo get_languageword("please_select_course_and_date_first"); ?>');
return;
}
$.ajax({
type: "POST",
url: "<?php echo URL_HOME_AJAX_GET_TUTOR_COURSE_DETAILS; ?>",
data: { "course_slug" : course_slug, "tutor_id" : <?php echo $row->id; ?>, "selected_date" : selected_date },
cache: false,
beforeSend: function() {
$('#time_slot_div').html('<font color="#5bc0de" size="6"> Loading...</font>');
},
success: function(response) {
if(response == "") {
$('#fee').text('');
$('#duration').text('');
$('#days_off').text('');
$('#content_li').remove();
$('#time_slot_div').html('<?php echo get_languageword("no_slots_available."); ?> <?php echo get_languageword("click_here_to_send_me_your_message"); ?>');
$('#request_tutor_btn').slideUp();
} else {
var fee_duration = response.split('~');
var fee = fee_duration[0];
var duration = fee_duration[1];
var content = fee_duration[2];
var time_slots = fee_duration[3];
var days_off = fee_duration[4];
$('#fee').text(fee +'€');
$('#duration').text('EUR');
if(content) {
$('#content_li').remove();
$('#course_li').after('<li id="content_li"><?php echo get_languageword("course_content"); ?><p>'+content+'</p></li>');
}
time_slot_html = "";
if(time_slots != "")
time_slots = time_slots.split(',');
total_available_timeslots = time_slots.length;
if(total_available_timeslots > 0) {
for(i=0;i<total_available_timeslots;i++) {
check_radio = "";
if(i == 0)
check_radio = 'checked = "checked"';
time_slot_html += '<li><div><input id="radio1'+i+'" type="radio" name="time_slot" value="'+time_slots[i]+'" '+check_radio+' ><label for="radio1'+i+'"><span><span></span></span>'+time_slots[i]+'</label></div></li>';
}
$('#time_slot_div').html(time_slot_html);
$('#request_tutor_btn').slideDown();
} else {
$('#time_slot_div').html('<?php echo get_languageword("no_slots_available."); ?> <?php echo get_languageword("click_here_to_send_me_your_message"); ?>');
$('#request_tutor_btn').slideUp();
}
}
}
});
}
I am trying to create a simple comment bar using PHP, AJAX, MySQL and json coding.
I've got two files written in php, the first one being a controller with a following code:
<?php
require("../includes/config.php");
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$comments = query("SELECT comments.comment, comments.author, comments.time FROM comments WHERE workid = ?", $_GET["workid"]);
echo json_encode($comments);
}
else if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_SESSION["userid"])) {
throw new Exception("Login");
}
else {
$result = query("INSERT INTO comments (comment, author, time, workid) VALUES(?, ?, ?, ?)", $_POST["text"], $_SESSION["userid"], date("Y-m-d H-i-s"), $_POST["workid"]);
if ($result !== false) {
echo "success";
}
}
}
?>
The second one is purported to display the records from MySQL, based on the data from the controller:
<script>
//loads the comments
$(document).ready(function(){
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.comment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
});
</script>
<script>
$(document).ready(function(){
$("#comment-button").click(function(){
$.ajax({
type: "POST",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>,
text: $("#comment-textarea").val()
},
dataType: "text",
success: function(e) {
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.domment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
$("#comment-textarea").val("");
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
}
});
});
});
</script>
Everything works pretty fine, except of the final step; when displaying the data from the database, the only thing displayed is a statement 'undefined' instead of the corect data. Except of this, the amount of comments and form display correctly. I am using a Apache server with a php installed.
In your JavaScript code, you need to replace comments.<xxx> with comment.<xxx>, since comments is indeed an undefined object in your JaveScript.
Strange things happen often.
The code works fine but when I alert the PHP echo from javascript it displays like this:
"< html > Login başarılı. < /html >"
click to view the screenshot
How can I get rid of that html tag in the message?
This is my javascript:
var dataString = 'user_eposta='+ eposta + '&user_sifre=' + sifre;
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString,
success: function(mesaj) {
alert(mesaj);
}
});
and this is the PHP:
<?php
$con=mysqli_connect("pantuff.com","ttoykoc","*******","db_pantuff");
if (mysqli_connect_errno($con))
{
echo "MySQL Bağlantısı yapılamıyor." . mysqli_connect_error();
} else
{
$result = mysqli_query($con,"SELECT * FROM member");
while($row = mysqli_fetch_array($result))
{
if ($row['user_eposta'] == $_POST['user_eposta'] && $row['user_sifre'] ==
$_POST['user_sifre'])
{
$adsoyad = $row['user_ad'] . " " . $row['user_soyad'];
$_SESSION['username']= $adsoyad;
setcookie("currentuser", $adsoyad, time()+(84600*30));
echo "Login başarılı.";
} else
{
echo "Kullanıcı adı ya da şifre hatalı!";
}
}
}
mysqli_close($con);
?>
alert($(mesaj).text());
alert($(mesaj).html());
$(mesaj) builds a jQuery object from html. Then text or html function fetches the message, where html gets the message with html entities in it, while text contains no entities.
A different solution, as proposed above in the comments:
Add header("Content-Type: text/plain"); in line 2 of the file outputting the text, and:
var dataString = 'user_eposta='+ eposta + '&user_sifre=' + sifre;
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString,
dataType: 'text',
success: function(mesaj) {
alert(mesaj);
}
});
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