I made a website that depends on PHP, AJAX and Javascript.
The problem here is that the website is unstable which means sometimes the validation is working and some times it is not working at all.
The validation code is written in JavaScript. Does this mean that we need more special conditions?
The code for validation:
<script language=Javascript>
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(src, val)
{
var req = Inint_AJAX();
req.onreadystatechange = function ()
{
if (req.readyState==4)
{
if (req.status==200)
{
document.getElementById(src).innerHTML=req.responseText;
}
}
};
req.open("GET", "traditional_locate.php?data="+src+"&val="+val);
req.send(null);
}
window.onLoad=dochange('cities', -1);
function submitform()
{
if(document.form1.onsubmit())
{
document.form1.submit();
}
}
function validate()
{
var p_o_box=(document.form1.p_o_box.value);
var owner_name=(document.form1.owner_name.value);
var cities=(document.form1.cities.value);
var post_office=(document.form1.post_office.value);
if(cities == 0)
{
alert("Please Choose city");
document.form1.cities.focus();
return false;
}
else if(post_office == 0)
{
alert("Please Choose post office");
document.form1.post_office.focus();
return false;
}
else if (p_o_box=="")
{
alert ("Please Write P.O.Box");
document.form1.p_o_box.focus();
return false;
}
else if(owner_name=="")
{
alert("Please Write Owner Name");
return false;
}
else if(p_o_box!="")
{
var a=new Array;
<?php
session_start();
$zipinfo=$_SESSION[zip_code];
$conn=mysql_connect('localhost','root','');
mysql_select_db('post_db',$conn);
$query="select p_o_box from p_o_box where zip_code='$zipinfo' ";
$result = mysql_query ($query , $conn ) or die ( mysql_error ());
$rows=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
for($i=0;$i<count($n); $i++)
{
echo "a[$i]='".$n[$i]."';\n";
}
?>
var ss=0;
for(i=0;i<a.length;i++)
if(a[i]==p_o_box)
{
var ss=1;
}
if (ss==0)
{
alert('not correct p.o. box');
document.form1.p_o_box.focus();
return false;
}
else
{ return true;}
}
return true;
}
</script>
Very hard to answer because I don't see a question.
What exactly does not work?
But I can suppose some problems:
Are you sure, that body.onload runs? Sometimes doesn't...
scripting is not crossbrowser
session_start() should fail because there is an output before and headers can't be sent.
you said that validation fails, but where is it being called?
please, provide more exact question and more clear example of code which does not work (i.e. I'm not sure, that source of submitform() is so nessecary).
Validation should be done on the server side. What happens when a use disables their JavaScript?
Also, that block of JavaScript will only execute the PHP when the page loads, and not everytime the user validates.
Related
I found this helpful example:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
that shows how to work with data using Ajax. However, the article does not give details about what the PHP file should contain to make the example actually work.
I have tried this:
<?php
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
echo json_encode($computedString);
?>
And variations thereof, to no avail. The result is a message box that says undefined. What should be in the PHP file for this example to make it work?
Here is the HTML page, complete with the JS:
<label>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function()
{
var userName = document.getElementById("ajaxTextbox").value;
makeRequest('test.php',userName);
};
function makeRequest(url, userName)
{
httpRequest = new XMLHttpRequest();
if (!httpRequest)
{
alert('Giving up - cannot create an XMLHTTP instance.');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
try
{
var response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
})();
</script>
EDIT:
The alertContents() function was modified as follows:
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
console.log(response);
console.log(httpRequest.responseText);
var response = "default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
The first console.log line is line #44 in the script. Rerunning the program and looking in the Console here is what happens:
When
console.log(response);
is commented out this is the result:
ANOTHER EDIT:
The problem does indeed appear to have been in the PHP script. Here is the updated PHP script and the result:
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['computedString' => $computedString];
echo json_encode($array);
A further improvement:
$array = ['userData' => $name, 'computedString' => $computedString];
results in:
Updated:
Based on my understanding with your comments, it looks liek your PHP file is not returning the JSON response. It is returning the text whihc you passed from your form. So your responseText is simple string.
Hence, when you are trying to read it's property, it is undefined. Try the following code now.
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
if(httpRequest.responseText == '')
{
alert('Error in code');
return;
}
alert(httpRequest.responseText);
}
else
{
alert('There was a problem with the request.');
}
}
}
Original:
There is an issue with the variable scope in your code.
var response = JSON.parse(httpRequest.responseText);
Here, you are defining response as a variable inside the try block and then trying to alert outside the block. That is why it is undefined.
Either you should move the alert statement inside the TRY block or define the variable outside.
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
var response = "Some default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
I want to send and receive data from php files. What is the best possible way to do this?
What is the best replacement for GDownloadUrl in Google Map V3?
Here is my existing function to check if I inserted successfully:
function checkSaveGeoFenceData(data,code)
{
//var geoFenceDataJson = eval('(' + json + ')');
if(code===200)
{
//alert("JSON VALUE : "+data+"test");
if(data=="SMGFE\n")
{
alert("Geo Fence " +
document.getElementById("geoFenceName").value +
" Already Exist");
}
else {
alert("Successfully Inserted");
window.opener.location.reload();
window.close();
}
}
else
{
alert("Fail to insert");
}
}
Existing function to grab data from php:
function processtViewData(json)
{
dataJson = eval('(' + json + ')');
var totalData = dataJson.data1.length;
}
There is no equivalent to GDownloadUrl in the API V3. Loading data via AJAX is a general javascrip task that is not specific to the API or to Google Maps.
Here's a function that will do the same:
function ajaxLoad(url,callback,postData,plain) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType && plain) {
http_request.overrideMimeType('text/plain');
}
} 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('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
eval(callback(http_request));
}
else {
alert('Request Failed: ' + http_request.status);
}
}
};
if (postData) { // POST
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.setRequestHeader("Content-length", postData.length);
http_request.send(postData);
}
else {
http_request.open('GET', url, true);
http_request.send(null);
}
}
Make sure your server responds with a content-type:text/plain header
Call it with postdsata:
var postdata = 'a=1&b=2';
ajaxLoad(serverUrl,myCallback,postdata);
function myCallback(req){
var txt = req.responseText;
// optional, if needed to evaluate JSON
eval(txt);
}
In Js file I've created a function which has to send an id and return boolean value to php file which returns false or true; but how can I do it?
JS function
function findDB(id)
{
}
PHP side
include_once("kutuphane/inc.php");
$id = $_POST['tipi'];
$sql= "select count(id) from bolge_db where parent_id=$id";
$faz2= $_SESSION["VT"]->doQuery($sql);
$flag=false;
if($faz2>0)
{
$flag= true;
}
else
{
$flag= false;
}
It's simple AJAX! Try out this code in js:
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
keep in mind that you have to echo something in php! eg: echo 1; echo 0;
Or using jQuery
var data = {
var1 : "string or another var"
};
$.post('url.php',data , function(data) {
var response = data;
//Do What Ever You Want
});
I want to create a edit pop up form using just ajax. i.e when user clicks on a link , a pop up comes up and he edits the data and saves it. can i do this with out any ajax framework ?
Yes you can, you can always create XMLHttpRequest objects yourself, but using a framework will save you hours or days of coding and make sure your service has maximum browser compatibility.
Yes, you can use the following function which I wrote and did several weeks optimizing it.
function ajaxGET(url,span_or_div) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/plain');
}
}
else if (window.ActiveXObject) { // IE ( yeah 200bytes wasted because of IE.. lol
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 1) {
window.document.getElementById(span_or_div).innerHTML='Loading...';
}
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
document.getElementById(span_or_div).innerHTML=(httpRequest.responseText);
} else {
window.document.getElementById(span_or_div).innerHTML='<strong>Error 404</strong><br />Page Not Found.';
}
}
};
httpRequest.open('GET', url, true);
httpRequest.send('');
}
I have the following javascript functions, which when in a standalone file, will be called correctly from a page.
function deleteItem(layer, url) {
var xmlHttp=GetXmlHttpObject();
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
if(xmlHttp.responseText == 'result=true') {
var row = document.getElementById(layer);
row.parentNode.removeChild(row);
}
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function deleteRec(layer, pk) {
url = "get_records.php?cmd=deleterec&pk="+pk+"&sid="+Math.random();
if (confirm("Confirm Delete?")) {
deleteItem(layer, url);
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
return xmlHttp;
}
It is called like so:
echo '<td>DELETE</td>' . "\n";
This displays the confirm dialog, and will delete the page if OK is clicked, as it should.
However.
When my other necessary functions are placed in the js file, nothing will happen.
function update(layer, url) {
var xmlHttp=GetXmlHttpObject();
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updateByPk(layer, pk) {
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
update(layer, url);
}
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
function updateByPage(layer, query, pg) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&pg="+pg+"&sid="+Math.random();
update(layer, url);
}
function deleteItem(layer, url) {
var xmlHttp=GetXmlHttpObject();
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
if(xmlHttp.responseText == 'result=true') {
var row = document.getElementById(layer);
row.parentNode.removeChild(row);
}
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function deleteRec(layer, pk) {
url = "get_records.php?cmd=deleterec&pk="+pk+"&sid="+Math.random();
if (confirm("Confirm Delete?")) {
deleteItem(layer, url);
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
return xmlHttp;
}
function makewindows(html) {
child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
There does not seem to be anything wrong with the JavaScript itself, so I am wondering if something is being canceled out somehow. Even when changing deleterec() to a simple alert nothing happens.
I wonder if there's an error being detected in your JS code? If your Javascript has a syntax error in it, the browser will probably just not run any of it. If you're using a debugger like Firebug, this will help you track down the error.
Alternatively, try adding one function at a time, which will tell you which one is breaking things.
First, in this text block:
if(xmlHttp.responseText == 'result=true') {
// Here you remove the appropriate element from the DOM rather than trying to update something within the DOM
var row = document.getElementById(layer);
row.parentNode.removeChild(row);
}
document.getElementById(layer).innerHTML=xmlHttp.responseText;
You don't actually want this line:
document.getElementById(layer).innerHTML=xmlHttp.responseText;
Additionally, try placing the deleteRec function first before the deleteItem function in the list of functions.
I would also recommend that you test this in Firefox with Firebug installed. This will show you any Javascript errors that are occurring on the page.
Try using FireBug to follow the code that does work.
Also if you have a complete page to show, that may clear things a bit.
maybe the html tag you are using to include the js file into your page is not correct
the correct way to include a script is
<script type="text/css" src="myfile.js"></script>
the following will not work
<script type="text/css" src="myfile.js" />
I would also recomend you to use Firefox's Error Console that is a nice app that will let you know if there are any issues.