Jquery function not working properly with php loop - javascript

I am working with jQuery and PHP. I am using AJAX in the controller and I am getting "Feeds" (Posts) in a PHP loop.
The issue is that whenever I click on any button in that loop it shows me the alert multiple times instead of one time. How can I solve this?
Right now I just alert a simple message for the test but the alert box shows more than 1 time after a single click. I just want that it should alert only one time so I can write/execute my function further.
Thank you in advance.
<?php
function fetch()
{
$FeedId;
(dynamic) $FeedData = $this
->M_main
->GetFeedData(); // getting feed data from database
foreach ($FeedData as $feeds)
{
if ($feeds['flag'] == "feed")
{
$GetFeedComments = $this
->M_main
->GetFeedsComment($FeedId);
$TotalFeedsComments = $GetFeedComments['TotalRows'];
if ($TotalFeedsComments > 1)
{
$Loads = '<div class="show_more_main" id="show_more_main' . $postID . '">
<input type="hidden" name="fixs" value="' . $postID . '" id="fixs">
<input type="hidden" name="MinValue" value="' . $postID . '" id="MinValue">
<input type="hidden" name="MaxValue" value="' . $postID . '" id="MaxValue">
<span id=' . $postID . ' data-val=' . $postID . ' data-status=' . $postID . ' class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>';
}
else
{
$Loads = "";
}
}
}
$paths = base_url() . "Main/AddComments";
echo "<script>
$('.show_more').click(function (e) {
e.preventDefault();
alert("Helloworld");
});
</script>";
}
?>

Related

How to view a pop up box with jquery for many data?

My question, before I go further with how I did it, is: How can I make this work, and make it easier and better than what I have done?
I have a database with a lot of data, and I am viewing all these in a table. Each <td> has a <div title=""> included, so that all who mouseover each <td> can see more information about that data item. The trouble is, that it's only viewable as a table on mobile devices. To create a hyperlink for a new page is difficult, because that takes the user away from a <table> with comparrision to just that one data information. So I was thinking to use jQuery UI. And was reading a little over the "Basic Dialog" option. I tried to put that into my script, but I see I have way too much data. So I created a file called jq_scripts.php. In there I have a script to create dialog options. But first I include it like this in the header:
<script src=\"//code.jquery.com/jquery-1.10.2.js\"></script>
<script src=\"//code.jquery.com/ui/1.11.4/jquery-ui.js\"></script>
<script src=\"jq_scripts.php\" type=\"text/javascript\"></script>
Then in the script I have put this as a standard:
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
});
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});
But since I have so many different dialogs, I need one #id to each button with unique information, so this is what I have as a script:
echo "\$(function() {\n";
$result = mysqli_query($con, "SELECT * FROM $database WHERE type = 1");
$num = mysqli_num_rows($result);
if(!$result) {
die('Invalid query: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
foreach($abo as $abo_vis) {
$abo_vis = strtolower(str_replace(' ', '', $abo_vis));
echo " \$( \"#dialog_" . $abo_vis . "_" . $id . "\" ).dialog({\n";
echo " autoOpen: false,\n";
echo " });\n\n";
echo " \$( \"#opener_" . $abo_vis . "_" . $id . "\" ).click(function() {\n";
echo " \$( \"#dialog_" . $abo_vis . "_" . $id . "\" ).dialog( \"open\" );\n";
echo " });\n\n";
}
}
echo "});\n";
This creates a viewing file with 12583 lines!!!
In a <td> I have put this _DATA_ and in the bottom of the viewing file, I have created this:
echo "<div id=\"dialog_" . $abo_vis . "_" . $id . "\" title=\"" . $abo_vis . "\">\n";
echo "<p>" . $dialog_info[$id] . "</p></div>\n\n";
This creates this file to be a lot longer than needed. And on top of that, none of my <a href="#"> works. Actually, the <div id="dialog..."> actually shows, while on the demo it was hidden.
Maybe your problem is the way you are calling it, instead of using IDs use classes:
echo "<div class=\"dialog_" . $abo_vis . "_" . $id . "\" title=\"" . $abo_vis . "\">\n";

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

Output from database use toggle to edit data

I have a database with some record which i output on my page using php. This all works fine but i want to be able to edit the outputted information using the toggle functionality. So basicly i output text when a button edit is clicked i want to toggle that specific table and show the information once more but then in an input form.
foreach( $result as $row2 )
$div = $row2['id'] ;
echo "<div id='d$div; '><table ><tr><td>" . 'Categorie: ' . '</td><td> ' . $row2['name'] . '</td></tr>'
. '<tr><td>' . 'Omschrijving: ' . '</td><td>' . $row2['comments'] . '</td></tr> . '<tr><td>' . '<button id="e1">' . 'Edit' . '</button>' . '</td></tr>' . ' </table><hr>'; } ?></p>
If I would then would then echo everything out again using <form> input fields and use as div id f$div every record would get its unique id.
foreach( $result as $row2 )
$di = $row2['id'] ;
echo "<div id='f$di; '><table ><tr><td>" . 'Categorie: ' . '</td><td> ' . $row2['name'] . '</td></tr>'
. '<tr><td>' . 'Omschrijving: ' . '</td><td>' . $row2['comments'] . '</td></tr> . '<tr><td>' . '<button id="e2">' . 'Safe' . '</button>' . '</td></tr>' . ' </table><hr>'; } ?></p>
Then I would toggle it but I don't have the ids as they still have to be generated. How would I go about this...same would go for the click function but I can generate an id for these in the same way.
<script>
$('#e1,#e2').click(function () {
$('#d?,#f?').toggle();
})
</script>
You can do this with javascript, too. This is one example. You can even use AJAX to update, otherwise you can update the data in database and come back to the same page.
<?php
foreach($result as $row2) {
$div = $row2['id'];
echo "<div id='d$div'><table ><tr><td>" . "Categorie: " . "</td><td> " . $row2["name"] . "</td></tr>" . "<tr><td>" . "Omschrijving: " . "</td><td>" . $row2["comments"] . "</td></tr>" . "<tr><td>" . "<button id=e$div onclick='makeForm(\"$div\",\"d$div\",\"$row2[name]\",\"$row2[comments]\")';>" . "Edit" . "</button>" . "</td></tr>" . "</table><hr></div>\n";
}
?>
<script>
function makeForm(id,mydiv,category,comment){
var div = document.getElementById(mydiv);
var divHTML = "<form action='update.php' method='POST'><table> <tr><td>Categorie: </td> <td><input type='text' name='cat_" +id+ "' value='"+category + "' /></td></tr> <tr> <td>Omschrijving:</td> <td><input type='text' name='comment_" +id+ "' value='"+comment+"' /></td></tr> <tr><td> <input type='submit' value='Safe'></td><td><button onclick='removeForm(\""+id+"\",\""+mydiv+"\",\""+category +"\",\" "+comment+"\" ); return false;'>Cancel</button></td></tr></table> </form><hr>";
div.innerHTML = divHTML;
}
function removeForm(id,mydiv,category,comment){
var div = document.getElementById(mydiv);
var divHTML = "<table> <tr><td>Categorie: </td> <td>"+category + "</td></tr> <tr> <td>Omschrijving:</td> <td>"+comment+"</td></tr> <tr><td><button onclick='makeForm(\""+id+"\",\""+mydiv+"\",\""+category +"\",\" "+comment+"\" ); '>Edit</button></td></tr></table><hr>";
div.innerHTML = divHTML;
}
</script>
Hope this helps...

Iterating over different divs in Javascript and passing arguments to a script

Background
I am using PHP to created a list of voting sections. Each section is the same except for a unique number, which increases by 1 each time the PHP loops.
I use the PHP variable $n as a counter, and place that in the id attributes in several places in each section.
Current PHP/HTML:
echo "<div id='votesection'>";
echo "<h3 id='rating " . $n . "' style='display:block;'>" .
echo "<h3 id='ratingup " . $n . "' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 id='ratingdown " . $n . "' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote($n)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote($n)'></div>";
echo "</div>";
Goal
When a user clicks on an arrow down or arrow up, certain divs are hidden or displayed. Example, when the up arrow in my second section is clicked, my <h3 id='ratingup2'></h3> would change to visible.
Current JS
function upvote() {
// Script to hide rating, and rating down and display:block ratingup
// Will also need to execture php sql query to increment event rating by one for event by one
}
function downvote(){
// Same script but to show rating down and decrement rating
}
Should I pass every rating id to the script or is there an easier way to do this that I'm missing?
Passing the ID is the easiest way to do it with plain Javascript.
function upvote(n) {
document.getElementById('ratingup ' + n).style.display="block";
document.getElementById('ratingdown ' + n).style.display="none";
}
function downvote(n) {
document.getElementById('ratingup ' + n).style.display="none";
document.getElementById('ratingdown ' + n).style.display="block";
}
A way to do it without passing the ID would be to put classes on the rating DIVs, and pass this instead.
HTML:
echo "<div id='votesection'>";
echo "<h3 id='rating " . $n . "' style='display:block;'>" .
echo "<h3 class='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 class='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote(this)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote(this)'></div>";
JS:
function upvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "block";
parent.querySelector(".ratingdown").style.display = "none";
}
function downvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "none";
parent.querySelector(".ratingdown").style.display = "block";
}
You can create only one wrapper with the id votesection_id and then do everything else with js/ajax
echo "<div id='votesection_" . $n . "'>";
echo "<h3 id='rating' style='display:block;'>" .
echo "<h3 id='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 id='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote($n)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote($n)'></div>";
echo "</div>";
<script>
function upvote(id){
// 1. Go To the server with ajax do your stuff 2. return the current upvotes 3.replace the upvotes h3 text
}
function downvote(id){
// 1. Go To the server with ajax do your stuff 2. return the current downvotes 3.replace the downvotes h3 text
}
</script>
As #idioteque says in their comment, spaces in element IDs are not allowed. The best way to get this information into the document is probably with data attributes.
Also, multiple elements with the same id are not allowed, what you probably need in this case are classes. (I'm assuming this chunk of HTML will be repeated multiple times per page.)
Borrowing #Barmar's idea of passing this into the event handler, here's how I'd change the server code:
echo "<div class='votesection' data-rating-id=" . $n . ">";
echo "<h3 class='rating' style='display:block;'>" .
echo "<h3 class='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 class='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote(this)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote(this)'></div>";
echo "</div>";
And the JS:
function upvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "block";
parent.querySelector(".ratingdown").style.display = "none";
var id = parent.dataset.ratingId;
// do your AJAX or whatever with id
}
function downvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "none";
parent.querySelector(".ratingdown").style.display = "block";
var id = parent.dataset.ratingId;
// do your AJAX or whatever with id
}

Php ajax sort data based on user selected input

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.

Categories

Resources