Php ajax sort data based on user selected input - javascript

I have a html form in which user can select an option upon which ajax call should be fired to php controller.
<form action="<?php echo URL . 'task/show_list/' . $this->tasks[0]->list_id;?>" method="GET" id="#sortTaks">
<select name="sort_task" id="selectSortTask">
<option value="" selected="selected">Sort by:</option>
<option value="byName">Name</option>
<option value="byDeadline">Deadline</option>
<option value="byPriority">Priority</option>
<option value="byStatus">Status</option>
</select>
<input type="submit" value="Submit">
</form>
Now, i would like that sort functionality provided asynchronously with ajax. This is the corresponding php code:
//controller
public function show_list($list_id)
{
if (isset($list_id)) {
$task_model = $this->loadModel('TaskModel');
$check = $task_model->checkUserPermission($list_id);
if ($check) {
$tasks = $task_model->showTasks($list_id);
$this->view->tasks = $tasks;
$this->view->render('task/task');
} else {
header('location:' . URL . 'dashboard/index');
}
} else {
header('location:' . URL . 'dashboard/index');
}
}
//model
public function showTasks($list_id)
{
if (isset($_GET['sort_task']) and !empty($_GET['sort_task'])) {
$sort_parameter = strip_tags($_GET['sort_task']);
$sort_order = $this->sortData($sort_parameter);
$sort_order = 't.task' . $sort_order;
} else {
$sort_order = 't.task_name';
}
$sql = "SELECT t.task_name, t.task_id, t.task_priority, t.task_deadline, t.task_completed, l.list_id
FROM task AS t
LEFT JOIN list AS l ON l.list_id = :list_id AND l.list_id = t.list_id
WHERE l.user_id = :user_id
ORDER BY $sort_order";
$query = $this->db->prepare($sql);
$query->execute(array(':list_id' => $list_id, ':user_id' => $_SESSION['user_id']));
return $query->fetchAll();
}
//view snippet
echo '<td>' . $value->task_name . '</td><td>' . $priority . '</td><td>';
echo $task_deadline->format('l jS \of F Y h:i:s A');
echo '</td><td>';
echo $overdue_until->format('%R %a day/s, %h hours, %i minutes');
echo '</td><td>' . $status . '</td>';
echo '<td><a href="' . URL . 'task/edit_task/' . $value->list_id . '/' . $value->task_id . '">Edit</td>';
echo '<td><a href="' . URL . 'task/delete_task/' . $value->list_id . '/' . $value->task_id . '">Delete</td>';
echo '<td><a href="' . URL . 'task/completed/' . $value->list_id . '/' . $value->task_id . '">Completed</td>';
echo '</tr>';
What is the best approach in solving this problem? I'm a little bit confused with how should ajax call look like regarding mvc structure and presenting sorted data back to user.
Any help is much appreciated.
For now i have this:
$(document).ready(function(){
$('#selectSortTask').change(function(e){
e.preventDefault();
var sortParam = $('#selectSortTask').val();
$.ajax({
url: $(this).attr('action'),
type: "GET",
data: {sort_task: sortParam},
dataType: 'json',
success: function(data){
alert(data);
},
error: function(error){
alert(error);
}
});
return false;
});
});
Which alerts object Object as error. How to modify this ajax call and model/view/controller to get desired result? Alerts are for debugging purposes.

Related

Change button text from "Like" to "Liked" when clicked

I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.

jQuery Mobile AJAX doesn't load page

echo '<script>
function ' . $row['idname'] . 'Click(){
$( "#flip-' . $row['idname'] . '" ).flipswitch( "disable" );
var isOff = document.getElementById("flip-' . $row['idname'] . '").value;
if(isOff == "off"){
console.log("action.php?do=turn-off-' . $row["id"] . '");
jQuery.ajax({
url: "action.php?do=turn-off-' . $row["id"] . '",
type: "GET",
success:function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
}else{
console.log("action.php?do=turn-on-' . $row["id"] . '");
jQuery.ajax({
url: "action.php?do=turn-on-' . $row["id"] . ',
type: "GET",
success : function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
}
}
</script><br>';
So my problem is that ajax doesn't even load the page that is requested.
It creates this code from the result of a MySQL query, so it's basically a JavaScript file in a PHP File. The target is an empty page that only has some functions.
The function is invoked onChange from this <select>:
echo '<div class="ui-field-contain" style="width: 100%;">
<label for="flip-' . $row['idname'] . '">' . $row['name'] . '</label>
<select onchange="' . $row['idname'] . 'Click()" name="flip-' . $row['idname'] . '" id="flip-' . $row['idname'] . '" data-role="flipswitch">
<option value="off" selected="">Aus</option> <option value="on">An</option>
</select>
</div>';
This may solve the problem because it is not a nice way to just replace it with always. You might consider adding some error handling where no wrong elements are tested to be selected with the error message as a part of the id.
Deprecated jqXHR.success()
The issue may occur because this method is deprecated since jQuery 1.8. It has been replaced by jqXHR.done().
jQuery.ajax({
url: "action.php?do=turn-on-' . $row["id"] . '",
type: "GET",
done: function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
Suggesting another way
$.get("api.php", {
do: "turn-on-' . $row["id"] . '"
}, function (data) {
console.log(data);}
});

Phpmyadmin - stored routine is meant to return multiply rows in the javascript function but instead returns a single row

i have a stored routine called collection_get_category_suggestions which has the following sql
select *
from album
where category=InCategory;
This should return a list of multiple records based on a category the user chooses. When run in sql tab the result of the routine returns multiple values however when executed in the routine tab and JavaScript it will only return the first record. Here is my JavaScript function which handles sql.
function getCategorySuggestions(catid)
{
var categoryid = catid;
console.log(categoryid);
selectedcategory = categoryid;
$("#suggestionsTab").empty();
var url = "categories_xml.php?category=" + selectedcategory;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function(xml){
var album_title = $(xml).find('album_title').text();
console.log(album_title);
var artist = $(xml).find('artist').text();
var year = $(xml).find('year').text();
var imageurl = $(xml).find('imageurl').text();
var categoryinfo = "<h3>" + album_title + "</h3><p>" + artist + " (" + year + ")</p>";
//categoryinfo += "<img src='" + imageurl + "' alt='" + album_title + " Album Cover' height='200' width='200' />";
console.log(categoryinfo);
$('#suggestionsTab').append(categoryinfo);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
the console.log returns one record. Why is this? Thanks very much for any help
EDIT:
php script
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
header("Content-type: text/xml");
$response='<?xml version = "1.0" ?><albums>';
if (isset($_GET['category']))
{
$obj = Collection::GetCategorySuggestions($_GET['category']);
$album_title=$obj['album_title'];
$artist=$obj['artist'];
$category=$obj['category'];
$year=$obj['release_date'];
$imageurl="./images/" . $obj['image'];
$response .= '<album><album_title>' . htmlentities($album_title, ENT_QUOTES) . '</album_title>';
$response .= '<artist>' . htmlentities($artist, ENT_QUOTES) . '</artist>';
$response .= '<category>' . htmlentities($category, ENT_QUOTES) . '</category>';
$response .= '<year>' . $year . '</year>';
$response .= '<imageurl>' . htmlentities($imageurl, ENT_QUOTES) . '</imageurl></album>';
}
$response .= '</albums>';
echo $response;
?>
i should add that the collection.php function is
public static function GetCategorySuggestions($category)
{
// Build SQL query
$sql = 'CALL collection_get_category_suggestions (:category)';
// Build the parameters array
$params = array (':category' => $category);
// Execute the query and return the results
return DatabaseHandler::GetRow($sql, $params);
}
foreach loop
foreach($albumsarray as $album)
{
$album_id=$album['album_id'];
$album_title=$album['album_title'];
$artist=$album['artist'];
$response .= '<album><album_id>' . $album_id . '</album_id><album_title>' . htmlentities($album_title, ENT_QUOTES) . '</album_title><artist>' . htmlentities($artist, ENT_QUOTES) . '</artist></album>';
}

Executing javascript in an an AJAX response - Codeigniter

I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>

Retrieving data from PHP using AJAX to send to different PHP file

Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!
I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.
Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php
You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']

Categories

Resources