I have a table that will display images stored in a DB as well as some other information. I have a column that has a link that the user can click to delete the image, this works fine however when the user does this I also want to remove the row that the user selects to remove but I can't seem to get it to work.
function removeSectionPhoto(image, section_id) {
if(confirm("Are you sure you want to delete this image?") == true) {
$.ajax({
type: "POST",
url: "remove_section_photo.php",
data: 'image='+image+'§ionID='+section_id,
success: function(data){
//this is supposed to remove the row but currently doesnt work
$("#"+$(this).data("remove-row")).remove();
}
});
}
}
The table rows are being output from PHP, this is what one of the table rows looks like:
echo "<tr id='fac_sec_photo_row". $imageRowCount ."'>";
echo "<td><a><img class='section_photo' src='" . $sectionPhotoRow['photo'] . "' alt='Section Photos' height='50' width='50'</a></td>";
echo "<td><input type='text' id='photoDesc' name='photoDesc[]' value='" . $sectionPhotoRow['photo_desc'] . "'</td>";
echo "<td><input type='file' id='new_section_photo' name='new_section_photo[]' onchange='displaySecImage(this)'></td>";
echo "<td><a href='#' class='removeImageRow' data-remove-row='fac_sec_photo_row". $imageRowCount . "' onClick='removeSectionPhoto(\"". $sectionPhotoRow['photo'] ."\", \"". $facilitySecId ."\")'>Remove</a></td>";
echo "</tr>";
What am I doing wrong, how can I remove the selected table row?
All right. I see part of the issue. You are mixing vanilla javascript with jquery. Jquery does a LOT behind the scenes that hides what javascript doesn't do. Since you are using a vanilla onclick inline on the element, this will likely refer to window, not the element that is being clicked on (I know, confusing). Jquery uses the function.prototype.apply method to re-map this to the target element. Javascript doesn't. But all is not lost, and there is an easy fix. The easiest of which is to just pass in $imageRowCount to your function as well. Then you can simply reference the id directly.
function removeSectionPhoto(image, section_id, row_id) {
if(confirm("Are you sure you want to delete this image?") == true) {
$.ajax({
type: "POST",
url: "remove_section_photo.php",
data: 'image='+image+'§ionID='+section_id,
success: function(data){
//this is supposed to remove the row but currently doesnt work
$("#"+row_id).remove();
}
});
}
}
And then:
echo "<td><a href='#' class='removeImageRow' onClick='removeSectionPhoto(\"{$sectionPhotoRow['photo']}\", \"{$facilitySecId}\", \"fac_sec_photo_row{$imageRowCount}\")'>Remove</a></td>";
Another option would be to pass in this to the function call in the onclick='removeSectionPhoto(this, ...etc...)' which would give your first argument (or whatever argument number you pass it in) a reference to that variable. Then $(ele).closest('tr').remove() would work.
Really though, you shouldn't mix vanilla js with jquery. Just use jquery to query for the elements and use it's event handlers and this wouldn't have been an issue (well, you still need to map this to self).
pass the $imageRowCount as a third argument into the function and then remove the row that way
echo "<td><a href='#' class='removeImageRow' data-remove-row='fac_sec_photo_row". $imageRowCount . "' onClick='removeSectionPhoto(\"". $sectionPhotoRow['photo'] ."\", \"". $facilitySecId ."\", \"". $imageRowCount ."\")'>Remove</a></td>";
function removeSectionPhoto(image, section_id,imageRowCount ) {
if(confirm("Are you sure you want to delete this image?") == true) {
$.ajax({
type: "POST",
url: "remove_section_photo.php",
data: 'image='+image+'§ionID='+section_id,
success: function(data){
//this is supposed to remove the row but currently doesnt work
$("#fac_sec_photo_row"+imageRowCount).remove();
}
});
}
}
Related
I have list of table which displays users information. There will be an amend link at the top. I need to update the form through Ajax rather than moving on to another page to update it.
This is my code.
<?php while ($row = mysql_fetch_assoc($displayer)){
echo("<tr><td>First Name</td><td>" . $row['first_name'] . "</td> </tr>");
echo("<tr><td>Last Name</td><td>" . $row['last_name'] . "</td> </tr>");
echo("<tr><td>Email</td><td>" . $row['email'] . "</td> </tr>");
echo("<tr><td>Country</td><td>" . $row['country'] . "</td> </tr>");
echo "<a class='page' href='amend.php?id=" .urlencode($row['users_id']) . "&firstname=" .urlencode($row['first_name']) . "&lastname=".urlencode($row['last_name']) ."'>Amend Record</a></td></tr>";
?>
Could any one tell me how to update the form using Ajax on the same page itself.
much details go into these that would require a very lengthy answer...nonetheless I am going to stress some important starting points.
First you need a JS file with a handler about the link.
When the link is clicked a ajax request must be made...there are various way to do that but I personally use jquery's $.ajax....inside the request you must gather the variables that reflect the values of the form inputs....then you send these values to a PHP script that makes validation and if this is successful update the corresponding values in the database.Inside the request you must also specify the URL that the this script resides.
This ajax request though is comprised of 2 important callbacks...error and success...in them you must write code that will deal with the situation if the request succeeds or not....for example you update he values in form when you are certain that this has indeed happen in the database and you can a make check for that in the PHP script...whatever values the PHP script echoes back must be done with json_encode...and you can access these values with the data argument of the success callback.AS I said there is an error callback also..this is triggered by various causes...it the URL is wrong or JSON is not returned from the server.
These above are just starting points...I am laying out a general approach.
/* AJAX using jQuery */
// attach event to your <a> upon click
$(document).on('click','a.page', function(e) {
e.preventDefault()
var sURL = $(this).attr("href"); // url to call for amend
update( sURL ) // call the function update
});
// update() function that is called after clicking anchor tag
function update( _url )
{
$.ajax({
method: 'POST',
url: _url,
success: function() {
alert("Amend Success)";
},
error: function( c ) {
alert("Internal server error. Check your browser console");
console.log( c.responseText )
}
})
}
NOTE: Put this before </body> tag
So this stems from a problem yesterday that quickly spiraled out of control as the errors were unusual. This problem still exists but the question was put on hold, here, and I was asked to reform a new question that now relates to the current problem. So here we go.
The problem is basic in nature. If you were helping yesterday I have switched from a $.post to an $.ajax post to deliver a variable to my PHP file. However my PHP file seems to never receive this variable stating that the index is 'undefined'.
Now this would normally mean that the variable holds no value, is named incorrectly, or was sent incorrectly. Well after a full day of messing with this (kill me) I still see no reason my PHP file should not be receiving this data. As I'm fairly new to this I'm really hoping someone can spot an obvious error or reccommend another possible solution.
Here's the code
jQuery
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: {'aid' : aid},
done: function(data) {
// this is for testing
}
}).fail (function() {
alert('error');
}).always(function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
PHP
<?php
include "$_SERVER[DOCUMENT_ROOT]/TrakFlex/core/init.php";
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
try {
$query_projectInfo = $db->prepare("
SELECT projects.account_id,
projects.project_name,
projects.pm,
//..irrelevant code
FROM projects
WHERE account_id = ?
");
$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);
$query_projectInfo->execute();
$count = $query_projectInfo->rowCount();
if ($count > 0) {
echo "<table class='contentTable'>";
echo "<th class='content_th'>" . "Job #" . "</th>";
echo "<th class='content_th'>" . "Project Name" . "</th>";
//..irrelevant code
while ($row = $query_projectInfo->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td class='content_td'>" . "<a href='#'>" . $row['account_id'] . "</a>" . "</td>";
echo "<td class='content_td'>" . $row['project_name'] . "</td>";
//..irrelevant code
echo "</tr>";
}
echo "</table>";
}
} catch(PDOException $e) {
die($e->getMessage());
}
} else {
echo 'could not load projects table';
}
?>
When I run this code by pressing '#projects' I get 2 alerts. This first alert says '6', which is the value of the variable 'aid' and is expected. The second alert is blank.
Now here is where I get confused. If the post is being sent with a value of 6. Isn't the $_POST['aid'] set? Also if that's true shouldn't my code execute the if portion of my conditional statement rather than my else?. Either way this strikes me as odd. Shouldn't I receive something back from my PHP file?
So in Firebug we trust, right? If I open up Firebug and go through like this
Firebug -> POST projects.php -> XHR -> POST(tab) ->
I see 6 in the 'Parameter' window and '6' in the 'Source' window. Then if I click the 'Response' and 'HTML' tabs they both hold no value.
So anyways, that wall of text is my problem. Again, I'm really hoping someone can help me out here. I would hate to waste anymore time on what should be a simple solution.
EDIT
If I change my php file to look like this
<?php
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
The response is now '6'! Hooray! We made a breakthrough! Now why won't it load my table that results from my query?
side note
This should of been noted originally if I take away the
if(isset($_POST['aid'])){
//all my code
} else {
//response
}
and just hard code the variable $aid like this
$aid = '6';
Then run the PHP file directly the query is successful and the page loads the table its dynamically creating.
Also in response to one of the answers asking me to use
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: aid,
success: function(data) {
// this is for testing
}
}).error (function() {
alert('error');
}).complete (function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
I was using that, but I'm using jQuery v1.10.2 and according to this those methods are or will be deprecated. Either way it made 0 difference in the outcome.
Anyways the question is now. Why is it if I used the simple version I get echo'd back my $aid variable of '6'. However when I try and run my query with it I get nothing. Also please try to remember if I hard code the 6, the table creates.
I think this may be the error:
data: aid,
it should be
data: {'aid':aid},
That will provide the $_POST['aid'] label and value you're looking for in your php page.
EDIT:
If you're having trouble with this, I'd simplify it for testing, the main reasons for things like this not working in my experience are:
it's not reaching the file
it's reaching the file but the file's expecting something different than it's receiving and due to control structures it's not returning anything
it's reaching the file with the correct data, but there are other errors in the php file that are preventing it from ever returning it.
You can easily rule out each of these in your case.
The jQuery data parameter to the ajax method should be an object, such as {'aid': aid}. I think that's your problem. I also noticed your always method is missing a parameter for data.
If you're now posting the data correctly could the problem be in your PHP page?
The init.php include couldn't be changing the value of $_POST['aid'] could it?
I'm not sure done is suppose to behave like that, normally you use done like this:
$.ajax({
//...
})
.done(function(data){
//...
});
Just do it like this:
var fetch = true;
var url = 'someurl.php';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'aid' : aid
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
}
},
complete : function(data)
{
// do something, not critical.
}
});
You can add the failure part in if you want. This is, anyway, guaranteed to work. I'm just not familiar enough with done to make more comments about it.
Try
include "{$_SERVER['DOCUMENT_ROOT']}/TrakFlex/core/init.php";
instead cause $_SERVER[DOCUMENT_ROOT] witout bracket won't work. When you are using an array in a string, you need those brackets.
Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Refer below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});
This is a tough one to explain...
I'm developing a restaurant system where the user add the dishes available to sell, but the user has to have an option to edit/delete AFTER the dish was registered.
So what i thought was: k, gonna make a table fetching the data from the DB and in the last column put some options like edit/delete... Here is the code for better understanding:
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img src="img/icons/16/delete.png" alt="delete" height="16" width="16">'.'</td>';
echo '</tr>';
}
Like you've saw the delete option has already there (with no function/action yet) Here is the thing... I could put a link to a file in href="delete.php? but when a user clicks on this link will lead them to the delete.php page, leaving the administration page... I would like that when the user clicks the delete img, worked as/similar AJAX. I don't want the user exit the page....
Sorry for bad english (not my mothertongue), if you guys want more details just ask.
Ps: New PHP Programmer
Thanks in advance.
use javascript or jQuery to do an ajax request to delete.php with the id of the row you want to delete. I often put the id in the <tr> like echo "<tr data-id='{$row['id']}'>" and my jQuery would look something like this
$(".delete").on('click', function() {
var id= $(this).parents('tr').data('id');
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function(data, textStatus, jqXHR) {
// do something with the data returned. I usually output "success" from my
// delete.php and then check for data.indexOf('success') != -1
$("tr[data-id="+id+"]").remove();
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Error: "+jqXHR+" "+textStatus+" "+errorThrown);
}
});
});
on my delete.php page i check that $_POST['id'] is not empty before continuing. If you use $_REQUEST['id'] it will also work with a direct link to delete.php?id=999
You can call Delete.php using AJAX, so the request is executed without leaving the page.
The advantage of making an actual link to the delete page, is that it also works without Ajax/Javascript. So you can start by building a plain delete page, and add the Ajax later.
First, you should also print a record_id because just deleting based on the name is a very bad idea where encoding will hunt you down.
Having said that, here is what I would do using jQuery:
//PHP
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img class="delete-btn" src="img/icons/16/delete.png" alt="delete" height="16" width="16" data-order-id="$row['id']">'.'</td>';
echo '</tr>';
}
//JQUERY
$(document).ready(function(){
$(".delete-btn").click(function(){
$.post("/delete.php", {order_id: $(this).attr("data-order-id")}, function(){
$(this).closest("tr").remove();
});
});
});
I´m trying to build a shopping cart in jQuery and PHP but cannot read values from form list.
When trying to get value from the form that is submitted i only get values from
the first form in the list view.
Please look at behaviour here:
http://www.adlertz.se/index.php?op=prodlist&katID=9&sidemenu=menushop
Click buy on ex. the middle, you get value from first.
Please help me with this, i have benn looking for solution for three days.
Probably a simple problem but i cant find the answer anywhere :| !!!.
Many thanks in advance!
function prodlist(){
$katID = $_GET['katID'];
$sql = mysql_query("SELECT * FROM shop_prod WHERE kategoriID=$katID");
while ($rad=mysql_fetch_array($sql)) {
echo "<div class=\"shop_prod_list\">";
echo "<div class=\"shop_prod_list_tmb\"><img src=\"shop/images/prod_images_tmb/".$rad['prodID'].".png\" alt=\"\"></div>";
echo "<form id=\"addcartform\" class=\"addcartform\" method=\"post\">";
echo "<input type=\"hidden\" name=\"prodID\" id=\"prodID\" value=\"".$rad['prodID']."\" />";
echo "<input type=\"submit\" class=\"shop_prod_list_kundvagn\" value=\"\" id=\"addcart\"/>";
echo "</form>";
echo "</div>";
}
echo "<div id=\"search_results\"></div>";
}
$(document).ready(function(){
$(".addcartform").click(function(e){
e.preventDefault();
addcart();
});
});
function addcart(){
var prodID=(this).document.getElementById('prodID').value; <-(Reads value but only the first)
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
}
<?php
include "db_config.php";
include "db_connect.php";
$prodID = strip_tags(substr($_POST['prodID'],0, 100));
$prodID = mysql_escape_string($prodID);
echo $prodID ." is added.";
?>
Use class instead of id
echo "<input type=\"hidden\" name=\"prodID\" class=\"prodID\" value=\"".$rad['prodID']."\" />";
Send the element which was clicked to your function
$(".addcartform").click(function(e){
e.preventDefault();
addcart(this); //this line
});
Then use that element to find the input with your class
function addcart(element){
var prodID = $(element).find('.prodID').val(); //Get val of clicked item
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
Although i would use only one button, without a form like this.
Php:
echo "<button name='prodID' class='shop_prod_list_kundvagn addcart' data-prodid='".$rad['prodID']."' value='Add' />";
Javascript:
$(".addcart").click(function(e){
e.preventDefault();
var prodID = $(this).data('prodid');
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
});
});
The code you use to pick out the value is not correct.
In theory you are supposed to have unique id's - so thats your first issue to resolve.
Secondly you need to find a better way to locate the value you are interested in.
My suggestion would be to add a button within each form and call it 'submit'.
On this button you add a data attribute that contains the product id.
With an onclick handler on this button you'll be able to get the data attribute directly.
Example which is not tested:
<button data-prodid="XYZ" onlcick="handleclick()">submit</button>
Javascript:
$(this).data('prodid')
Please note that you should not have duplicate IDs on the same page.
In this case, all three of your products have the id of "prodID". So in your JavaScript, when you getElementById, you will always get the first ID with that name.
There are many solutions for this. For example, you could add the product ID to the ID of the button, like 'id="addcart_' . $rad['prodID'] . '"'
You'd then parse that ID upon form submit to determine which product was selected.
I found another solution here: http://api.jquery.com/serialize/ - to pass hidden values.
But your solution is much simpler :)
I use jquery to post data to mysql.
**In settings.php i have this short JS code:**
$("form#submit").submit(function() {
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "settings.php",
data: "fname="+ fname +"& lname="+ lname,
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
return false;
});
**And this short php:**
if (isset($_POST['fname'])){
$fname = htmlspecialchars(trim($_POST['fname']));
DO SOMETHING....
}
This is the code where the FNAME comes from: (after hit ADD image-button then posted the fname value..)
echo "......
<form id='submit$i' method='post'><input type='hidden' name='fname' id='fname' class='text' value='$fm_linkaz'></div><input name='add'type='image' id='add' value='$fm_linkaz' src='s.png'/></form>..........";
This is work well. But i need a SELECT element, so i changed the code to:
......
echo "<select name=dropdown_list id='**ONAME**'><option value''>test</option>";
for($i=0; $i < count($myarray); $i++){
echo "<option value='$myarray[$i]'>$myarray[$i]</option>";}echo "</select>";
......</form>";
This is work well, but i dont know how can i modify the JS code, to post the selected value too.
Thank u for your help.
First of all the javascript code needs a few updates:
$('#fname').val() is better than $('#fname').attr('value') -- .val() will work on selects/checkboxes as well - where .attr('value') won't be reliable.
Second: the data parameter to your $.ajax() call can take a json object (which it will convert to the form string)
$.ajax({
type: "POST",
url: "settings.php",
data: {
'fname': $('#fname').val(),
'lname': $('#lname').val(),
'oname': $('#oname').val()
},
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
There is a plugin that makes this much easier:
$("form").ajaxForm({
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
UPDATED:
Also - the <select> element was named "dropdown_list" - perhaps you wanted it to be submitting data as "oname" instead. Form elements use the "name" property to submit, the id property only makes css/js selectors easier to code.
To get a selected value for use
jQuery('#**ONAME**').val();
Although I'm not sure if **ONAME** is valid ID, try removing the **
To get the value use the
$('select[name=dropdown_list]').val();
You could also use and ID, but I think you have some invalid chars in it and I doubt this will work:
$('select#**ONAME**').val();
Anyway .val() is what you are looking for. I also suggest using val() instead of attr('value').