I am using jquery.editinplace.js which is excellent but the problem I have it that I have multiple instances on a page - therefore need to somehow send a variable with it so it knows which row to update in the table
Can the ID be variable? e.g. #my_id123465, #my_id76543 then i can strip the #my_id in the backend PHP and be left with variable which tells me which row to update
So, example html for the page is currently: (there will be multiple of these)
<div id="my_notes" title="Click to edit">'.$item[comments].'</div>
And the jquery which is fired:
$(document).ready(function(){
$("#my_notes").editInPlace({
saving_animation_color: "#ECF2F8",
url: '/pages/includes/edit_in_place.php',
});
});
I'd almost like the code to be something like
$("#my_notes*").editInPlace({ // note the wildcard*
But that doesn't work
Try doing this:
$("div^='#my_notes'").editInPlace({ // etc
Have a look at the docs for this:
http://api.jquery.com/attribute-starts-with-selector/
Not tested, but could something like this work.
Note i have changed the id to a class identifier if you have multiple instances
$(document).ready(function(){
$(".notes").editInPlace({
saving_animation_color: "#ECF2F8",
url: function(item){
var id = $(item).attr("id");
return '/pages/includes/edit_in_place.php?id=' + id;
},
});
});
Related
I am using .load to update my list, but this is not right approach as it get nested each time. what would be the alternate. I am new to Ajax.
$(document).on('click','#npDelete',function(){
var dataId = $(this).data("id");
alert(dataId);
$.ajax({
type:'get',
url:"{!! URL::to('deleteproject') !!}",
data:{'id':dataId
,},
success:function(data){
console.log('success');
console.log(data);
console.log(data.length);
$("#projects1").load("projects");
},
error:function(){
},
});
});
Projects is the page which contains the list of projects from database. So each time I delete a project the list is updated, its working fine but each time the ajax request is called plus one(+1) time
The quick and dirty solution would be to:
Import only the #projects1 element instead of the whole document
Replace the contents of the existing document's #projects1 element's parent element (so that the #projects1 element itself is replaced)
Such:
$("#projects1").parent().load("projects #projects1");
… but a nicer solution would be to have {!! URL::to('deleteproject') !!} return JSON that gave a true or false response and then delete the element that was actually clicked:
Add var $clicked_element = $(this); above var dataId = $(this).data("id"); and the you can $clicked_element.remove() when the request is successful. (Or possibly something like $clicked_element.parents("tr").remove() … but I'm having to speculate as to what your HTML looks like).
NB: Your HTML implies that you have multiple elements with the id #npDelete. This is invalid HTML. Don't do that. Use a class to identify a group of related elements. Use an id only to identify a unique element.
do
$("#projects1").html("projects");
and i suggest you use
$(document).ready(function(){});
or
$("#target").on('click',function(){});
at the beginning of your code instead of using $(document).on('click',function(){});
I'm currently working on records that is tabulated in HTML, records are from the database and on the end part of that table, i have some actions, EDIT DELETE SHOW, i've already done the edit, which is NOT the same as my DELETE, my DELETE action is done using ajax, but the problem is that i can't properly get the value of each button, which contains the ID from the database.
This is part of the table where the delete button is located:
<td width="61"><button id="delete" value="<?php echo "$arr[0]"; ?>">Delete</button></td>
These is the jQuery part
$("#delete").click(function(){
alert($("#delete").val()); <-- CAN"T GET THE CORRECT ID
//AJAX PART HERE
})
The problem is that i can't correctly get the value of the button which i pressed, how do i do this, any suggestions are greatly appreciated..
This is the whole view of the table,
Not tested, but I expect the issue is that you are trying to get the val() of all the matches for #delete, which is probably all of your delete buttons (I can not know without seeing your generated HTML).
You should actually use a class of delete and select with .delete rather than an id, as an id, according to the HTML specification should refer to a unique element.
$("#delete").click(function(){
// note the use of `this` to refer to clicked object, rather than all delete buttons
alert($(this).val());
//AJAX PART HERE
})
First, write delete method in server side, like delete.php, return status, like 'error' and 'success'
$("#delete").click(function(){
var id = $(this).attr('id');
//AJAX PART HERE
$.get('delete.php?id=xxx',function(status){
if (status == 'success') $(this).parent().remove();
}
})
Just use jQuery's 'this' to access the button within the function...
e.g.
replace
alert($("#delete").val()); <-- CAN"T GET THE CORRECT ID
with
alert($(this).val());
The value of the button is what's displayed on it as text, but that won't get you the table's id. Also, since there are several delete buttons, use a class instead of an id.
Change your html code to something like this, using a custom attribute called "db-id", through which you will find out which record to delete:
<input class="delete" db-id="<?=$db-id?>" value="Delete"/>
Then, your js code can be adjusted like this:
$(".delete").click(function(){
var dbid = $(this).attr('db-id');
$.ajax({
type: 'POST',
url: 'script-url/here.php'
data: 'id=' + dbid,
success: function(feedback){
if(success==true) $('tr[db-id="' + dbid + '"]').delete
}
}).error(){
alert('Something went horribly wrong!');
};
})
Note that in the success function you can even make the row with the data disappear using .delete()
Also note that any malicious user will be able to edit the button's db-id in the browser, so take all necessary precautions and validations in the php script!
Try this:
$("button[id=delete]").click(function(){
$(this).closest('tr').remove(); // Delete row
alert($(this).attr('value')); // ID
});
button[id=delete] - because you'll have many buttons with same ID, better use CSS Classes...
ok here is your solution:
1) insted of id="delete" use class. like this:
<td width="61"><button class="delete" value="<?php echo "$arr[0]"; ?>">Delete</button></td>
2) your jquery should be:
$(".delete").click(function(){
alert($(this).val()); <-- CAN"T GET THE CORRECT ID
//AJAX PART HERE
})
This should alert the propper id, I proposee to this mehoded for edit, and show actio....
My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,
Before anyone says "try searching", I have - I realize this is probably a simple solution, but I just can't get it to work. This is my first venture into AJAX - and my knowledge of javascript is slightly above a 1st grader...I know I need to get up to speed on it.
I'm trying to build a nested task manager, using AJAX. I'm getting jammed up on the AJAX implementation...the list works well otherwise. The basic concept should output like this:
Goal: Create a nested task list
Milestone: Build the basic setup - completed 2/11/12
Task: Design the database - completed 2/11/12
Task: Design the php stuff - completed 2/11/12
Milestone: Add the finesse
Task: Include AJAX functioning
Task: Include CSS
As you click on the link, it runs my MySQL update to show the item being completed. I have three nested while loops (one for goals, one for milestones and one for tasks). They are near identical. Here's the most deeply nested loop:
$query_tasks = mysql_query("SELECT * FROM task WHERE task_gid = '$task_gid' AND task_mid = '$task_mid' AND task_tid IS NOT NULL");
$t_numrows = mysql_num_rows($query_tasks);
if($t_numrows > 0){
while( $get_task = mysql_fetch_array($query_tasks)){
$task_id = $get_task['task_id'];
$task_goal = $get_task['task_goal'];
$task_due = $task_task['task_due'];
$task_due = date("m/d/Y", $task_due);
$task_complete = $get_task['task_complete'];
$task_complete_date = $get_task['task_complete_date']; ?>
Here is my link to trigger the query:
<a id="link" href="#"><?=$task_goal?> by <?=$task_due?> </a>
}
Here is my ajax query:
<script type="text/javascript">
$('#link').click(function(){
$.ajax({
type: "GET",
url: "complete.php?id=<?=$task_id?>"
});
return false;
});
</script>
I've got it to work for one link (if I click on the last rendered link, it works as desired - but no other links do). I've tried calling the javascript in the head (my preferred method) as well as calling it each time the loop passes (not sure that's a good idea, but whatever). My thought is to use the variable from the while loop for each task in the javascript function. I've tried placing the ajax script into a javascript function and calling it on the onClick behavior for the link, but no luck. Thoughts?
This is how you should do it:
http://pastebin.com/ZMCzAS5H
By setting a custom attribute (task_id) to your link you'll be able to retrieve it later in the ajax request. This way you'll use one event binder for all of the links instead of one for each link.
It's not a good idea to use the same ID for several elements within the same document; IDs should be unique. Use classes instead so try
<a class="link" href="#"><?=$task_goal?> by <?=$task_due?> </a>
and
<script type="text/javascript">
$('.link').click(function(){
$.ajax({
type: "GET",
url: "complete.php?id=<?=$task_id?>"
});
return false;
});
</script>
JavaScript and PHP do not interact. PHP is a 'pre-processor' and basically generates HTML (in this context). You can't use PHP variables in JavaScript. Period.
When generating the HTML, add the task_id to the anchor
echo "<a class=\"link\" href=\"#\" rel=\"". $task_id ."\">". $task_goal ." by ". $task_due . " </a>";
(don't use an ID for link, but use a class)
Then in jQuery:
$('.link').click(function(e){
e.preventDefault(); // use this instead of return false;
task_id = $(this).attr('rel');
$.ajax({
type: "GET",
url: "complete.php?id="+ task_id
});
});
"I've got it to work for one link (if I click on the last rendered link, it works as desired - but no other links do)"
This is probably because you have used an ID for the anchor, and you can only use an ID once on the page. You must use a class
Finally, I find some article in http://code.google.com/intl/en/web/ajaxcrawling/docs/getting-started.html msnbc use this method. Thanks for all the friends.
Thanks for your all help. I will study it for myself :-}
Today, I updated my question again, remove all of my code. Maybe my thinking all wrong.
I want make a products show page.
One is index.php, another is search.php (as a jquery box page). index.php has some products catagory lists; each click on product catagory item will pass each value to search.php. search.php will create a mysql query and view products details. It(search.php) also has a search box.(search.php can turn a page to show multiple products; the search result looks similar to a jQuery gallery...).
I need to do any thing in search.php but without refreshing index.php.
I tried many method while I was thinking: Make search.php as an iframe (but can not judge search.php height when it turn page and index.php without refresh); use jquery ajax/json pass value from index.php to search.php, then get back all page's value to index.php. (still met some url rule trouble. php depend on url pass values in search.php, but if the value change, the two page will refresh all. )
so. I think, ask, find, try...
Accidental, I find a site like my request.
in this url, change search word after %3D, only the box page refresh
in this url, change search word after = the page will refresh
I found somthing in its source code, is this the key rules?
<script type="text/javascript">
var fastReplace = function() {
var href = document.location.href;
var siteUrl = window.location.port ? window.location.protocol+'//'+window.location.hostname +':'+window.location.port : window.location.protocol+'//'+window.location.hostname;
var delimiter = href.indexOf('#!') !== -1 ? '#!wallState=' : '#wallState=';
var pieces = href.split(delimiter);
if ( pieces[1] ) {
var pieces2 = pieces[1].split('__');
if ( pieces2[1] && pieces2[1].length > 1) {
window.location.replace( unescape(pieces2[1].replace(/\+/g, " ")));
}
}
}();
</script>
If so. in my condition. one page is index.php. another is search.php.
How to use js make a search url like
index.php#search.php?word=XXX&page=XXX
then how to pass value from one to another and avoid refreshing index.php?
Still waiting for help, waiting for some simple working code, only js, pass value get value.
Thanks to all.
I have read your problem, though I can not write complete code for you (lack of time ) So I can suggest you to what to do for your best practice
use dataType ='json' in jQuery.ajax function and
write json_encode() on B.php
and json_decode() on A.php or $.getJSON()
Alternate:
Read
jQuery.load()
assuming you really want to do something like here: http://powerwall.msnbc.msn.com/
I guess they are using a combination of ajax-requests and something like this: http://tkyk.github.com/jquery-history-plugin/
make shure that the navigation (all links, etc.) in the box works via ajax - check all the links and give them new functionality by js. you can write some function which requests the href url via ajax and then replace the content of your box. ...
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
//update url in addressbar
change_box_links(output_area);
}
});
});
});
}
it is upgradeable but shell show the main idea...
addendum[2011-05-15]
Get away from thinking you will have two files, that can handle some many "boxes". i mean you can do this but it's worth it.
but to be able to set up your templates like normal html page you could use the above script to parse the ajax requested html pages.
build your html-pages for
viewing the content,
viewing the search result
, etc.
on your main page you have to provide some "box" where you can display what u need. i recommand a div:
<div id="yourbox"></div>
your main page has buttons to display that box with different content, like in the example page you have showed us. if you click one of those a JS will create an ajax call to the desired page:
(here with jquery)
$('#showsearch_button').bind('click', function(){showsearch();});
function show_search() {
$.ajax({
url: 'search.php',
success: function(data){
var output_area = $('#yourbox');
output_area.html(data);
$.address.hash('search');
change_box_links(output_area);
}
});
});
for other buttons you will have similar functions.
the first function (see above) provides that the requested box-content can be written as a normal html page (so you can call it as stand-alone as well). here is the update of it where it also provides the hashtag url changes:
jquery and requireing the history-plugin
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
var name = url.replace('/\.php/','');
$.address.hash(name);
change_box_links(output_area);
}
});
});
});
}
and you will need some kind of this function, which will bind the back and forward buttons of your browser:
$.address.change(function(event) {
var name = $.address.hash();
switch(name){
case 'search': show_search(); break;
default: alert("page not found: "+name);
}
});
the above code should give an idea of how you can solve your problem. you will have to be very consequnt with filenames if you just copy and past this. again: it is improveable but shell show you the trick ;-)
im not sure that i fully understood what you want, but correct me if i didnt,
i think u need something like a dropdown that once the user select one item some div inside ur page show the result of another page result..
if so u can do it with jquery .load() and here is an example (no need for json)
Step 1:
Index.php
<p>
brand:<select id=jquerybrand>$jquerybrands</select><br />
Model:<select id=jquerycars></select><br />
</p>
<script type=\"text/javascript\">
$(document).ready(function(){
$('#jquerybrand').change(function(){
var value=$(this).value;
var url='api/quick.php?'+this.id+'='+this.value+' option';
$('#jquerycars').load(url);
});
});
</script>
This will simply show 2 dowpdown boxs (can be text or anything u like). and will add a listener to any change in value. once changed it will submit the id of the field and the new value to api/quick.php , then quick.php responce will be loaded into #jquerycars dropdown.
Step 2 quick.php
if(isset($_GET['jquerybrand'])){
$jquerycars="";
require_once("../lib/database.php");
$sql_db = new database();
$l=$sql_db->Item_in_table("car","sheet1","WHERE `brand`='$jquerybrand';");
foreach($l as $l)$jquerycars .="<option>$l</option>";
echo $jquerycars;//response that will replace the old #jquerycars
}
this will confirm that this is a request to get the query result only, then it will do the query and echo the results.
now once the results come back it will replace the old :)
hope it helps :).