How can I add php variables to this Javascript? - javascript

I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>

I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}

Related

Posting data without refresh + calling another jquery function

My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});

Simple JSON code doesn't work

This code tries to populate a dropdown list in a form with values. I have tested the PHP separately and the query is ok (small wonder !). I have a similar form whith 3 connected dropdown lists and they work flawlessly. Debugging this in Mozilla, I notice that the success function of JSON is not executed. I cannot understand why.
JavaScript
$(document).ready(function()
{
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
// var selOption = document.getElementById("selJudet");
// selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
// document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
// selText.value = selText.defaultValue;
selText.value = "Abcgcfkjsdhfsjkdh";
// $("#selText").change();
});
});
PHP (I skipped the database connection code)
$query = '(SELECT 1 AS sc, nume_judet FROM sa_Judet ';
$query .= 'WHERE nume_judet <> "N/A" ) UNION ';
$query .= '(SELECT 2 AS sc, "N/A" FROM sa_Judet) ';
$query .= 'ORDER BY sc, nume_judet';
//print $query;
$result = mysqli_query($db_conn, $query);
$judet = array();
if ($result == FALSE)
{
array_push($judet, 'QUERY_ERROR');
goto _adr1;
}
$rows = mysqli_num_rows($result);
if ($rows == 0)
{
array_push($judet, 'TBD_');
goto _adr1;
}
while ($row = mysqli_fetch_array($result))
{
array_push($judet, $row['nume_judet']);
}
_adr1:
print json_encode($judet);
mysqli_free_result($result);
mysqli_close($db_conn);
?>
Ajax variant of my original Javascript
$(document).ready(function()
{
$.ajax({
url: "/scripts/033A_GetJudet.php",
dataType: 'json',
success: function(data)
{console.log('SUCCESS: ', data);},
error: function(data)
{console.log('ERROR: ', data);}
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
var selOption = document.getElementById("selJudet");
selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
selText.value = selText.defaultValue;
// $("#selText").change();
});
});
It is possibly an error in parsing the data received. HTTP 304 is the same as HTTP 200, only the contents is pulled from cache, not serverside.
$.ajax({
url: url,
data: data,
success: function(response, textStatus, jsqxhr) {
var obj; try { obj = eval(response); } catch(e) { console.error(e); }
// -- do something with obj --
},
fail: function(jqxhr, textStatus, error) {
console.log( "error", textStatus, error);
}
});
Use this function instead and look closer at the data. If data is returned through success, we try to evaluate the json string into an object. Should it fail, an exception is thrown (possibly SyntaxError) and log should show this.
Replace this line
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
with this one
$.getJSON("/scripts/033A_GetJudet.php", function(data)

PHP,Jquery(ajax) post uncaught syntaxerror:unexpected token <

guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});

Pagination jTable in PHP

How to use paging in jTable use PHP?
I have code below in employeeTable.php
<script src="jtable.2.4.0/jquery.jtable.min.js" type="text/javascript"></script>
//Get record count
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM employee;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
Then I realize the problem is in here
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
if I change $_REQUEST["jtSorting"] = rowname, $_REQUEST["jtStartIndex"] = number, $_REQUEST["jtPageSize"] = number, it works.
But if I don't change it, it shows 'An Error Occured While Communicating to the server'.
here is the code in jquery.jtable.min.js, when there are line about jtSorting, jtStartIndex, jtPageSize
/* Adds jtSorting parameter to a URL as query string.
*************************************************************************/
_addSortingInfoToUrl: function (url) {
if (!this.options.sorting || this._lastSorting.length == 0) {
return url;
}
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
return (url + (url.indexOf('?') < 0 ? '?' : '&') + 'jtSorting=' + sorting.join(","));
},
/* Overrides _createJtParamsForLoading method to add sorging parameters to jtParams object.
*************************************************************************/
_createJtParamsForLoading: function () {
var jtParams = base._createJtParamsForLoading.apply(this, arguments);
if (this.options.sorting && this._lastSorting.length) {
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
jtParams.jtSorting = sorting.join(",");
}
return jtParams;
}
});
})(jQuery);
Can anybody please help me understand?
I think you should go through this once.
Listaction jtable for Pagination and sorting table
It would require jQuery.Deferred to return data.
Handle it as
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Employee_Controller/EmployeeList_method?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
Manually post values for it. I hope this maybe helpful.
the options will be received in $_GET object
like:
$jtStartIndex=$_GET['jtStartIndex'];
$jtPageSize=$_GET['jtPageSize'];
$jtSorting=$_GET['jtSorting'];
example:
$query="select * FROM products ORDER BY $jtSorting LIMIT $jtStartIndex, $jtPageSize;";
and in jtable settings:
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'name ASC' ,
actions: {
listAction: 'data/products.php'//Set default sorting
},
...

undefined error when iterating over json list

i got this code that keep on returning undefined msg instead of the expected html.
Purpose of function:
the purpose of the below function is to return notifications in away similar to fb one's. the code is working fine. but there's something wrong with the getJSON part that i couldn't figure out. so instead of returning "clonex1 likes your post" i get undefined.
the code
function buzzme()
{
jQuery('#cnumber').removeClass();
jQuery('#cnumber').empty();
jQuery('#floating_box').toggle();
var nHeader = '<div id="floating_box" class="fb">' +
'<div id="header"><span id="htext">Notifications</span></div>' +
'<div id="int">' +
'<div id="bodyx">' +
'<ul>';
var nFooter = '</ul>' +
'<div class="jfooter">' +
'See all notifications' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var nContent;
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
});
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
}
notifications.php - setUpFlayout(); and setUpJSONList()
function setUpFlyout() {
$notify = new se_notify();
$data2 = $notify->notify_summary();
$trk = 0;
if($data2['total'] >= 1) {
for($i = 0; $ $i <= $data2['total']; $i++) {
$nid = $data2['notifys'][$i]['notify_id'];
$im = $data2['notifys'][$i]['notify_icon'];
$img = "<img src='./images/icons/$im' />";
$notifier = $data2['notifys'][$i]['notify_text'][0];
$atype = $data2['notifys'][$i]['notifytype_id'];
$url = '';
$url2 = $data2['notifys'][$i]['notify_url'];
if($atype == 1) {
$url = ' has sent you friend <a href='.$url2.'>request</a>';
}
$trk++;
if($data2['total'] >= 2) {
$ret_arr = '';
if($i == 0) {
$ret_arr = '[';
}
$ret_arr = $ret_arr.setUpJSONList($data2['total'], $nid, $img, $notifier, $url, $trk);
if($i == $data2['total']-1) {
$ret_arr = $ret_arr.']';
}
echo '';
} else if($data2['total'] == 1){
//$ret_arr = '[{"dh3":"'.$data2['total'].'","nid":"'.$nid.'", "img":"'.$img.'","notifier":"'.$notifier.'","url":"'.$url.'"}]';
$ret_arr = '';
echo $ret_arr;
}
if($i == ($data2['total']-1))
break;
}
}
}
setUpJSONList();
function setUpJSONList($total, $nid, $img, $notifier, $url, $track) {
$comma = ',';
$lp = '';
$rp = ']';
$result = '';
if($track == $total) {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"}';
} else {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"},';
}
return $result;
}
thanks
Your usage of nContent after getJSON might be undefined since getJSON is asynchronous and would not have completed initializing nContent. You need to move the code using nContent inside the callback of getJSON.
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
});

Categories