Posting data without refresh + calling another jquery function - javascript

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>');
}
}
});
});

Related

Drag and Drop using jQuery Save the new order

i'm using drag and drop to order a list with jquery ....
and i want to save the new order to Database by clicking a button for exemple
this is my methode to get list element
public function test() {
$choice = Database::getInstance()->query("SELECT * FROM choix WHERE condidat_concour_id = ".$this->data()->ID." ORDER BY ordre ASC");
foreach($choice->results() as $choi){
$cs_code = $choi->cs_code;
$cs = Database::getInstance()->query("SELECT code,designation,site
FROM cs
WHERE code = '{$cs_code}' ");
echo "<li id=".$choi->id.">";
echo "<span class='handle'><i class='fa fa-ellipsis-v'></i><i class='fa fa-ellipsis-v'></i></span>";
echo "<span class='text'>".$choi->cs_code."</span>";
echo "</li>";
}
}
I'm looking to use this Script to save order
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('id');
else
articleorder += "," + $(this).attr('id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('set_order.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
but i don't know what i should use in set_order.php ??
i'm trying with this code but i didn't get any result !!
$i = 1 ;
$orderlist = explode(',', $_POST['ordre']);
foreach ($orderlist as $k=>$order) {
$sql = 'UPDATE choix SET ordre = :ordre WHERE id = :id' ;
$query = $pdo->prepare($sql);
$query->bindParam(':ordre', $i, PDO::PARAM_INT);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$i++ ;
}
you can check my Database classe here

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)

How can I add php variables to this 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;
}

Displaying existing content in editable textarea

Hi I am trying to make editable page with javascript and php and I want to display whats already stored in the area however it does not work. Its meant to be a blog page meaning that there are multiple posts. And I am unsure whether the problem is within the js or php.
This is the javascript I am using. The console.log() writes that post_id is unassigned.
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = '<textarea class="editPostBody">' + data.body + '</textarea>';
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});
});
var formatPost = function(d) {
var s = '';
s = '<div class="post" data-id="' + d.post_id + '"><h2 class="postHeading">' + d.title +'</h2>';
s += d.body;
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '</div>'
return s;
};
And this is the PHP file
connection to db established prior
if(count($_GET)) {
if(isset($_GET['post_id'])){
get_post_id( $_GET['post_id']);
}
}
else{
get_posts();
}
function get_posts() {
global $link;
// $sql = "SELECT COUNT(1) FROM posts";
// $result = mysqli_query($link, $sql);
// $total = mysqli_fetch_array($result);
$sql = "SELECT * FROM post ORDER BY date DESC LIMIT 0, 5";
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
// $json = '{"total":"' . $total[0] . '","posts":';
$json = json_encode($rows);
// $json .= "}";
print($json);
}
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
Thank you
I modified the code like this
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE post_id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
and JS
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
// console.log(post_id);
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = $('<textarea class="editPostBody">' + data.body + '</textarea>');
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});

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
},
...

Categories