jquery click event not firing after ajax event - javascript

I am having trouble getting my button to click after an ajax call. It works fine before the call. However, when i perform a search and return the data from php, the click event stops working.
I have tried the .on event but this just display the form and not the values. I would be grateful if someone could check my code and see where I am going wrong.
I am aware that the element needs to be in the page and I assumed that after he ajax call the dom would contain the element. Obvously i was wrong.
Many thanks
Order of clicks.
1) page load, .edit click works fine.
2) perform search from #btn-search. Pagintes the table but .edit click is no longer firing.
js code
Get inital values from row. works fine on first click. Not after ajax call to display search results
$(function() {
$('.edit').click(function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
service = currentRow.find("td:eq(1)").html();
activity = currentRow.find("td:eq(2)").html();
dept = currentRow.find("td:eq(3)").html();
company = currentRow.find("td:eq(4)").html();
address = currentRow.find("td:eq(5)").html();
user = currentRow.find("td:eq(6)").html();
item = currentRow.find("td:eq(7)").html();
date = currentRow.find("td:eq(8)").html();
var data = id + "\n" + service + "\n" + activity + "\n" + dept + "\n" + company + "\n" + address + "\n" + user + "\n" + item + "\n" + date;
$("#editForm").dialog("open");
$("#id").val(id);
$("#service").val(service);
$("#activity").val(activity);
$("#dept").val(dept);
$("#company").val(company);
$("#address").val(address);
$("#user").val(user);
$("#item").val(item);
$("#datetimepicker").val(date);
});
});
php backend
<?php
if ($_POST['search1'] == '') {
echo 'enter a search term';
exit;
} else {
$search = $_POST['search1'];
$sqlsrch = mysqli_query($conn, "select * from act where item like '%$search%'");
$numsrch = mysqli_num_rows($sqlsrch);
if ($numsrch == 0) {
// what to do if no results found
echo 'No Results Found';
} else {
while ($rowsrch = mysqli_fetch_array($sqlsrch)) {
$id = $rowsrch['id'];
$service = $rowsrch['service'];
$activity = $rowsrch['activity'];
$dept = $rowsrch['department'];
$company = $rowsrch['company'];
$address = $rowsrch['address'];
$user = $rowsrch['user'];
$box = $rowsrch['item'];
$date = $rowsrch['date'];
$date = date('d/m/Y h:i:s', strtotime($date));
$edit = "<button type='button' class='btn btn-primary edit'>Edit</button>";
$action = "<button type='button' class='btn btn-success action'>Action</button>";
$delete = "<button type='button' class='btn btn-danger delete'>Delete</button>";
// Now for each looped row
echo "<tr><td>" . $id . "</td><td>" . $service . "</td><td>" . $activity . "</td><td>" . $dept . "</td><td>" . $company . "</td><td>" . $address . "</td><td>" . $user . "</td><td>" . $box . "</td><td>" . $date . "</td><td>" . $edit . ' ' . $action . ' ' . $delete . "</td></tr>";
} // End our scale while loop
}
}
?>
jquery search click event
$(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
var search = $("#search").val();
$.ajax({
url: "tabletestajax.php",
method: 'POST',
data: {
search1: search
},
success: function(data) {
$("#search").val('');
$(".paginated tbody").empty();
var result = $.trim(data);
if (result === "enter a search term") {
$("input[name='search']").val(result).css({
'color': 'red'
});
return false;
} else if (result === "No Results Found") {
$(".paginated tbody").html('<div>' + result + '</div>');
return false;
} else {
$(".paginated tbody").html(result);
}
}
});
});
});

Probably you need event delegation
$(document).on('click', '.edit', function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
.
.
}
Resource
Event delegation .on()

Related

How to change database values with dynamically created buttons in PHP

I am dynamically creating html content with PHP and I am creating a button and when that button is clicked It should invoke a PHP script that will update the values of a column of a specific row in the database
Here is my code:
<?php
session_start();
if(!isset($_SESSION['id'])){
header("Location: login.php");
}else{
require_once("mysqli_connect.php");
$query = "SELECT * FROM markeri WHERE odobreno ='F'";
$response = #mysqli_query($dbc,$query);
if($response){
echo "<hr>";
while($row = mysqli_fetch_assoc($response)){
echo "<div align='center' id='markeri'><h3>Naziv: " . $row['naziv'] . "</h3>";
echo "<h3>Ulica: " . $row['ulica'] . "</h3>";
echo "<h3>Opis:</h3>" . "<p>" . $row['opis'] . "</p>";
echo "<h4>Email: " . $row['email'] . "</h4>";
echo "<img src='" . $row['link_slike'] . "' width='300px' /></br>";
echo "<form action='update.php' method='POST'>";
echo "<textarea rows='10' cols='30' maxlength='500' placeholder='Komentar' name='" . $row['marker_id'] . "'></textarea></br>";
echo "<input type='button' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
}
}
}
?>
I tried something like making the name of the textarea equal to the marker_id in my database and making the name of the button the value of marker_id + the string "b" but I don't know how to call them on my update.php script. Usually when it is a normal case and when there is no dynamic content I know how to do it with $_POST['name'];
EDIT:
I used AJAX to dynamically create the HTML as you told me but I've encountered another problem
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'><a href='odobri_prijavu.php?id=" + m.marker_id + "'>Odobri</a>" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>IzbriĆĄi</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
</script>
I tried to use buttons but I couldn't figure how to add event handlers to dynamically created buttons that will post a request via AJAX to some php script with the proper id as the value and the value of the textarea. So I used the anchor tag and I was able to send the id, but I can't send the value of the textarea because I don't know how to reference it and even if I referenced it, it will be NULL because its value is set to the anchor tag at the very beginning and I want to type in text in the textarea.
try this
$(".btn_class_nm").click(function(){
$.ajax({
type: "POST",
url: "http://domain.com/phpscript_filenm.php",
data: {
val1:"val1",
val2:"val1",
},
success: function(msg){
alert( "record updated"); //Anything you want
}
});
});
First of all give a Class Name to the Button as it is being generated dynamically and the number of them can vary based on the number of records the query returns. Something like this:-
echo "<input type='button' class='btn btn-primary btn-xs btn-block active view_data' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
Note that I have add view_data in the class definition. This will help is trapping the onclick event through jquery.
the jquery will be something like
$('.view_data').click(function(){
var yourvariable = JSON.stringify($(this).val()); //Gets Clicked button value
$.ajax({
url:"workstatus.php",
method:"post",
data:{yourvariable:yourvariable, anymoreyourvariables:anymoreyourvariables, , },
success:function(data){
$('#htmldivID').html(data);//If you want result there.
alert( "record updated"); //Anything you want
}
});
I hope this helps you.

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

InnerHTML creation issue, doesn't load in the correct order, possible processing issue

I am using a series of JavaScript functions to load information from a database and use the information in the creation of a thumbnail image and a radio button corresponding to each 'comic' record that the user has theoretically created and uploaded to the database.
My problem arises when the HTML tags are created. While the image and button are both created correctly with no errors, they are outputted in the wrong order. They should be loaded alphabetically by 'comicName', which is represented in the radio button's text, for example:
Comic A (img)
Comic B (img)
Comic C (img)
I have checked the array 'arr' of 'comicID's that determine the order of outputted html objects at several stages in the code using window alerts, and at all stages the comics are ordered correctly in the array, even when outputting incorrectly. There is an odd circumstance when I have quite a lot of alerts opening up at once; the items DO in fact output in the correct order. (In this case there were around six 'comicID's in the array and each ID had an alert pop up for it at three different times).
I therefore think that the code is creating them in the correct order and trying to output them as such, but some items may be loading sooner than others due to image size or some other processing reason. If this is indeed the case how would I go about sorting it to make sure they load correctly?
Thanks in advance.
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
document.getElementById("uploadTagID").innerHTML="";
document.getElementById("uploadTagID").innerHTML="No Comics Uploaded";
document.getElementById("btnDeleteComic").disabled=true;
document.getElementById("btnEditComic").disabled=true;
document.getElementById("btnDelAllComics").disabled=true;
$("#listButtons").hide();
}
else
{
document.getElementById("loadList").innerHTML="<br>";
for(i = 0; i < arr.length; i++)
{
tempID = (arr[i].comicID);
getCoverJSON(arr, i, tempID);
}
document.getElementById("uploadTagID").innerHTML="";
document.getElementById("uploadTagID").innerHTML="<u>Uploaded Comics</u>";
document.getElementById("btnDeleteComic").disabled=false;
document.getElementById("btnEditComic").disabled=false;
document.getElementById("btnDelAllComics").disabled=false;
$("#listButtons").show();
}
}
</script>
<script>
// Function to prevent $.get from technically being inside a loop (fixes an issue when loading more than one item).
function getCoverJSON(arr, i, tempID)
{
$.get("getCover.php", {'comicID': tempID}, function(result)
{
getCover(result, arr, i);
}
);
}
</script>
<script>
// Function to create a list of radio buttons and associated images from a user's comic list.
function getCover(result, arr, i)
{
var buildLine = document.getElementById("loadList").innerHTML;
if (result[0].pageLocation == "nocvr")
{
var out = "<hr><br><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='assets/img/nocvr.jpg'><br><br>";
document.getElementById("loadList").innerHTML="";
document.getElementById("loadList").innerHTML=(buildLine + out);
}
else
{
var getImg = result[0].pageLocation;
var out = "<hr><br><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + getImg + "'><br><br>";
document.getElementById("loadList").innerHTML="";
document.getElementById("loadList").innerHTML=(buildLine + out);
}
}
</script>
PHP (loadCom.php):
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$user = $_GET['userID'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE userID = '$user' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[")
{
$outp .= ",";
}
$outp .= '{"comicID":"' . $rs["comicID"] . '",';
$outp .= '"comicName":"' . $rs["comicName"] . '"}';
}
$outp .="]";
$conn->close();
echo ($outp);
?>
PHP (getCover.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if (isset($_GET["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_GET["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0)
{
$outp = '[{"pageLocation":"nocvr"}]';
echo ($outp);
}
else
{
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[")
{
$outp .= ",";
}
$outp .= '{"pageLocation":"' . $rs["pageLocation"] . '"}';
}
$outp .="]";
$conn->close();
echo ($outp);
}
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
You're using AJAX calls, which are by default asynchronous - there is NO guarantee whatsoever as to what order the responses come back in. e.g. if you have requests A,B,C, then the response to A might come 20 minutes after the C response, because someone's backhoe severed an optic cable somewhere and caused the A request to take a much longer path to the server than C's.
You can switch to synchronous, but that will lock the browser while the requests are pending, which is a bad user experience.
You'd be better off simplifying the code. Instead of doing one ajax call per fetch, you should have ONE call, and send over all of the ids you want to fetch.
In other words, instead of
$.get('getCover.php', {id:1});
$.get('getCover.php', {id:2});
$.get('getCover.php', {id:3});
switch your code over to
$.get('getCover.php', {ids:[1,2,3]});
Now it's one single ajax request, one single json response, and within that response, you can order your data however you want.

PHP auto-fill selectbox through URL

I have a question I can't figure out.
<?php
$killtheboy = 0;
if($killtheboy == 1){
echo "<input type=\"text\" name=\"dwanummer\" id=\"dwanummer\">";
}else{
echo "<div id=\"dropdowndwa\">
<select name=\"dwanummer\" id=\"dwanummer\" class=\"dwanummer\">
<option selected=\"selected\">Kies uit lijst</option>";
include("config/instellingen.php");
$query = "SELECT DISTINCT `Klantvraag`,`Wensweek` FROM `DWA` WHERE `Status DWA` = 'DBAA' OR `Status DWA` = 'DBAP' OR `Status DWA` = 'DIUI' ORDER BY wensweek - '$wensweekber' ASC";
if ($result = mysqli_query($connect, $query)) {
while ($get = mysqli_fetch_assoc($result)) {
$week = date('W', strtotime("this week"));
$jaar = date('Y', strtotime("this week"));
$wens = ''. $jaar . ''. $week. '';
$wensweek = $get['Wensweek'];
$wensweekber = $wensweek - $wens;
echo '<div class="selectBlock"><option value="' . $get['Klantvraag'] . '" name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option></div>';
}
}
echo "</select></div><br />";
}
?>
The above code (PHP) fetches a list of numbers on pageload and I have to select one in order to fetch that information through JS.
<script type="text/javascript">
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax
({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
}
});
});
});
</script>
Basically I have a search system and u can find all 'cases' there and if you see one you want then you click it it goes to the above page with code and it auto selects that ID instead of still having to select it. (like additem.php?id=125533 or something)
Can someone please explain me how I can solve this.
Can you try this, You need to use selected attribute in select element
$Selected ='';
if(isset($_GET['id']) && ($get['Klantvraag'] == $_GET['id'])){
$Selected =" selected='selected' ";
}
echo '<option value="' . $get['Klantvraag'] . '" '.$Selected.' name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option>';
Javascript:
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
Populate();
});
Populate();
});
function Populate(){
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
removeAllNameSelectBoxes();
var selected = $("#dropdowndwa option:selected").map(function (i, el) {
return el.value;
}).get();
getNamesFromSelectIds(selected);
}
});
}

Can jQuery/JS check what changed the input?

can jQuery or plain JavaScript check how the value of input field was changed? Maybe something similar to that:
$('input').change(function(e){
e.preventDefault();
console.log(e.changedFunction.name);
});
I know given code doesn't work and doesn't do what I want. But is this even possible somehow?
Why do I need that? I have a dialog box where I have multiple forms (each form changes one thing). When I submit form, the value resets back to value which was there previously. e.g. In the form there's a word 'Hello', when I change it to 'Hello, World!', it successfully sends the data to $.post, but then resets the value to 'Hello'. I can't seem to find any function, neither php, nor javascript that changes the input. That's why I need to check what or who changes my input value back.
EDIT:
Including sample code.
editblock.php
} else if ($_POST['what'] == 'email') {
$sql = mysql_query("SELECT id, email, loggedin FROM users WHERE id = " . mres($_POST['id']) . " LIMIT 1");
$edit = mysql_fetch_array($sql);
$output .= '<div id="block-' . $_POST['what'] . '"><form method="post" id="form-' . $_POST['what'] . '">';
$output .= '<input type="hidden" name="id" value="' . mres($_POST['id']) .'" />';
$output .= '<input type="text" name="value" value="' . $edit['email'] .'" /> ';
$output .= '<input type="hidden" name="what" value="' . mres($_POST['what']) .'" />';
$output .= '<input type="submit" name="submit" value="OK" />';
$output .= '</form></div>';
$output .= '<script>
$("#form-' . $_POST['what'] . '").submit(function(event) {
event.preventDefault();
var $form = $( this ),
doval = $form.find( "input[name=\"value\"]" ).val(),
doid = $form.find( "input[name=\"id\"]" ).val(),
dowhat = $form.find( "input[name=\"what\"]" ).val();
$.post("/pages/profilis/doedit.php", { do: doval, id: doid, what: dowhat },
function( data ) {
$("#block-' . $_POST['what'] . '").empty().append( data );
$form.find("input[name=\"value\"]").val(doval);
}
);
});
</script>
';
}
doedit.php
else if ($_POST['what'] == 'email') {
if (empty($_POST['do'])) {
$error[] = 'err';
} else {
if ( ! preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['do'])) {
$error[] = "err";
}
$sql = mysql_query("SELECT `id` FROM `users` WHERE `email` = '" . mres($_POST['do']) . "' LIMIT 1");
if (mysql_num_rows($sql) == 1) {
$error[] = "err";
}
if ($edit['loggedin'] > 0) {
$error[] = "err";
}
if (sizeof($error) >= 1) {
echo join($error, '<br/>');
} else {
$sql = mysql_query("UPDATE users SET
email = '" . mres($_POST['do']) . "'
WHERE id = " .(int)$edit['id'] . "
LIMIT 1");
if ($sql) {
echo 'OK';
$logmsg = 'Changed email';
} else {
echo 'Error';
}
}
}
}
PHP function mres() escapes all the characters (for database injection protection - not really important here).
According to the situation which you explained. I would prefer you to use jqueryajax
in this Once the Post function is done you can change the value with the changed value
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg ); // portion where you can change the field value to the updated one.
});
Thanks and Regards,
Philemon Philip Kunjumon

Categories

Resources