Getting trouble in saving data to a mysql using AJAX - php

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;

Related

script is not getting variable from GET

I have code in /user.php:
<?php
$thisuser = $_GET['user'];
echo $thisuser;
?>
And i write in browser: /user.php?user=Maria
And the website do not echo anything. What is wrong about it?
I actually have a ajax script that should send there a variable by get but it do not work at all.
EDIT here is the whole thing:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
<script>
function prof(profuser){
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
This seems to be related to the <a> tag's default behavior preventing your function to execute on click.
Since you are setting the URL inside the prof() function, you don't need he href value inside the <a> tag, so you could do something like this:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
Note that I just set the href value to javascript:void(0);. So now onClick should take effect and the prof() function should be invoked.
** Visually verify if it's working: **
Use this javascript code:
<script>
function prof(profuser)
{
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if ( (xmlhttp.readyState == 4) && (xmlhttp.status==200) )
{
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
Then you will also have to add, in the same file where the javascript code is, the following:
<div id="result"></div>
Finally, please make sure you are properly closing the PHP tags <?php ?> and make sure that only PHP code is inside that block. HTML and Javascript must be outside that block.
The AJAX script will send the data by POST not by GET.
GET is to 'get' the value, POST is to pass the value.
You also only use the send() value for POST, so change the GET to POST in the AJAX.
Also, you need to declare your script BEFORE you call it in the HTML.

Web Shoutbox Idea

Hello I was thinking about making a shoutbox for my site. I don't want to use any others because it doesn't fit in well with my pre-existing members database. I thought of some ideas but I'm not really sure on a better way of doing this. I want to submit a form and without 'GET' send a shout. I also can't re-load the page. That's where AJAX comes in :p
I thought of setting up the form on my webpage as:
<form method="post" onsubmit="return sendShout()" >
<input type="text" name="Shout" id="Shout" />
</form>
With my javascript being the following:
<script>
function sendShout()
{
if(ShoutTime == 0)
{
var http = new XMLHttpRequest();
http.open("GET", location.href+"?shout="+encodeURIComponent(document.getElementById("Shout").value)+"&name="+encodeURIComponent(document.getElementById("username").value), true);
http.send();
ShoutTime = <?php echo $shoutWait;?>+1;
ShoutWait();
unidle();
document.getElementById("Shout").value='';
}
else
{
ShoutWaitNote();
getLogs();
}
return false;
}
</script>
then on the page I could put into the databse like $_GET['shout']... etc.
Now is there a better way to use ajax to send a shout to a mysql database without having the shout as a GET in the url?
I suspect there are bigger problems at hand here, but you can do a POST with XMLHttpRequest like so:
var http = new XMLHttpRequest();
http.open("POST", location.href);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send("shout=something&name=something");
As opposed to the GET version:
var http = new XMLHttpRequest();
http.open("GET", location.href + "?shout=something&name=something");
http.send();
You'll want to apply URL encoding in both cases. Good luck.

Able to receive data using $_GET but not $_POST [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 9 years ago.
Using Ajax to communicate with server,
I am trying to pass a value to dat.php using AJAX and get another value from dat.php back. The below code works fine when I use GET but doesn't work work with POST. I need to use POST as this is sensitive information I am trying to pass. Any idea hwy this is happening.
This is my code on test.php
<html>
<body>
<form action="<?php echo $_SERVER['$PHP_SELF'];?>" method="post">
<input type="text" name="value" onchange="ch_email1(this.value)"></input>
</form>
<script>
function ch_email1(str){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
var xl=xmlhttp.responseText
alert("Something Went wrong");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var xl=ajaxRequest.responseText;
alert (xl);
}
}
ajaxRequest.open("POST","dat.php?q="+str, true);
ajaxRequest.send(null);
}
</script>
</body>
</html>
This is dat.php
<?php
$q=$_POST['q'];
echo $q;
?>
Please note that above code works fine when I replace POST with GET. Any ides why this is happening.
This might help:
ajaxRequest.open("POST","dat.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send("q="+str);
Take a look at this page.
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Right now, you're sending a post request with nothing in it. Appending to the url just changes the $_GET variables.
You are mixing POST Ajax call with GET way
When you send an AJAX call with POST, you don't have to put parameter on the URL, but you must send parameters using the .send() method.
exemple:
ajaxRequest.open("POST","dat.php",true);
ajaxRequest.send("q=" + str);
You should use a JS librairy like jQuery or other, that will make it for you, instead of re-inventing the wheel and have common problems.

Ajax to read PHP

I think I'm getting ahead of myself, but I tried AJAX tutorials to read from a PHP file. The PHP file simply has an echo statement for the time, and I want to pass that to initialize a javascript clock.
But this is my first time trying AJAX and I can't even seem to get it to activate a test alert message.
Here is the code, it's at the bottom of my PHP page after all of the PHP.
<script type='text/javascript'>
function CheckForChange(){
//alert("4 and 4");
//if (4 == 1){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readystate == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
alert("here");
alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>
Can somebody tell me why this isn't working? No idea what I'm doing wrong.
The problem in your code is an uncapitalized letter. (Oops!) You check ajaxReady.readystate; you need to check ajaxReady.readyState.
Because ajaxReady.readystate will always be undefined, your alerts never fire.
Here's your code fixed and working.
As an aside, have you considered using a library to handle the ugliness of cross-browser XHR? jQuery is your friend:
function CheckForChange(){
$.get('ServerTime.php', function(data) {
$('#clocktxt').text(data);
});
}
You should probably have something like:
setInterval(CheckForChange, 7000);
On an unrelated note, it's common naming convension in JavaScript to have function and methods names' first letters not capitalized, and the rest is in camelCase. i.e. checkForChange().
I'm not sure the exact problem with your code; here's what I use -- I'm sure it will work for you. (plus, it works with more browsers)
var xhr = false;
function CheckForChange(){
/* Create xhr, which is the making of the object to request an external file */
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
/* End creating xhr */
/* Retrieve external file, and go to a function once its loading state has changed. */
if(xhr){
xhr.onreadystatechange = showContents;
xhr.open("GET", "ServerTime.php", true);
xhr.send(null);
}else{
//XMLHTTPRequest was never created. Can create an alert box if wanted.
}
/* End retrieve external file. */
}
function showContents(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
//Error. Can create an alert box if wanted.
}
}
}
setInterval(CheckForChange, 7000);

[HTML/PHP]: Abort refresh of page

In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.

Categories