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
}
});
Related
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 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.
So I have the majority of my system working and I am stuck on one last bit
The GET is currentlyusing the same notification_id it gets from the while loop, so it constantly searches against that id for new records over and over.
LIKE SO...
jquery....4862996 (line 4)
GET http://viewajax.php?notification_id=43&_=1405814864693
jquery....4862996 (line 4)
GET http://viewajax.php?notification_id=43&_=1405814864694
What I'm looking to do is search the first notification_id from the while loop send it off to the server side viewajax.php to see if there is a new record and if there is insert it into its div, (which it currently does) but then use that same new notification_id from the server on its next ajax cycle for new records. I've tried everything and asked many questions and I've been looking high and low online for possible solutions to no avail.
Any help would be greatly appreciated and I will love you forever.
AJAX
<?
$user1_id=$_SESSION['id'];
$call="select * from notifications WHERE notification_targetuser='$user1_id' AND notification_status=1 ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
function loadIt() {
var notification_id=<?php echo $notification['notification_id'] ;?>
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(data){
$("#notif_actual_text-"+notification_id).prepend('<div class="notif_ui"><div class="notif_text"><div id="notif_actual_text-'+data['notification_id']+'" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+data['notification_triggeredby']+'.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br /></div></div></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
}
});
}
setInterval(loadIt, 10000);
</script>
<? }}?>
VIEWAJAX.php
if(isset($_GET['notification_id'])){
$id= mysqli_real_escape_string($mysqli,$_GET['notification_id']);
$user1_id= $_SESSION['id'];
$json = array();
$com=mysqli_query($mysqli,"select notification_id,notification_content,notification_time,notification_triggeredby from notifications where notification_id > '$id' AND notification_status='1' ");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num>0){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
$json['notification_triggeredby'] = $resultArr['notification_triggeredby'];
$json['notification_time'] = $resultArr['notification_time'];
mysqli_free_result($com);
echo json_encode($json);
}
EDIT
PHP SOURCE
{"num":0,"notification_id":null,"notification_content":null,"notification_triggeredby":null,"notification_time":null}
AJAX SOURCE
<script type="text/javascript">
function loadIt() {
var notification_id=44
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(data){
$("#notif_actual_text-"+notification_id).prepend('<div class="notif_ui"><div class="notif_text"><div id="notif_actual_text-'+data['notification_id']+'" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+data['notification_triggeredby']+'.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br /></div></div></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
}
});
}
setInterval(loadIt, 10000);
</script>
Why don't you just update "notification_status" to 0 after you retrieve it in the php parts? Then it will not be retrieved again.
I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});
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);
}
});