[HTML/PHP]: Abort refresh of page - php

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.

Related

how to make ajax request in Yii?

I want to make an ajax request to allow the user to send some data from input field to database and then return it to the input field, as same as the comment box, so the data should inserted into the database and then displayed in the input field without reloading the page, here is my code:
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject !== null) {
httpObject.open("GET", "a page or a controller action"
, true);
httpObject.send(null);
// httpObject.onreadystatechange = setOutput;
}
}
so, how I can make a request that can call a controller action without leaving the entire page?
First, to make the Ajax request I suggest you to use jQuery. It will be a lot easier.
Here is an example (using jQuery) :
jQuery.getJSON('/path/to/your/controller/someAction/',function(response) {
console.log('Server reply : ',response);
}
In your controller's action do not forget to send output as json :
public function actionSomeAction()
{
die(json_encode("This is my response"));
}
edit : If you don't need jQuery, see this SO answer for making Ajax call without jQuery : https://stackoverflow.com/a/8567149/911718

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.

Getting trouble in saving data to a mysql using AJAX

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;

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);

javascript, php, ajax - AJAX response is always empty

Good day to all. I have the flowing problem.
I have 2 domains. On one domain I send an ajax post to the other and expect some results. The problem is that the response is always empty. If I inspect the net tab the request looks alright (the post data is fine), it doesn't receive any error, it ends (I put an alert on the handle response function to check what the response is). I tried sending a request to random domains (like example.com) to see if I get anything. The response is the same... none.
Here is the script I use:
function sendReqPost(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
//http_request.onreadystatechange = handleResponseAccept;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
//parameters is a global variable with the post data.
http_request.send(parameters);
}
I double checked everything in the script... I also inserted echos in the requested php page to see if I get anything. Whatever I do the response is empty.
P.S. On another domain the ajax script worked fine. Exactly the same.
I have 2 domains. On one domain I send an ajax post to the other and expect some results.
There's your problem. This is because of the Same Origin Policy in JavaScript. And thats why...
...on another domain the ajax script worked fine.
There are some workarounds though, called Cross Domain Ajax.
For your needs, since you apparently want HTML and not JSON, I would suggest a small PHP script to get the content from the other domain and forward it to your client side. This would be called Ajax proxy.
See this question
I don't see your http_request.responseText, it returns what is echo'ed in the request URL.
So try add this:
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert("An error occurred: "+ http_request.statusText);
}
}
};
Before:
//parameters is a global variable with the post data.
See if it works.

Categories