I am trying to pass data in textarea and make the php callback to retutn the same and display it in textarea after simple manipulation to ensure transfer took place.But i can't make my ajax function pass the data.
<script type="text/javascript" src="ajax.js"></script>
This is my form
<form action="#" method="post" onsubmit="submit_notes_call();return false;">
<textarea rows="5" cols="30" name="user_notes" id="user_notes"></textarea>
<input type="submit" name="notes_submit" id="notes_submit" value="UPDATE NOTES" >
</form>
Here is my Ajax function in ajax.js
function submit_notes_call()
{
var ajaxVar;
var user_notes = " Data from ajax call to php callback ";
/*document.getElementById("user_notes").value; */
try
{
ajaxVar = new XMLHttpRequest();
}catch (e)
{
try
{
ajaxVar = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e)
{
try
{
ajaxVar = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e)
{
alert("Your browser broke!");
return false;
}
}
}
ajaxVar.onreadystatechange=function(){
if(ajaxVar.readyState==4)
{
document.getElementById("user_notes").innerHTML = ajaxVar.responseText;
}
};
ajaxVar.open('POST','notes_submit.php',true);
ajaxVar.send(user_notes);
}
and here is my php code in notes_submit.php
<?php
$data_recieved = "Data from php call back to ajax function+".$_POST['user_notes'];
echo "Data : " . $data_recieved;
?>
I get the output as Data : Data sent from php call back to ajax function+ inside the textarea field which means that although comunication is taking place but php call back is not able read the data sent by ajax caller or may be ajax function is not able to send the data to php call back.
What is the error here??
Replace thie line
ajaxVar.send(user_notes);
by
ajaxVar.send('user_notes='+user_notes);
Read this http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Related
I am having problems with a really basic request to a php file from AJAX. I am running all this stuff through XAMPP. What I'm trying to do with this code is to echo the name typed into the textbox once the submit button is clicked and the results to be posted in the div "results". I am doing this to try and weed out errors in another script and so far it hasn't gone too well.
<html>
<head>
<script type="text/javascript">
function go() {
var request;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var uname = document.getElementById("name").value;
request.onreadystatechange= function() {
if(request.readyState == 4) {
document.getElementById("result").innerHTML = response.Text;
}
}
url = "win.php?name="+uname;
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>
Name:<input type="textbox" name="jesus" id="name" />
<input type="button" value="Submit" onlick="go()" />
<div id ="result"> Result:</div>
</body>
</html>
<?php
$name = $_GET['name'];
echo $name;
?>
You don't have an object called response, you are looking for the responseText property on the request object.
document.getElementById("result").innerHTML = request.responseText;
Also:
avoid using globals
don't send your HTTP request before the target div exists, you run the risk of it still not existing when the response comes back
you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4).
Don't put raw user input in URLs, escape it with encodeURIComponent first
Use that
document.getElementById("result").innerHTML = response.responseText;
I am using the very basic technique of AJAX to save the form into a database using AJAX.
However I am having some trouble.
All I searched, I was getting jQuery code, but I want to do this with simple AJAX only.
HTML FORM:
<form id="submitcourse" name="submitcourse" method="get">
<p>Course Name: <input type="text" name="cvalue" id="cvalue" /></p>
Successfull
</form>
<span id="result">.</span>
AJAX CODE:
<script type="text/javascript">
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXobject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitformwithajax()
{
var myAjaxPostrequest=new GetXmlHttpObject();
var coursename=document.submitcourse.cvalue.value;
var parameter="cvalue="+coursename;
myAjaxPostrequest.open("GET", "do.php", true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter)
myAjaxPostrequest.onreadystatechange=function{
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
document.getElementById("result").innerHTML=myAjaxPostrequest.responseText;
document.getElementById("submitcourse").style.display="none";
}
else
document.getElementById("submitcourse").innerHTML="An error has occured making the request";
}
}
}
</script>
The purpose of the above AJAX code is to send the form details to do.php File, where I can work on the data received.
do.php File :
<?php
$course=$_REQUEST['cvalue'];
echo "dddd".$course;
?>
Right now I am not able to get the value in the do.php file, Please help me out,
NOTE: I have the code to do this using jQuery, but I want to do it in this method only. Since it is for teaching students about Basic AJAX.
Right off the bat I'm noticing that you don't have () after your function definition...
myAjaxPostrequest.onreadystatechange=function{
Should be
myAjaxPostrequest.onreadystatechange=function(){
Let me know if this helps!
The problem is: you put your parameter inside send(), which is not correct, because you sending GET request, change your code to:
myAjaxPostrequest.open("GET", "do.php?"+parameter, true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send()
Using Ajax GET, the parameter should be mixed with the URL, however, your code is correct for POST method.
or if you want to use POST
myAjaxPostrequest.open("POST", "do.php", true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter)
See if you can't get away with using getElementsByName instead
var coursename=document.getElementsByName('cvalue')[0].value;
I'm trying to POST and email address entry from a HTML form to a PHP script to store the result in a database. The script is also responsible for firing an error message should the user enter an invalid email address etc. I would like the whole process to involve an AJAX call so that the page doesn't have to be reloaded each time that the user hits the submit button on the form.
As of now, each time the user hits the form submit button the page is being refreshed and i'm getting a response from the ajax call but it is immediately being written over due to the refresh.
Here's my HTML and Javascript/ajax:
<div id="emailform">
<form method="post"><!--action="planethome.php"-->
<input class="emailinput" type="text" name="email" maxlength="80" placeholder="enter your email address"/>
<input class="submitemailbutton" name="send_button" type="submit" value="Send" onClick="ajaxFunction()/>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
</div>
<div id="errororsuccess">
</div>
<!--ajax stuff:---------------------------------->
<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("Ajax is struggling in your browser.");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('errororsuccess').innerHTML = ajaxRequest.responseText;
}
}
// Create a function that will receive data sent from the server
ajaxRequest.open("POST", "addemailtodatabase.php", true);
ajaxRequest.send(null);
}
and here's my PHP:
<?php
require_once ('planetconfig.php');
if (isset($_POST['submitted'])) { /
require_once (MYSQL);
$email = FALSE;
$trimmed = array_map('trim', $_POST);
if (!empty($_POST['email']))
{
if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$_POST['email'])) {
$email = mysqli_real_escape_string ($dbc, $trimmed['email']);
} else {
echo "Invalid";
}
} else {
echo "You need to enter an email address";
}
if ($email) {
$q = "INSERT INTO planetemail (email, time) VALUES (AES_ENCRYPT('$email', 'password'), NOW())";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_affected_rows($dbc) == 1) {
echo "Thanks, we'll be in touch";
exit();
} else {
echo '<p class="error">We\'re sorry, something has gone wrong.</p>';
}
}
mysqli_close($dbc);
}
?>
I'm sure it's something to do with my POST method or how I have my ajax call set up.
I'm new to all this, can anyone tell me what I'm doing wrong or suggest a better implementation. I have a deadline of tomorrow morning to have this done.
You're problem is that you are using a submit button. The submit button will submit the form, change it from a type="submit" to type="button" and it will work and as #juzerali suggested, use jQuery, that code hurts my head.
1st, yes that is awful, use jquery. 2nd although you have bound ajax call with onclick of submit button, you have not prevented the default behaviour from executing. The form will still get submitted the usual way.
if (isset($_POST['submitted'])) { /
There is a stray / in your code.
Also, Change type="submit" to type="button"
The onClick event handler will pick up the submit becuase you are making an AJAX request, no need to POST.
return false; at the end of the script to keep it from submitting the normal way.
Why is this not working? When the Ajax code IS NOT wrapped in function xmlhttpGet() it does work: PHP returns the called page and inserts it into the DIV. In this code i have wrapped the code into the function xmlhttGet() amd nothing happens. The requested page is not loaded into the DIV.
<html><head><title>AJAX GET </title>
</head><body><center />
<h1>Loading a web page into a DIV</h1>
<FORM id="form" method="post" action="">
<b> Enter argument: </b>
<input size="40" name="q" id="q" value="">
<INPUT TYPE="submit" id="submit" VALUE="Submit" onClick="xmlhttpGet(this.form)">
<INPUT TYPE="reset" VALUE="Reset">
</FORM>
<div id='info'>This sentence will be replaced</div>
<script>
function xmlhttpGet(form)
{
nocache = "&nocache=" + Math.random() * 1000000
request = new ajaxRequest()
var $q = form.q.value
request.open("GET", "urlget.php?url=amazon.com/gp/aw" + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
}// END xmlhttpGet
request.send(null) ;
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}// ajaxRequest
</script></body></html>
[EDIT]
the onClick is triggered fine. I have verified by inserting alerts into the functions.
[EDIT2]
i suppose it would help if i show the PHP bit too
<?php // urlget.php
if (isset($_GET['url'])) {
echo file_get_contents("http://".sanitizeString($_GET['url']));
}
else {
echo "problem!" ; // [edited line]
}
function sanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
you have to call xmlhttpGet() somewhere in ur script to get it to 'run'
When your code is not wrapped in a function, it will simply execute as the code is parsed by the browser.
Once you wrap it in a function, it will not execute until the function is explicitly called.
If you want to get the script to run automatically, try changing your body tag to:
<body onload='xmlhttpGet();'>
If you want to fire the function with user interaction, use one of the many events such as onclick or onmouseover or onmousedown
Your xmlhttpget function should start as:
function xmlhttpGet(form)
{
... as it is you're referencing the variable form in the function (eg var $q = form.q.value) but never assigning it a value (so it's being created/pulled from global scope).
The scope of this in your function for onreadystatechange will vary wildly depending on browser and how it's called - not a good design decision, try replacing this with request in the function.
Ajax responds with an empty string when triggered via form onsubmit in Firefox, but it is working fine in Internet Explorer and Opera (works in Firefox if sent by a submit button instead of form onsubmit).
I am simply calling a php file with the ajax GET and the php file response with - echo $response = "something";. Then the response value is alerted. I am getting it work in IE but in Firefox the response is an empty string (checked by typeof()).
code is 4 files: index.php, ajax-connect.js, cbb.js, cbb.php
index.php
<html> <head> <script src="ajax-connect.js"></script> <script src="cbb.js"></script>
</head> <body>
<form name="condtactform1" method="get" action="" onSubmit="contactfunction()">
<input type="submit" name="hissubmit" id="hissubmit" value="submit"> </form>
</body> </html>
ajax-connect.php
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*#cc_on #*/
/*#
if (#_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
#end
#*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
cbb.js
function contactfunction() {
var url = "cbb.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var responsae = xmlHttp.responseText;
alert(responsae);
}
}
cbb.php
<?php $response = "something"; echo $response; ?>
If i trigger ajax by submit button instead of the form submit then it works fine in firefox like:
<form name="condtactform1" method="get" action="">
<input type="submit" name="hissubmit" id="hissubmit" value="submit" onFocus="contactfunction()"> </form>
Any idea why it is doing this?
Thanks.
I think part of the problem is that you aren't stopping the normal action of the submit. That it is working at all is probably based on how the return values of the last function executed is handled, though its hard to tell. Try adding a "return false" to your contactFunction();
If that doesn't work, I'd invest some time in retrofitting it to use a javascript framework for the AJAX (jQuery, MooTools, Prototype, etc.) rather than going down the route of debugging the cross browser differences. A jQuery solution would look like:
<form name="condtactform1" method="get" action="cbb-full.php">
<input type="submit" name="hissubmit" id="hissubmit" value="submit">
</form>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('#hissubmit').click( function() {
$.get( 'cbb.php', function(response) {
alert(response);
});
return false;
});
});
</script>
Note that the form ought to post to a url that will generate a full response if javascript isn't enabled.