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.
Related
Rooms are an array
window.location = "booking_status.php?array="+ JSON.stringify(rooms);
sending from javascript to php page
on php page url show full array value which are store in array in page address bar url
like that
http://localhost/zalawadi/booking_status.php?array=[{%22id%22:10,%22rate%22:100}]
I want to prevent this data which show in url %22id%22:10,%22rate%22:100
I am decoding on php page any other way to send array data from javascript to php page
The only way to send data to another page without showing them in the url is to use POST.
Basically, you can put your data into an invisible form input :
<form method="post" id="form" action="booking_status.php">
<input name="array" id="array" type="hidden" value="" />
</form>
Send
<script type="text/javascript">
function sendForm(){
document.getElementById('array').value = JSON.stringify(rooms);
document.getElementById('form').submit(); //fixed syntax
}
</script>
You can use a hidden form and the post method. Then you would use $_POST instead of $_GET.
<form action="script.php" onsubmit="this.firstChild.value=JSON.stringify(value);">
<input type="hidden" value="" />
Link text
</form>
You can use a POST request, however this would require generating and submitting a form:
// assuming `rooms` already defined
var frm = document.createElement('form'), inp = document.createElement('input');
frm.action = "booking_status.php";
frm.method = "post";
inp.type = "hidden";
inp.name = "array";
inp.value = JSON.stringify(rooms);
frm.appendChild(inp);
document.body.appendChild(frm);
frm.submit();
Why not just POST the data instead then?
For example, with jQuery:
$.ajax({
type: "POST",
url: "booking_status.php",
data: JSON.stringify(rooms),
success: // add success function here!
});
The advantage is you're not passing some horrific URL. As an added bonus, this example is also asynchronous, so the user doesn't see any refresh in their browser.
Non-Framework Version
If you don't wish to use jQuery, you can do this with pure Javascript, using the XMLHttpRequest object, like so:
var url = "get_data.php";
var param = JSON.stringify(rooms);
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// Request has gone well. Add something here.
}
}
http.send(param);
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;
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.
I have my site on index.html made in html+css., at my index.html i have this div id "content", where you put in main content to the page, and there's a link at the menubar that src to page2.php. When you press on the link it goes to the page2.php, but i want it to display inside the < div "content".
In page2 i have Hello this is a test, in a echo..
I dont want to use frames.. should i split up my design on index.php, and then on page2.php include top & footer? or is there another way
function test() {
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readystate==4 && xhr.status=200)
document.getElementById('content').innerHTML = xhr.responseText;
};
xhr.open("GET", "start.php", false);
xhr.send(null);
}
Hjem |
<div id="content" ></div>
Use AJAX to post a HTTP GET request to page2.php and display the result(echo) in the div container.
Somewhat like following, (will not work in IE)
<script>
function test(){
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readystate==4 && xhr.status=200)
document.getElementById('content').innerHTML = xhr.responseText;
};
xhr.open("GET", "page2.php", false);
xhr.send(null);
}
</script>
Try AJAX online
Like you suggested in your question, you should look into splitting the index.html into a header and a footer. This will allow your site to work without javascript, and you may find that it is easier or makes more sense.
There's some quite good tutorials around, such as this one, but googling for php header footer returns plenty of options.
You can use XMLHttpRequest() and not only "Hello this is a test", but you can also set any data from your MySQL database to <div id="content"> innerHTML.
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.