Passing a value to ajax with anchor. - php

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

Related

Post ID on Keyup AJAX/PHP/MYSQL

I have the below code. Currently it submits only the first_name which is exactly what I want and it does that on the fly without the page refreshing.
However I need to parse an ID number along the same ajax request through the hidden id field.
Can anybody suggest any ideas to help me?
Thanks in advance
CODE:
<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 = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var vars = "firstname="+fn+;
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>Ajax Post to PHP and Get Return Data</h2>
<input type="hidden" name="my_id" value="1234">
First Name: <input id="first_name" name="first_name" type="text" onkeyup="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
Use jquery
<!DOCTYPE html>
<html>
<head>
<title>TITLE</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ajax_post(){
var $elementStatus = $('#status');
$elementStatus.html('processing...');
var url = 'my_parse_file.php';
var data = { firstname : $('#first_name').val() };
var success = function(responseText, textStatus, jqXHR) {
if(jqXHR.status != 200)
return;
$elementStatus.html(responseText);
};
$.post(url, data, success);
};
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input type="hidden" name="my_id" value="1234">
First Name: <input id="first_name" name="first_name" type="text" onkeyup="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>

Form gets re-rendered after submit Ajax

<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "index2.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
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>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
The code above works and submits the data and gets the result, along with the result it renders the form again. Image --> http://oi47.tinypic.com/1bt02.jpg
How to fix it?
Thanks in advance.
Don't include the form in the response you send to the Ajax request.

submit a form via Ajax and update a result div

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=...&param2=... 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);
}
}
}
}

radio button data to ajax

Hi i'm printing out a radio button list dynamically with php using the following code:
<form method="post">
<p>Name of list:
<label for="name"></label>
<input type="text" name="name" id="name">
</p>
<p>Name of item:
<input id="first_name" name="first_name" type="text" />
<br />
<?php echo $form;?>
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();"></form>
where $form is the variable in which the radio button list is saved.Now i need to pass the selected radio button to an another php file using an ajax function ajax_post().But since my form method is POST my ajax function gets overridden and doesnt get called.
heres my ajax function
function ajax_post(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var rd = '<?php echo $_POST['radio'];?>';
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var nm = document.getElementById("name").value;
var vars = "todo="+fn+"&name="+nm+"&id="+id+"&rd="+rd;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
}
I need it to be POST because i want to extract what radio button i press and i also need the ajax function to work...any way around this?
You need to return false; from your function to avoid the form getting submitted the regular way.

Passing js variable to php variable

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>

Categories