In a module of my PHP application, there are multiple forms, generated with unique id's and names by server side as "formToProcess1, formToProcess2, ... , fromToProcessN". However, there are two ajax functions that handles the request of each form, which both of them gets form name in string as argument, like following:
function ajaxReject(formToProcess)
{
var ajaxRequest;
//document.getElementById('divUploadResultAjax').style.display = 'none';
try
{
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e)
{
alert('Something is wrong with your browser, AJAX not working!');
return false;
}
}
}
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
var ajaxDisplay = document.getElementById('divUploadResultAjax');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
//document.getElementById('loadingAjaxIcon').style.display = 'none';
document.getElementById('divUploadResultAjax').style.display = 'block';
}
}
var updName = document.forms['formToProcess'].getElementById('userName').value;
//i'll get other elements values for query string to send if i can get this one first :)
var queryString = '?name=' + updName + '&lastname=' + updLastname + '&bio=' + updBio + '&country=' + updCountry + '&cams=' + updCams + '&fb=' + updFacebook + '&twitter=' + updTwitter + '&processRequest=' + RequestProcess;
alert (queryString);
return;
ajaxRequest.open('GET', 'dashboardUpdateProfile.php' + queryString, true);
ajaxRequest.send(null);
}
#Every form in the php page is generated like following:
echo '
<div id="divUploadResultAjax">
<form name="profileUpdater'. $formCounter .'">
<input type="hidden" id="uluid" name="uluid" value="'.$UL_UploadID.'" />
<table class="tg" style="width: 100%">
<tr>
<td style="font-weight: bold; width: 250px; color: #000000;" colspan="3">
<h3>Upload ID #'.$UL_UploadID.' </h3> (Uploaded On '.$NewCreateDate.')
</td>
...
...
bla bla bla
...
...
----> this is where i call functions in each form.
<input type="button" class="btnRegister" name="updateProfile" onclick="ajaxReject(\'profileUpdater'. $formCounter .'\')" value="Reject" />
<input type="button" class="btnRegister" name="updateProfile" onclick="ajaxApprove()" value="Approve" />
I'm not really sure what is wrong. When i call the function with button click, it works perfectly until end of if(ajaxRequest.readyState == 4), after that, when i'm trying to get the var updName = document.forms['formToProcess'].getElementById('userName').value; function crashes. What i'm doing wrong?
Thanks.
Can't you use something like var updName = document.getElementById('userName').value;.
I don't find username element in the form? Is it there in your actual code?
Related
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 a form post.php where the user inputs data and receivepost.php where the data entered is transferred through Ajax post. I want to achieve the following in the receivepost.php:
if (button save is pressed) {
save to database
} else if (button retrieve is pressed) {
retrieve from database
}
I tried using isset($_POST['submit']) on the reveivepost.php but it does not detect the button which is pressed. The Ajax post is working and all the data is available on the receivepost page. I have another solution that is to create 2 different PHP files and run them according to the button pressed but I think there is a better solution to it.
Here is my ajax call :
$("document").ready(function () {
$("#submit").click(function () {
var xmlhttp;
// test browsers
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// get the values of textboxes
var desc_text = $("#desc").val();
var speed_text = $("#speed").val();
var tarea_text = $("#tarea").val();
// variable to hold value of textboxes
var content = "desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
// open the request
xmlhttp.open("POST", "receivepost.php", true);
// set header
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// check xmlhttp state and status and display text in div
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('para').innerHTML = xmlhttp.responseText;
}
}
// send the content of the textboxes
xmlhttp.send(content);
});
});
Here is my post.php form:
<form id="myform">
<label for="description">Description:</label>
<input type="text" id="desc" name="desc" /><br/>
<label for="speed">Speed: </label>
<input type="text" id="speed" name="speed" /><br/>
<textarea id="tarea" cols="10" rows="10" name="tarea"></textarea><br/>
<input type="button" id="submit" name = "submit" value="Save">
<input type="button" id="retrieve" name="retrieve" value="Retrieve">
</form>
<div id="para"></div>
Try to add to the content an extra parameter called button-pressed which you can later use in receivepost.php as below:
if($_POST['button-pressed']=="save"){
//savetodb code
}
else if($_POST['button-pressed']=="retrieve"){
//retreivefromdb code
}
Perhaps you have two JavaScript functions, one on each button:
$("#submit").click(function () {
var content = "button-pressed=save" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
$("#retrieve").click(function () {
var content = "button-pressed=retrieve" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
Hope this helps?
<input type="button" id="submit" name ="submit" value="save" onClick="fnc(this.id)">
<input type="button" id="retrieve" name="retrieve" value="retrieve" onClick="fnc(this.id)">
<script type="text/javascript">
function fnc(myid) {
var val=document.getElementById(myid).value;
alert(val);
}
</script>
How to send looping data from html page to php page using ajax. I am trying so hard but i don't get any way passing looping data into php page.
order.html page code are described in the below:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age[]').value;
var queryString = "?age=" + age ;
ajaxRequest.open("GET", "example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='age[]' Name='age[]' /> <br />
Name: <input type='text' id='age[]' Name='age[]'/>
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>result will display here</div>
</body>
</html>
example.php page code are described in the below:
<?php
$len = count($_GET['age']);
for($x=0;$x<$len;$x++)
{
echo $service[$x]=$_GET['age'][$x];
}
?>
the [] should be append to the query string, not to the input name
var queryString = "?age[]=" + age1 + "&age[]=" + age2 + "&age[]=" + age3 ;
ajaxRequest.open("GET", "example.php" + queryString, true);
I have a script in which I need to process a file using ajax. Everything in the script works, except I can not get the right variable. I have tried everything and I currently have this in its place
title = "<?php echo $_FILES["file"]["name"] ?>";
I was wondering if anyone could tell me how to successfully set whatever is in this field
<label for="file">Thumbnail Pic:</label>
</td>
<td>
<input type="file" name="thumbnail" id="thumbnail" />
As a variable in the ajax script that I have. All help is extremely appreciated, thanks for the help!
<script language='javascript' type='text/javascript'>
function ajaxupload(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try{
ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e){
// Something went wrong
alert('Your browser broke!');
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('response');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var songtitle = document.getElementById('songtitle').value;
var thumbnail = document.getElementById('thumbnail').value;
var name = document.getElementById('file').value;
var title = "<?php echo $_FILES["file"]["name"] ?>";
var description = document.getElementById('description').value;
var params= 'songtitle=' + songtitle + '&thumbnail=' + thumbnail + '&title=' + title + '&description=' + description + '&name=' + name;
ajaxRequest.open("POST", 'ajaxupload.php', true);
ajaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajaxRequest.send(params);
}
</script>
<div id="centered2">
<h1>Music Upload</h1>
<div id="centered">
<table>
<tr>
<td>
<h4><br><?php
echo $echovar10;
echo $echovar20;
echo $echovar40;
echo $echovar50;
echo $echovar60;
echo $echovar120;
echo $echvoar130;
?><div id='response'></h4>
<table>
<tr>
<td>
<label for="file">Choose a song:</label>
</td>
<td>
<input type="file" name="file" id="file"/>
</td>
</tr>
<br />
<tr>
<td>
<label for="file">Thumbnail Pic:</label>
</td>
<td>
<input type="file" name="thumbnail" id="thumbnail" />
<br />
</td>
</tr>
I would really recommend you use jQuery. It'll make your life alot easier. Here's the ajax function documentation. jQuery also provides some wonderfully simple wrapper functions for get and post methods. Google hosts the code (minified) which is convenient.
$.post(
'ajaxupload.php', // url
$("#form_id").serialize(), // data
function(data) { // return function on success
alert(data);
}
);
But as for the real reason you are here, looks like a simple typo.
title = "<?php echo $_FILES['thumbnail']['name'] ?>";
I Have a select box, on selectinga value in it I have to display a form in which there is a Date field which include a javascript calendar functionalty. I tried it with normal AJAX and PHP combination, but I dont get the Calendar in it, So I just need to know How I can make it happen using JSON and AJAX and PHP?
Thanks
Every Help Is Appreciated....
THE CODE
This is The Javascript I am Using to AJAX function:
<script>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(path,val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('docfields').innerHTML="";
if(req.responseText != ''){
document.getElementById('docfields').innerHTML=req.responseText; //retuen value
}else{
document.getElementById('docfields').innerHTML="<br> \t<font size='2'><b>No Fields Available</b></font>";
}
}
}
};
req.open("GET", path+"getDocFields.php?doctype_id="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
</script>
Below Is the HTML form which I need to display with Calendar object (tcal) instantiated in the script tag:
<form onsubmit="" action="" method="post" name="newdoc">
<table border="0" style="border: medium none;" id="docfield">
<tbody>
<tr>
<td style="border-right: medium none;">
Date
</td>
<td style="border-right: medium none;">
<input type="text" value="" maxlength="10" name="Test" style="width: 100px;" id="date">
<script>
new tcal ({
'formname': 'newdoc',
'controlname': 'Test'
});
</script>
</td>
</tr>
</tbody>
</table>
</form>
I am not getting the calendar displayed...
I see javascrip in the response html, which will never be executed if the html is coming through ajax call.
Try to put that javascript
new tcal ({
'formname': 'newdoc',
'controlname': 'Test'
}); after your XMLHttpRequest object fetches and puts data in '#docfields'.
if (req.readyState==4)
{
if (req.status==200)
{
document.getElementById('docfields').innerHTML="";
if(req.responseText != '')
{
document.getElementById('docfields').innerHTML=req.responseText; //retuen value
/** here **/
new tcal ({'formname': 'newdoc','controlname': 'Test'});
/** here **/
}
else
{
document.getElementById('docfields').innerHTML="No Fields Available";
}
}
}
Hope it will help.
Imran is right. You need to extract the scriptcode and run it.
This code can be used very commonly:
var scripts = "";
$('form)'.find("script").each(function() {
var content = $(this).html();
content = content.replace(/<!--/g, "").replace(/(\/\/)?-->/g, "");
scripts += content;
});
eval (scripts); // eval is evil, but in this case...