Hi i have small project which will display news from last 4,6 weeks. I have created select box which will ask for news from last 4,6 weeks. and submit button.So user select news from select box and click on submit button and he will get the result. But i am not getting proper ouput not even getting any error. By default i dont know why the ouput displaying data from database. And my submit button is not even showing active.I am making small mistake which is not able to identify. Thanks.
js file
$.ajax({
type: "POST",
url: "ajax/edit_news.php",
dataType : 'json',
cache: false,
data: {'aktion' : 'edit-news'},
success: function(data){
$('#editnews').html(data.html);
}
});
Here is my code:
<?php
chdir('..');
include 'constant/const_system.inc.php';
include 'functions/ad_json.inc';
include 'functions/ad_formulare.inc';
include 'constant/const_system_db.inc.php'; //database file
$return = array();
if(isset($_POST['BtnSubmit']))
{
if(($_POST['news'])==4){
$sql=" SELECT DISTINCT ad_news_texte.headline, ad_news.datum_archiv
FROM ad_news_texte
INNER JOIN ad_news_oe ON ad_news_texte.news_id = ad_news_oe.id_ad_news
INNER JOIN ad_news ON ad_news_oe.id_ad_news = ad_news.id
WHERE ad_news.datum_archiv
BETWEEN curdate( ) - INTERVAL DAYOFWEEK( curdate( ) ) +28
DAY AND curdate( )
";
$sql_select=mysql_query($sql);
while($row = mysql_fetch_array($sql_select)) {
echo $row['headline'] . " " .$row['datum_archiv'] ;
echo "<br>";
}
}
if(($_POST['news'])==6){
$sql=" SELECT DISTINCT ad_news_texte.headline, ad_news.datum_archiv
FROM ad_news_texte
INNER JOIN ad_news_oe ON ad_news_texte.news_id = ad_news_oe.id_ad_news
INNER JOIN ad_news ON ad_news_oe.id_ad_news = ad_news.id
WHERE ad_news.datum_archiv
BETWEEN curdate( ) - INTERVAL DAYOFWEEK( curdate( ) ) +42
DAY AND curdate( )
";
$sql_select=mysql_query($sql);
while($row = mysql_fetch_array($sql_select)) {
echo $row['headline'] . " " .$row['datum_archiv'] ;
echo "<br>";
}
}
}
if($param['aktion'] == 'edit-news')
{
$html = '
<form name="UserInformationForm" method="POST" action="#">
<select name="news">
<option value="4" '. (($_POST['news']=="4") ? "selected=selected" : "" ) .'>Show news from last 4 weeks</option>
<option value="6" '. (($_POST['news']=="6") ? "selected=selected" : "") .'>Show news from last 6 weeks</option>
</select>
<br/><br/>
<input name="BtnSubmit" type="submit" value="Submit" >
</form>
';
$return = array(
'status' => 1,
'html' => $html
);
echo json_encode($return);
die();
}
?>
And its showing output like this:
You are returning a invalid json mixed with html, that's why its not working, here is code you need to change
//Change this in both places
...
$news = '';
$sql_select=mysql_query($sql);
while($row = mysql_fetch_array($sql_select)) {
$news .= $row['headline'] . " " .$row['datum_archiv'] ;
$news .= "<br>";
}
...
//and return news like below
$return = array(
'status' => 1,
'news' = $news
);
//Return the json
header('Content-Type: application/json');
exit(json_encode($return));
Add below line in the top of file
header('Content-Type: application/json');
Try this
$.ajax({
type: "POST",
url: "ajax/edit_news.php",
dataType : 'html',
cache: false,
data: {aktion: 'edit-news'},
success: function(data){
$('#editnews').html(data.html);
}
});
and do echo html . dont json
like echo $html; . This will fix your issue
Related
I'm beginner at JS, AJAx, and so on. I was searching over the internet and found one code, so I used it, changed it a little... but it seems that it doesn't work (it does nothing).
First the javascript and html:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
<select onchange="fetch_select(this.value);">
<option>Wybierz</option>';
$zapytanie = "
SELECT
scan_category.scat_id,
scan_category.long_name
FROM
scan_category
WHERE
scan_category.state = 1 OR scan_category.state = 4 and scan_category.hide = 0
ORDER BY
scan_category.long_name";
$wykonaj = mysql_query($zapytanie) or die(mysql_error());
while($row=mysql_fetch_array($wykonaj))
{
echo '<option>'.$row[1].'</option>';
}
echo'</select>
<div id="new_select">
</div>';
$manga = $_POST['get_option'];
$znajdz = "
SELECT users.nick, scan_category.long_name, scan_work.work_name, scan_roles.role_id, scan_roles.scat_id, scan_roles.uid, scan_roles.what_id
FROM scan_roles
INNER JOIN scan_work ON scan_roles.what_id = scan_work.work_id
INNER JOIN users ON scan_roles.uid = users.uid
INNER JOIN scan_category ON scan_category.scat_id = scan_roles.scat_id
WHERE
scan_roles.scat_id = '$manga'";
$wykonaj = mysql_query($znajdz or die(mysql_error());
while ($row = mysql_fetch_array($znajdz)) {
echo '<h2>'.$row[1].
'</h2><br />'.$row[2].
':
<form enctype="multipart/form-data" action="manage.php5?mode=edit_role&edit&role_id="'.$row[4].
' method="POST">
<input type="hidden" name="pass" value="'.$_POST['pass'].
'">';
echo('<select name="user_id" size="1">');
$zapytanie = '
SELECT
users.uid,
users.nick
FROM
users
WHERE
active > 0
ORDER BY
users.nick';
$wykonaj2 = mysql_query($zapytanie) or die(mysql_error());
while ($wiersz = mysql_fetch_array($wykonaj)) {
echo('<option value="'.$wiersz[0].
'"');
if ($wiersz[0] == $row[6]) echo ' selected="selected"';
echo('>'.$wiersz[1].
'</option>');
}
echo '</select>';
echo('<input type="submit" value="edit">
</form>');
Do you have any idea how to make it work (it doesn't seem to be even going to the file "fetch_data.php).
If I should add something else, tell me, I'm pretty much beginner!
When i put console.log(response) it does say ReferenceError: response is not defined, when i puted it like this - console.log("response") it gives me "response".
For a few days I am busy solving following. I would like to load bootstrap table through a click into a <div>. My situation:
index.php
<div id="page-content">
<div id="data" class="animated"></div> on page load, loaddata
<div id="table" class="animated">
<table id="report-table" data-toggle="table"></table>
</div> hidden, onclick hide #data and show #table
</div>
loaddata.php
$tab_id = $_POST['tab_id'];
$tab_name = $_POST['tab_name'];
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = $tab_id ORDER BY document_datum");
if (!$selectTabbladen->execute()) return false;
if ($selectTabbladen->rowCount() > 0) {
$tabblad_data = array();
while ($tabdata = $selectTabbladen->fetch()) {
$tabblad_data[] = array(
"id" => $tabdata['id'],
"document_soort" => $tabdata['document_soort'],
"voornaam" => $tabdata['voornaam'],
"relatie_naam" => $tabdata['relatie_naam'],
"tabblad" => $tabdata['document_status'],
"status" => $tabdata['document_status'],
"aanmaak_datum" => $tabdata['document_datum'] = date('d M Y H:i:s'),
"laatst_gewijzigd" => $tabdata['document_datumgewijzigd'] = date('d M Y H:i:s'),
);
}
print '</tbody>
</table>
';
$json_data = json_encode($tabblad_data);
print_r ($json_data);
}
ajax
$('body').on('click', '.tab_data', function () {
content.hide();
$('#dataa').show();
var tab_id = $(this).attr("id");
$.ajax({
type: "POST",
url: "loaddata.php",
data: {
tab_id: tab_id
},
dataType:"json",
success : function(data) {
$('#report-table').bootstrapTable({
data: data
});
}
});
});
As result I'm getting:
No matching records found
Can you help me please. What am I doing wrong?
If you have passed your tab_id correctly then the problem is with your query
Instead of
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = $tab_id ORDER BY document_datum");
try this
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = ".$tab_id." ORDER BY document_datum");
Updated
Try this
$('#report-table').bootstrapTable({
'load': data
});
I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . Wİthout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;
I tried to modified the long polling code to fit my situation.
I would like to count the total number from mysql and if the number changes (increase or decrease), it will notify me.
The problem is the while loop keep looping. How can I stop it? I just need to have notification whenever the total sum change.
<?php
include("db.php");
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$old_totalsum = $row['totalsum'];
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var old_totalsum =<?php echo $old_totalsum; ?>;
function waitForMsg(){
$.ajax({
type: "GET",
url: "poll.php?old_totalsum=" + old_totalsum,
async: true,
cache: false,
success: function(data){
var json = "eval(+(" + data + ")+)";
if(json['msg'] != "") {
alert(data);
}
old_msg_id = json['old_msg_id'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
}); // end ajax
} //end waitformsg
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<div id="chat">
</div>
</body>
</html>
<----------------------------------------------------------->
poll.php
<----------------------------------------------------------->
<?php
include("db.php");
$old_totalsum = $_GET['old_totalsum'];
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
}
while($last_sum < $old_totalsum || $last_sum > $old_totalsum)
while($last_sum <= $old_totalsum)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
//echo $last_sum;
//return;
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $last_sum;
echo json_encode($response);
?>
<------------------------------------------->
I expected logic like this:
$latest_sum= -1;
// Loop until sum from DB is different from what was passed in
while( $latest_sum == -1 || $latest_sum!= $old_sum ){
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$lastest_sum = $row['totalsum'];
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $latest_sum;
echo json_encode($response);
If it takes a long time to change, then Apache (or whatever is running PHP) will likely cancel the request. This is also going to run lots of queries on the db which is expensive.
So it would be better to have your loop in the javascript. It would call a function that would just return the latest sum from the database. The javascript should wait a second or more inbetween each request.
If performance is still too hard on the database, then the php should somehow cache the value every minute and return the cached value.
Quick sum up: I have a facebook-like activity wall on the user profiles. There are multiple "sorting" options to choose from. So if they want to only see, say, their own activity, they click "Your Activity". That part works perfectly. I am adding a new piece to this puzzle, where they can also sort through certain types of activity such as: posts, comments, votes, etc.
What I am trying to get this to do is, if they have their activity already selected, and then they check the Posts and Responses checkboxes, it should display only their posts and responses.
I am using checkboxes so they can check/uncheck things at will and jquery ajax/php to call this. Here are the checkboxes:
<div class="activitySelector">
Following Activity • Your Activity
</div>
<input type="checkbox" class="sortOption" id="post" /><label for="post">Posts</label>
<input type="checkbox" class="sortOption" id="response" /><label for="response">Responses</label>
Here is the jQuery/ajax:
$('input[type=checkbox]').live("click", function(){
$('input:checked').each(function(){
var ID = $('.activitySelector .selected').attr("id");
var optionID = $(this).attr("id");
if (optionID) {
$('ul.streamActivity').html('<img src="/images/ajax-loader.gif" class="loader" alt="" />');
$.ajax({
type: "POST",
url: "/profile/sort_activity.php",
data: "sort="+ID+"&option="+optionID+"&user=<?php echo $user; ?>",
cache: false,
success: function(html){
$("ul.streamActivity").html(html);
}
});
}
});
});
And finally the PHP (I am only showing the code that has to do with what I am talking about...I have no need to show the full query as it is working perfectly, I just want you to be able to get right to the headache :P): sort_activity.php
if ($sort == "user") {
$checkActivity .= " WHERE a.name = '$user'";
$activityNum .= " WHERE a.name = '$user'";
if ($option == "post") {
if ($option == "response") {
$checkActivity .= " AND a.type = 'Post' AND (a.type = 'Comment' OR a.type = 'Advice')";
$activityNum .= " AND a.type = 'Post' AND (a.type = 'Comment' OR a.type = 'Advice')";
} else {
$checkActivity .= " AND a.type = 'Post'";
$activityNum .= " AND a.type = 'Post'";
}
} elseif ($option == "response") {
if ($option == "post") {
$checkActivity .= " AND a.type = 'Post' AND (a.type = 'Comment' OR a.type = 'Advice')";
$activityNum .= " AND a.type = 'Post' AND (a.type = 'Comment' OR a.type = 'Advice')";
} else {
$checkActivity .= " AND (a.type = 'Comment' OR a.type = 'Advice')";
$activityNum .= " AND (a.type = 'Comment' OR a.type = 'Advice')";
}
}
}
So, essentially what this needs to do is realize that "Your Activity" (user) was already selected, and then IF "Posts" AND "Responses" is chosen after that, then display only YOUR posts and responses. Right now, it only displays one or the other (if both "posts" and "responses" are selected it seems to display only your responses. Which is half-way there lol.)
I've thought of maybe setting cookies or such so it remembers what they have checked, but I'd like to stay away from that if at all possible.
Any help would be greatly appreciated as I am trying to do a re-launch with these cool new features :)
UPDATE:
Here is the foreach statement I've added. Echo is in there to see if it's calling it properly, which it is. Checking on and off the boxes displays post/response/vote - it's just not displaying any results whatsoever :/
I think I need to do something like, if there's more than 1 option then change AND to OR so that it selects all of them...maybe? Can't seem to get it to work properly though.
if (isset($options)) {
foreach ($options as $option) {
echo $option .'<br />';
if ($option['post']) {
$checkActivity .= " AND a.type = 'Post'";
$activityNum .= " AND a.type = 'Post'";
}
if ($option['response']) {
$checkActivity .= " AND (a.type = 'Comment' OR a.type = 'Advice')";
$activityNum .= " AND (a.type = 'Comment' OR a.type = 'Advice')";
}
if ($option['vote']) {
$checkActivity .= " AND a.type = 'Vote'";
$activityNum .= " AND a.type = 'Vote'";
}
}
}
What's happening, is that you're not sending all the checked values to the server. Just change your click binding to this:
$('input[type=checkbox]').live("click", function(){
var options = []; //We'll send an array of options instead only one
var ID = $('.activitySelector .selected').attr("id");
$('input:checked').each(function(){
var optionID = $(this).attr("id");
options.push("options[]="+optionID);
});
if (options.length) {
$('ul.streamActivity').html('<img src="/images/ajax-loader.gif" class="loader" alt="" />');
$.ajax({
type: "POST",
url: "/profile/sort_activity.php",
data: "sort="+ID+"&options="+options.join("&")+"&user=<?php echo $user; ?>", //Here we're sending 'options'
cache: false,
success: function(html){
$("ul.streamActivity").html(html);
}
});
}
});
As you see, we're sending all the checked ID's (options) not only one.
Server side:
<?php
$options = $_POST['options'];
//Now $options is an array with all checked IDs
foreach($options as $option)... //Do your stuff with $options. Everything else remains the same
?>
Hope this helps. Cheers