I am displaying a table using php on an html page. I want to edit the cell contents (basically make changes to a value, and make ajax call to update the database). The requirement for me is to use an onblur function (I can get around with using onkeypress as well). Can anyone please tell me what would be the simplest way of getting the new value entered with the cell id?
The alert for x tells me its "object HTMLTableCellElement"
Thanks!!!
foreach($_RESPONSE['VENDOR_LIST'] as $r){
echo "<tr><td>".$r['fdEmail']."</td><td id='companyname_".$r['fdId']."' contenteditable='true' onblur='updateValue(id)';>".$r['fdCompanyName']." ".$r['fdId']."</td></tr>";
}
Javascript method
function updateValue(thisdata){
alert(""+thisdata);
var x=document.getElementById(""+thisdata);
if(x){
alert(x);
//var r = x.value;
}
else
alert("not found");
}
In your HTML, change updateValue(id) to updateValue(this.id);
Then put this inside your first if statement in the updateValue function.
if(x.innerText){
alert(x.innerText);
} else {
// Firefox support
alert(x.textContent);
}
The "value" of a table cell is not actually considered a value by javascript, it's just HTML. Try alerting x.innerText. See this question for obtaining cell contents by ID.
Also, I know everyone hates hearing this, but this would be much easier with jQuery.
In your code
var x=document.getElementById(""+thisdata);
Here x is an object, you need to write the required function to change the values or to get the values.
alert(x.innerHTML);
will give you the value of the cell.
Id mentioned in HTML td tag and the id in your getElementById deos not match.
(Use error console in your browser to get the javascript errors)
You may have to change your function like this
function updateValue(thisdata){
var x=document.getElementById("companyname_"+thisdata);
if(x){
alert(x.innerHTML);
}
else
alert("not found");
}
Your HTML code to :
foreach($_RESPONSE['VENDOR_LIST'] as $r){
echo "<tr><td>".$r['fdEmail']."</td>
<td id='companyname_".$r['fdId']."' contenteditable='true' onblur="updateValue('companyname_".$r['fdId']."');">".$r['fdCompanyName']." ".$r['fdId']."</td></tr>";
}
NOTE : I have not tested the code please make changes accordingly, Post here if you find it difficult :)
ALWAYS USE jQuery, It makes your task simple :)
Related
I want to add a button on my website, where a User can delete his Account. Unfortunately I don't know how to realize it...
my Code so far:
Javascript:
<script language = "JavaScript" >
function delete(id) {
if (confirm("Do your really want to delete your account?"))
{
header("refresh:1;url=intern.php?act=account");
}
else
{
}
}
</script>
my .html file:(there are no tags like html title head... it begins with ?php..)
<td></form><input type='submit' name='deleteuser' value='Delete Account' onClick='return delete()'/></form></td>
Also i have an if clause in the .html file:
if(isset($_POST['deleteuser'])) {
if(delete() == true){
delete_user;
}
else{
header("refresh:1;url=intern.php?act=account");
}
}
The Button is there and when I click on it, it asks me if I'm sure to delete my account, but afterwards I got an error: "Fatal Error:Call to undefined function delete() "
I have a stored procedure named: sp_deleteAccount. In my config.php I declared it as:
$SQL_delete_user = "CALL sp_deleteAccount('";
Now I don't know how to bind that stored procedure in the code so that the Account will be deleted after pressing "Yes I want to delete my Account".
Hope I didn't miss anything and someone can help me
JOP
In this portion you're calling a php redirect(i think?) in javascript without php open tag so that's not going to work. Instead you can use a javascript reditrect if the 'if' statement returns true(yes) then redirect to a url with a get variable of delete or something, see below.
edit -- you'll probably want the id as well so i made adjustments. PLus in the onclick in the form you'll need to pass the id, unless it's stored in a session variable or something, in which case you don't need to pass it into the url. your sql should end with "WHERE id=" then just tack the id onto the query. This is just a simple example to get you started, always be cautious of sql injection, but i'll leave preventing it up to you.
<script language = "JavaScript" >
function deleteUser(id) {
if (confirm("Do your really want to delete your account?"))
{
window.location.href= 'intern.php?delete=true&id='+id;
}
else
{
window.location.href = 'intern.php?act=account';
}
}
</script>
next in intern.php check for the get variable
if(isset($_GET['delete'])) {
$mysqli = new mysqli(connection variables here);
$mysqli->query($SQL_delete_user.(int)$_GET['id']);
}
give that a try, rearrange the code as you like but that should get it done.
as for the error, you can't use the keyword delete for a function name. One last thing, for this to work make the input type "button"
I am not sure there might be a way to achieve it using the approach you are trying , but I am not aware of it. For this I would typically use an ajax call to an url, on the click event of the OK button in the jquery-ui Dialog. And then process the logic and on success create another dialog for confirmation.
I searched and struggled with this issue until I did a little lateral thinking.
I used JavaScript to show a hidden div containing the Yes/No options.
Then an onClick around the Yes option which loaded the php script into a hidden iFrame.
The onClick around the No option simply hid the div and did nothing else.
A bonus is being able to style the div any way I wanted, show and hide it with an effect and place it exactly where it looked best.
I am using codeigniter.I have simple form_dropdown(). I want to execute an onchange() function for my drop down.
I will get the string which was selected through JavaScript.
This is my code but its not working
$js ="onChange=message()";
echo "<script type=\"text/javascript\" > function message(){ var no=document.getElementById('name').value;
alert(sr);
}
</script>";
echo form_dropdown('name',$data,'large',$js);
form_dropdown doesn't automatically add an id to the element, so getElementById won't work as written.
also, for understanding's sake, the guide doesn't do a good job of explaining the fourth parameter. Calling it $js is misleading, as it well add anything you give it to the attributes list.
Change the one line of code to this (note the quotes around the onChange function as well):
$js = 'id = "name" onChange="message();"';
make sure you're viewing your source code after it's output to verify it is outputting valid html as well.
Also, on Chrome, F12 will bring up your developer tools, and hitting the esc key will toggle showing your JavaScript console, which will hopefully give you meaningful errors if everything doesn't go as planned.
Edit:
It also looks like you're setting the value of a variable called no, but alerting a variable called sr, which doesn't seem to be defined.
you can also simply pass ref from function call that would easy instead of getting value from document.getElementById(), it will work when you will add id in select dropdowm
try this code
<?php
echo "<script type=\"text/javascript\" >
function message(element){
var no=element.value;
alert(no);
}
</script>";
echo form_dropdown('name',$data,'large', 'onChange="message(this);"');
?>
how do i do that ?
my html structure looks like this
EDIT: i have updated to html so it fits the rules.
<td id="1" class="LinkWrap">link</td>
i use this code:
$(".link").click(function() {
$(this).parent();
//some ajax code
});
To select the td by the id LinkWrap, but i need the value of the class,
the class' value is fetched by php && mysql and is the id of the element thats i fetched. therefor the value is not a constant i and i cant just say chose class with value 1 it could be 2 or 5932.
i need that value to my ajax script so i can insert when the user clicks that link.
if theres a better method please let me know :)
Aside from the fact that it's not recommended to start class names with a number. Use attr to get the class attribute.
$(".link").click(function() {
alert( $(this).parent().attr('class') );
});
Edit: You're better of using the data attribute as stated by others as well.
HTML
<td data-rowid="1" class="LinkWrap">link</td>
Javascript
$(".link").click(function() {
alert( $(this).parent().data('rowid') );
});
It sounds like you're doing data storage in the class attribute. Classes cannot start with a digit, and this means your invalid usage may wind up causing glitches in some browsers. You'd be better off using jQuery's data() in conjunction with data-* attributes instead.
Interstellar_Coder and wilbbe01 are both right in the execution but there is one thing in your code that is going to bite you. The td has an ID that, if repeated, could cause you referencing issues. id attributes should be unique across a DOM instance at peril of very unpredictable results across different browsers.
aside from that ceejayoz solution is best.
Since, as I mentioned in my comment, it seems you mixed up the classes and IDs, and to avoid the problem noted by ceeyajoz, I'd suggest using another approach:
$('.link').click(function(e){
var the_id = $(this).closest('td').attr('id'); //or parent().
$.ajax({
url: 'http://www.mysite.com/index.php?page_id='+the_id,
success:function(response){
alert(response);
}
});
e.preventDefault();
});
And in your html:
<td class="LinkWrap" id="td_1">link</td>
And in your php:
$id = $_GET['page_id'];
$id = str_replace('td_','',$id);
echo $id;
I think what you will need is the following.
$(this).parent().attr('class');
Edit: Ditto the data attribute stated by others as well.
How to get an array of all checkboxes selected on the page, and then passing it to the next page (in this case php, so it can be picked up by php _POST function). I have come up with this :
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox:checked").each(function() {
selected.push($(this).val());
});
$('#od').submit(function() {
alert(this.selected); // *See note below
$.post('receiver.php', {'registration': selected});
return false;
});
});
</script>
But is does not seem to work :( It returns null, as if no checkboxes would have been added to the array, or maybe the post function is wrong. Can you point me in the right direction here?
I've found the following of issues:
You read the checked items on page load, thus ignoring all changes made by the user. Move that code to the submit() handler.
Your debugging code (alert(this.selected)) tries to display the value of the selected property for the form node. It isn't a reference to your JavaScript global variable selected. I suggest you use a proper debugging tool such as Firebug; alerts are highly unsuitable.
You sucessfully send the values of checked items. You just ignore the field name and rename everything to registration. That looks intended, otherwise report back:
{'registration': selected}
I suppose you can make jQuery serialize the values for you but fixing these little details in your code should do the trick anyway.
I think $("input:checkbox:checked") should be `$("input[type="checkbox"]:checked")
Or simply: $('input:checked', '#form-container');
$('#od').submit(function() {
var selected = $('input[type="checkbox"]:checked').toArray();
$.post('receiver.php', {'registration': selected});
return false;
});
The Data being posted might need to be split up.....
echo "<td> + manuf + </td>";
Is this above ever going to work??
I'm pulling results from a mysql db to edit the contents but need the jQuery functionality to edit it, hence the embedded javascript variable...
EDIT:
Sorry for the lack of context, its related to another question i've asked on here Mysql edit users orders they have placed
this is the end goal. To edit the order i place, i need to pull the results into an environment similar to how the user placed the order. So my thinking was to include the jQuery functionality to add items to a cart etc, then they could press submit and in the same way i used .Ajax to post the data to an insert php script i would post the values to an update php script! Is this backwards thinking, any advice welcomed!
I suggest you take a look at the follwing.
json_encode
Ajax
JSONP
Now your simplest solution under you circumstances is to do go for the json_encode method. Let me show you an example:
$json_data = array(
'manuf' => $some_munaf_data
);
echo "<script type=\"text/javascript\">";
echo "var Data = " . json_encode(json_data);
echo "</script>";
This will produce an object called Data, and would look like so:
<script type="text/javascript">
var Data = {
munaf : "You value of $some_munaf_data"
}
</script>
Then when you need the data just use Data.munaf and it will hold the value from the PHP Side.
Try just emitting the MySQL content with PHP:
echo "<td id='manuf'>".$manuf."</td>"
Then get the contents with jQuery like this:
var manuf = $('#manuf').text();
Would you not echo out the jQuery within a Javascript code island? You need the client-based code (jQuery) to be able to execute after the server-side code (PHP).
echo '<td><script language = "JavaScript" type = "text/JavaScript">document.write("");</script></td>';
Is this above ever going to work??
Nope. You'd need to output valid JavaScript for the browser to interpret:
echo "<script>document.write('<td>'+manuf+'</td>')</script>";
But that is a dreadful construct, and I can't really see why you would need this, seeing as the td's contents are likely to be static at first.
Consume you have the table echoed with php:
<table id="sometab">
<tr>
<td>
</td>
<tr>
</table>
The jquery for printing resuls in any td is :nth-child(2) takes 2 table td object :
<script type="text/javascript">
$(function(){
$("#sometab tr td:nth-child(2)").html("bla");
})
</script>
Is "manuf" a JS variable or part of a PHP output e.g. part of generated ?
Basically this can easily be done by:
mysql thru PHP(*I can't put table tag..sorry.):
while($row = mysql_fetch_object($result)) {
echo 'tr';
echo 'td a href="#" class="myres"'.$row->manuf.'/a /td';
echo '/tr';
}
then on your JS just attach a "click" handler
$(function() {
$(".myres").click(function() {
//my update handler...
});
});
i think you cant embed the jquery variable in the php like this .
you just give the class name here from here when edit will be click you will get the variable as in submit click in other questions .