I want to pass the id value of the tag that has just been clicked to a php file that is being loaded onto the page using greybox.
I got the id stored in a js variable called linkID and I can get it passing the correct id using location.href but this needs a page reload and doesnt work alongside greybox. Can and maybe how can I use Ajax to help send this info in the background?
Any help would be greatly appreciated?
The Javascript to get the id of the clicked a tag
<script type="text/javascript">
function myCallback(caller)
{
var linkID =caller.id;
location.href="species/butterfly.php?linkID=" + linkID;
alert(linkID);
}
</script>
The html a tag in index.php
<div id="stump">
<a href="#" id="2" class="hedgehog descript" title="Hedgehog"
rel="gb_page_center[1020, 550]" onclick="myCallback(this)"></a>
</div><!--close stump div -->
The butterfly.php page that is trying to recieve the id
<?php
// Retrieve the URL variables (using PHP).
$linkid = $_GET['linkID'];
echo "Number: ".$linkid;
?>
var myCallback = function(caller){
var linkID = caller.id;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","species/butterfly.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("linkID="+linkID;);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert("Request complete. Data: "+xmlhttp.responseText);
}
};
alert(linkID);
}
EDIT:
Pure GreyBox:
var myCallback = function(caller){
var linkID = caller.id;
caller.href = "species/butterfly.php?linkID="+linkID;
}
This will convert js variable to php variable
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Related
I am trying to pass a value to a ajax function. This was simple on a form and working as expected(changed the id to gal_id1 in the example below) but I am getting undefined error on the value passing for my anchor.
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "ajax_json_gallerySQL.php";
var gid = document.getElementById("gal_id").value;
var vars = "gal_id="+gid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Test Pictures. </h2>
THis is working
<input id="gal_id1" name="gal_id1" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();" > <br><br>
<div id="status"></div>
<?php
$myValue='13';
This is not working
echo "<td> <a id='gal_id' name='gal_id' href='#' onClick='ajax_post();' value='13' ><img src='images/Parents/Brook/Brook1.jpg' alt='Image' width='270' height='203'></a><br><br>";
?>
</body>
</html>
Anchors don't have values in the same way that inputs do, so .value won't work. What you can do instead is use document.getElementById("gal_id").getAttribute('value')
Having said that, you should probably be using data attributes, e.g.
<a data-value="13" id="gal_id">
and then
document.getElementById("gal_id").dataset.value
More information on data attributes
I have two divs, and when one is clicked it empties the div. I want to be able to load data into that div once it's been emptied. I've got it so it loads in both, but I only want to load data into the div that's been emptied.
HTML (I have two of these)
<div class="fl person">
<div class="maintain_size">
<input type="hidden" name="userSaved" value="<?php echo $user_one['id']; ?>" />
<img src="<?php echo "http://graph.facebook.com/".$user_one['id']."/picture?type=large"; ?>" class="circle-mask" />
<img class="hoverimage" src="images/fire_extinguisher.png" />
<div class="meta_data">
<h2><?php echo $user_one['name']; ?></h2>
</div>
</div>
</div>
Javascript
<script>
$("div.person img").click(function () {
$(this).parent("div").fadeOut(1000, function () {
var saved_id_user_who_voted_val = "<?php echo $_SESSION['id']; ?>";
var saved_id_user_voted_on_val = $(this).parent('div').find('input:hidden');
var saved_id_user_voted_on_val = saved_id_user_voted_on_val.val();
$(this).parent("div").empty();
// Load in new data
var current_div = $(this).parent("div");
$.get('loadNewUser.php', function(data) {
current_div.html(data);
});
});
});
</script>
The data seems to come through fine if I select a div that's not the current one, or I just use an alert to see if the data is there--which it is, but if I try load the data into the current div it just doesn't work. Any ideas? Thanks.
The code that I think is wrong:
$.get('loadNewUser.php', function(data) {
current_div.html(data);
});
Edit: The div I'm trying to get the data into is: div.person - although, there are 2 of these.
Once you empty the div your 'this' is no longer there. Try just declaring var current_div before you empty.
var current_div = $(this).parent("div");
current_div.empty();
$.get('loadNewUser.php', function(data) {
current_div.html(data);
});
See fiddle
You need to delegate the event as you are replacing old content with new one
$(document.body).on('click',"div.person img",function () {
Use live() function
Example
$("div.person img").live("click",function () {
//Your code goes here
});
I wrote script directly in html file, it adds some pagination feature, and it works just fine until it's in HTML file, but I just cant get how to transfer this script to external js file and make it run from there. So heres html part :
<form id="moredisplay" method="get" style="display:inline;">
<input class="hiddeninteger" type="hidden" name="loadmore" value="">
<!--LIMIT CHANGER-->
<input type="checkbox" title="" id="limitcheck" name="limit" value="<?php echo $vsego;?>" style="display:none;">
<input type="checkbox" title="" id="skipforfcheck" name="skip_items" value="" style="display:none;">
<input type="checkbox" title="" id="skipbackcheck" name="skip_items" value="" style="display:none;">
<button type="submit" title="back" value="" id="rerurn_more_items"/>back</button>
<button type="submit" title="next" value="" id="skip_more_items"/>fowards</button>
<button type="submit" title="more content" value="<?php echo $vsego;?>" id="limit" name="limit" onclick=""/>more content</button>
<script>
var currentval = jQuery('.scippeditems').attr('value');
jQuery('#skip_items,#rerurn_items').attr('value',currentval);
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){
jQuery('#rerurn_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
var itemsshow = jQuery('#limit').val();
var pagescount = (jQuery('#skip_items').attr('value'))/(jQuery('#limit').attr('value'));
if(pagescount >=5){jQuery('#skip_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
function changepageforf(){
var elem = document.getElementById("skip_items");
var currentval = elem.value;
elem.value = parseInt(currentval) + 24;}//parseInt(itemsshow);}
function changepageback(){
var elem = document.getElementById("rerurn_items");
var currentval = elem.value;
elem.value = parseInt(currentval) - 24;}//parseInt(itemsshow);}
</script>
<script>
jQuery(document).ready(function(){
jQuery('#limit').click(changelimit);//RUN FUNCTION ON LIMIT CHANGE
if ( document.location.href.indexOf('&limit') > -1 ) {//IF URL CONTAINS LINES LIMIT
jQuery('#rerurn_items, #skip_items').hide()//HIDE PAGINATION
jQuery('#rerurn_more_items, #skip_more_items').show()//SHOW LIMIT PAGINATION
var checkval = jQuery('#limitcheck').attr('value');
var currentvalskip = jQuery('.scippeditems').attr('value');
jQuery('#skipforfcheck').attr('value', (parseInt(checkval)+parseInt(currentvalskip)));//NEXT BTN VALUE
var currentforfaction = jQuery('#skipforfcheck').attr('value')
jQuery('#skipbackcheck').attr('value',Math.ceil( ( (parseInt(currentforfaction)-parseInt(checkval) ) - parseInt(checkval) ) ) );//PREV BTN VALUE
var pagescount = (jQuery('#skipforfcheck').attr('value'))/(jQuery('#limitcheck').attr('value'));
if(pagescount >=5){jQuery('#skip_more_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
if( jQuery('#skipbackcheck').attr('value') <= 0 ){ jQuery('#skipbackcheck').attr('value', 0 );}//RETURN 0 AS A VALUE IF NEGATIVE
jQuery('#skip_more_items').click(function(){//SUBMIT NEXT BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipforfcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
jQuery('#rerurn_more_items').click(function(){//SUBMIT PREV BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipbackcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
}
function changelimit(){//LIMIT INCREASE STEP
var elem = document.getElementById("limit");
var currentval = elem.value;
elem.value = parseInt(currentval) + 6;}//HOW MUCH
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){//HIDE PREV BTN IF NO PREV
jQuery('#rerurn_more_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
});
</script>
</form>
What i did try: copied script and put in in the pagination.js file and called a script on the top of the page like this
$document =& JFactory::getDocument();
$document->addScript("jquery/pagination.js");
but that doesnt work...Im new to jQuery so please dont bash me if im just stupid:L)
You need to wrap your code in:
$(document).ready( function() {
// your code here
});
As Aspiring Aqib pointed out, you need to start your JQuery script with either
$(document).ready( function() {
// your code here
});
or
$(function() {
// your code here
});
This is basically saying, ' wait until the DOM has been fully created before executing the script inside that function.
Both Aspiring Aqib and Dave were right about wrapping your jQuery code in the $(function(){//code goes here}); block.
Yet one more common mistake is not loading jQuery library file and your own .js files in the correct order, which might be tricky to find out as there is no warning anywhere in your editor or browser. The jQuery library must precede all your own .js files.
I was using a self submitting form to process the data but I now need to process it separately so now I need to submit a form, return the results and place it in a div. It seems using AJAX is a good way to do this to have the data return to the original page where the form is. I have had a look at alot of examples and I don't really understand how to do it or really how its working.
Say I wanted to send this form data from index.php to my process page twitterprocess.php what do I need to do and get it to return to display the data processed.
<form method="POST" action="twitterprocess.php">
Hashtag:<input type="text" name="hashtag" /><br />
<input type="submit" value="Submit hashtag!" />
</form>
This is what I have been using to display the results.
<?php foreach($results as $result) {
$tweet_time = strtotime($result->created_at);?>
<div>
<div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?>
<div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div>
</div>
<br />
<? } ?>
I'm new to AJAX but any guidance would be greatly appreciated
*When you use AJAX the output generated on other page is the result for this page.
*Now when you want to post data and retrieve results through the use of AJAX then in form part of your html don't use type="submit" for button, but simply go for type="button".
*action attribute should be left blank as you are going to trigger the action through your AJAX code.
*Well rest all your solution in the code snippet below:
Below is the HTML code along with AJAX
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Form Handling Through AJAX</title>
<script type="text/javascript">
function loadXmlDoc(fname, lname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname + "&" + "lname=" + lname);
}
</script>
</head>
<body>
<p>
<span id="ajaxify"> </span>
</p>
<form id="frm" action="#">
<input type="text" name="fn" />
<input type="text" name="ln" />
<input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" />
</form>
</body>
</html>
Below is the PHP code that is used in above code
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
echo "Hello " . $fname . " " . $lname;
?>
Assign some id to your submit button, i'd use id="submit" and some id for your text field (i use id="text");
Client-side js:
$("#submit").click(function () {
var postData = new Object(); //for complex-form
postData.hashTag = $("#text").val();
$.ajax({
type: 'POST', //or 'GET' if you need
contentType: "application/json; charset=UTF-8", //i use json here
dataType: "json",
url: "some_url",
data: JSON.stringify(postData), //or smth like param1=...¶m2=... etc... if you don't want json
success: function (response) {
//handle response here, do all page updates or show error message due to server-side validation
},
error: function () {
//handle http errors here
}
});
return false; //we don't want browser to do submit
});
So, if user has js enabled = your code will do ajax request, otherwise - regular post request will be made;
On a server-side you have to handle ajax and regular submit different to make it work correct in both cases. I'm not good in php so can't do any advise here
You can use jQuery, for example,
function doPost(formdata){
var url="/twitterprocess.php";
var senddata={'data':formdata};
$.post(url,senddata,function(receiveddata){
dosomethingwithreceiveddata(receiveddata);
}
your php will get senddata in JSON form. You can process and send appropriate response. That response can be handled by dosomethingwithreceiveddata.
I find the Ajax Form plugin a good tool for the job.
http://www.malsup.com/jquery/form/#tab4
A basic code example could be:
$(document).ready(function() { // On Document Ready
var options = {
target: '#output1', // ID of the DOM elment where you want to show the results
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// the callback function
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
All your PHP file have to do is echo the html (or text) back that you want to show in your DIV after the form has been submitted.
If you do not want to use jquery try this in pure javascript
function SendData(Arg) {
xmlhttp=null;
var uri = "/twitterprocess.php";
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null) {
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
if(xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if(xmlDoc.xml) {
Xml2String = xmlDoc.xml
} else {
Xml2String = new XMLSerializer().serializeToString(xmlDoc);
}
document.getElementById("CellData").value=Xml2String;
} else {
alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status);
}
}
}
}
I have code like this :
<?php
$username = 'johndoe';
?>
<head>
<script>
...
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});
...
</script>
</head>
<body>
...
<li><input type="hidden" value="001" class="block-hidden-input" />
<a href="#" id="manage-1" class="manage-content-link">
<img src="images/web-block/web-block1.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
<li><input type="hidden" value="002" class="block-hidden-input" />
<a href="#" id="manage-2" class="manage-content-link">
<img src="images/web-block/web-block2.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
...
</body>
as you can see there, every time user click "manage-content-link" class, either manage-1, manage-2, ... or even manage-X (multiple li tags) jQuery will load "file-XXX.php". which XXX is actually value of hidden input in li tag.
but that "file-XXX.php" requires $username from PHP tags and ID itself, that is "manage-X". how to pass this 2 variables needed by "file-XXX.php", one from PHP and other from ID's?
Use jQuery's .ajax() instead of .load(): http://api.jquery.com/jQuery.ajax/
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val(),
this_id = self.attr('id');
$.ajax({
url: "file-" + file + ".php",
data: { username: "<?php echo $username;?>", id: this_id },
context: this,
success: function(data) {
$(this).next(".manage-content-wrap").find(".manage-content").html(data);
}
});
e.preventDefault();
});
If you want to keep the script external, you couldn't rely on php to echo the $username inside the script. So, you could add the username a few ways. You can make a hidden input somewhere in the page with the value equal to the username; you could attach the username to an element (like the body) as a data-username attribute; or you could just have a script block in the header that purely defined the username. For example:
<input type="hidden" name="username" value="<?php echo $username;?>>
Or:
<body data-username="<?php echo $username;?>">
Or:
<head>
<script>
var username = "<?php echo $username;?>";
</script>
</head>
In your <body> you can add a hidden field
<input type="hidden" value="<?=$username?>" id="username" />
and in your jquery,
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
var username = $("username").val(); //use this variable where ever you want
var ids = $(this).attr('id'); // this is the id
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php?id="+ids+"&username="+username); //and in php file usee $_GET
e.preventDefault();
});
$('a.manage-content-link').click(function (e) {
var self = $(this);
file = self.prev('.block-hidden-input').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});
Instead of passing username from script, i would suggest you store username in a session and get that value inside php using $_SESSION['username'] otherwise it will cause you security issue in the future.
DEMO