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();
}
}
}
});
}
Related
I want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});
I have a svg.php file with some shapes.
<rect onclick="window.location='search.php?filter=1'" width="50" height="50">
<rect onclick="window.location='search.php?filter=2'" width="50" height="50">
Search.php
div class="container">
<textarea class="search" id="search_id"></textarea>
<div id="result"></div>
<?php include("svg.php"); ?>
</div>
//This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var search_id = $(this).val();
var dataString = 'search='+ search_id;
if (search_id=='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).hide(); }
});
};
if(search_id!='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show(); }
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#search_id').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#search_id').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Then a search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
echo $search; //echos "2".
if ($search=="1") {
echo $search; //enters if, and it's not supposed to, and echos "1"
Select * from table;
}
Search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : "1";
echo $search //echos "2";
if ($search=="1") {
$q = $_POST['search'];
$q_length = strlen($q);
$sql = <<<SQL
SELECT * FROM table
LIMIT 6
SQL;
if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');
}
while($row = $result->fetch_array()) { ?>
<div class="show_search">
<?php echo $row['name'] ?> </a>
</div>
<?php } } ?>
I'm on search.php?filter=2 and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1".
I'm not defining the $search variable anywhere else. Thank you for your help.
Your code is a bit too complicated.
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
if($search == 1) {
echo $search;
}
Thats enough, you don't need the check if $_POST is available. That make not so much sense because you don't send a form and you don't have post data in that case when you it with window.location.
If there is no other code between following two lines:
echo $search; //echos "2".
AND
if ($_POST AND $search=="1") { ... }
Then, its not possible to go inside if condition. its only possible if your if condition is like if($_POST AND $search=1). Check that, whether you have single = or double == in comparing $search variable.
If there is some php code in between, then show us, whatever it is, so that we can help you.
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.");
});
Here is my code:
<div class="category" id="<?php echo $cat->term_id; ?>"><?php echo $cat->cat_name; ?> </div>
$(".category").click(function(){
var categ = $(this).attr('id');
alert(categ);
ajax({
type:'POST',
url:'http://myweb.com/rel_notes/?page_id=238',
data:'cat='+categ,
success:function(data) {
if(data) {
} else { // DO SOMETHING
}
}
});
});
and the code behind the page which is receiving the posted data (http://myweb.com//rel_notes/?page_id=238) is here:
<?php
if (isset($_POST['cat']))
{
$cat_id = $_POST['cat'];
echo "<script>alert('$cat_id')</script>";
}
else
$cat_id = NULL;
?>
Problem: It didn't get the value in $cat_id. I tried changing $_POST to $_GET but that didn't work too. So kindly help me where am i missing something?
$.ajax({
type:'POST',
data: {cat: categ},
url:'http://myweb.com//rel_notes/?page_id=238',
error: function() {
alert("Data Error");
},
success:function(data) {
if(data) {
} else {
}
}
});
This is not good way dude.
None can make alert on server side.
You are doing alert code on the server side.
Just replace
<?php
if (isset($_POST['cat']))
{
$cat_id = $_POST['cat'];
echo "<script>alert('$cat_id')</script>";
}
else $cat_id = NULL;
?>
by
<?php
if (isset($_POST['cat']))
{
echo $cat_id = $_POST['cat'];
}
else {
echo $cat_id = "";
}
?>
and alert the code like
$(".category").click(function(){
var categ = $(this).attr('id');
alert(categ);
ajax({
type:'POST',
url:'http://myweb.com/rel_notes/?page_id=238',
data:'cat='+categ,
success:function(data) {
if(data != "") {
alert(data);
}else { // DO SOMETHING
}
}
});
});
I am trying to make a webapp and I have used a php, ajax and mysql search function from another site.
It currently allows me to search the database and return what I want. The only problem I am having is that it returns the results in a simple text box. I want to be able to return the results in a table.
The search simply searches the database for forename, surname, address etc... This is the code I have.
php:
<?php
include('config.php');
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$sql=mysql_query("SELECT * FROM info WHERE CONCAT(Forename,' ',Surname) LIKE '%$search_word%'or Address1 LIKE '%$search_word%' or Address2 LIKE '%$search_word%' or Postcode LIKE '%$search_word%' or DOB LIKE '%$search_word%' ORDER BY ID DESC LIMIT 20 ");
$count=mysql_num_rows($sql);
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
}
?>
This is connecting into the database and pulling out the results. I then have my html etc...:
script:
$(function() {
//-------------- Update Button-----------------
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
// $("#MainTable").append(data);
if(html.length > 0)
{
$("#MainTable tr:not(:first-child)").remove();
}
for(var i = 0; i < html.length; i++)
{
var date = new Date(html[i]["Timestamp"]*1000);
html[i]["Timestamp"] = date.getHours()+":"+date.getMinutes();
$("#MainTable").append("<tr><td><a href='#' id='info"+data[i]["ID"]+"' data-role='button' data-theme='b' data-icon='check' data-iconpos='notext' class='id'></a></td><td>"+data[i]["Timestamp"]+"</td><td>"+data[i]["ID"]+"</td><td>"+data[i]["Forename"]+" "+data[i]["Surname"]+"</td><td class='hidden'>"+data[i]["ID"]+"</td><td>"+data[i]["DOB"]+"</td><td class='hidden'>"+data[i]["Address2"]+"</td><td class='hidden'>"+data[i]["Town"]+"</td><td class='hidden'>"+data[i]["City"]+"</td><td class='hidden'>"+data[i]["County"]+"</td><td>"+data[i]["Address1"]+"</td><td>"+data[i]["Postcode"]+"</td><td class='hidden'>"+data[i]["Phone2"]+"</td><td class='hidden'>"+data[i]["DOB"]+"</td></tr>");
if(data[i]["Completed"] == "1")
{
$("#MainTable tr:last-child td").addClass("lineThrough");
}
$("#MainTable tr:last td:first a, #MainTable tr:last td:last a").button();
}
}
});
}
return false;
});
//---------------- Delete Button----------------
});
I have tried a few different things such as changing the +Data+ in the table script to html or tried adding append(html) but I am having no luck and when I search I am instead getting undefined in my table or it is blank completely.
This is the HTML for my table:
<table data-role="table" id="MainTable" data-mode="columntoggle">
<tr><th> </th><th>ID Number</th><th>Name</th><th>DOB</th><th>Address</th><th>Postcode</th></tr>
<tr><td colspan='7'>No data currently available, connect to the internet to fetch the latest appointments.</td></tr>
</table>
Would appreciate any help with this. Hope this makes sense.
Instead of outputting this in your php page:
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
Loop through the results outputting them in the table format you need, e.g:
echo "<tr>";
echo "<td>".$row['Forename']."</td>";
echo "<td>".$row['Surname']."</td>";
//etc
echo "</tr>"
Then take that response and fill the containing table with (jquery AJAX) something like:
.done(function( response ) {
$('#MainTable').html(response);
}
Changes:
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<tr>
<td> </td>
<td><?=$row['id']?></td>
<td><?=$final_msg?></td>
<td><?=$row['address']?></td>
<td><?=$row['postcode']?></td>
</tr>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
Changes in the JS
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
$("#MainTable").append(html); //<-- append the data from the ajax
}
});