how you doing, i've been working on this for 2 hours now and I can't seem to get my page to dynamically display information when I change it. Would appreciate if someone can tell me what went wrong.
This is my HTML
<h2>Feedbacks</h2>
<form>
<select onchange="viewFeedback(this.value);">
<option value="unread">View Unread</option>
<option value="all" >View All</option>
</select>
</form>
<div id="feedbackview"></div>
This is my ajax
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
function viewFeedback(condition) {
http.onreadystatechange = function() {
if(http.readyState == 4) {
document.getElementById('feedbackview').innerHTML=http.responseText;
}
http.open("GET",'viewfeedback.php?condition='+condition,true);
http.send(null);
}
}
and here is the php
$condition = $_GET['condition'];
$db = new db();
$query = $db->query("SELECT * FROM feedback");
$rows = $db->countRows($query);
if($rows != 0) {
$results = $db->getRows($query);
foreach($results as $result) {
extract($result);
echo $name;
}
}
The open() and send() calls should not be within the onreadystatechange event, move them outside. You can also move the event outside from the viewFeedback() too because there's no need to keep re-defining it every time your dropdown is changed.
var http = createObject();
http.onreadystatechange = function() {
if(http.readyState == 4) {
document.getElementById('feedbackview').innerHTML=http.responseText;
}
}
function viewFeedback(condition) {
http.open("GET",'viewfeedback.php?condition='+condition,true);
http.send(null);
}
Also note that you don't do anything with $_GET['condition'] on the PHP side, so the response will always be the same regardless of which dropdown item is selected.
First, I don't know if that Ajax creation function is so great. I would comment it out for now and add it back only if it is not working in a supported browser. Instead just do this:
var http = new XMLHttpRequest();
Next, try hitting the PHP web service directly in your browser. Is it working? If so, fix the issues in your Ajax request:
function viewFeedback(condition) {
http.open("GET", 'viewfeedback.php?condition=' + condition, true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
if (http.status == 200) {
document.getElementById('feedbackview').innerHTML = http.responseText;
} else {
console.log(http.response);
}
}
}
http.send(null);
}
Let me know if this doesn't work.
Related
I have a small form which contains a first name, last name and a date. On clicking to submit the form I want it to check the database for a duplicate entry (with Ajax), and if there is already 1+ entries, present a confirm window confirming another submission. The confirm shouldn't show if there aren't any entries.
For some reason it seems to be presenting the confirm without the result from the Ajax PHP page. If I introduce an alert after the xmlHttp.send(null) line, it gets the text from the PHP (as wanted), making me think I misunderstand the order the code is executed. Here is the code:
Javascript:
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+first;
url=url+"&last="+last;
url=url+"&date="+date;
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
result = xmlHttp.responseText;
alert("RESULT="+result);
if(result != "clean") {
var validate = confirm(result);
return validate;
}
}
}
xmlHttp.open("GET",url,true);
var test = xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP:
// DATABASE CONNECTION INFORMATION REMOVED
$first = $_GET['first'];
$last = $_GET['last'];
$date = date('Y-m-d',strtotime($_GET['date']));
$sql = "SELECT COUNT(*) AS count FROM Table WHERE First='$first' AND ".
"Last='$last' AND Date='$date'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row['count'] > 0) {
if($row['count'] == 1) {
echo "There is already an entry for ".$first." ".$last." on ".
date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
else { // plural version of the same message
echo "There are already ".$row['count']." entries for ".$first." ".
$last." on ".date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
} else {
echo "clean";
}
Here is an answer using synchronous AJAX. This way, you don't have to overload the default form handling to get it to work. However, all javascript will be blocked while the confirmation request is running, which means your web page may appear to come to a screeching halt for however long the confirmation request lasts.
This function will return true if the record should be added, and false otherwise.
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return false;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
var validated = true;
var result = xmlHttp.responseText;
if (result != 'clean')
validated = confirm("RESULT="+result);
return validated;
}
This line of code return undefined.
var test = xmlHttp.send(null);
What you have to understand is that the send() call returns immediately and Javascript keeps running. Meanwhile, your AJAX request is running in the background. Also, your onreadystatechange handler is called once the request is done, whether it takes 10ms or 100s, and its return value is not received by the rest of your code.
I think what you wanted to submit the form AFTER the confirmation was finished. You only know when the request is finished from inside your onreadystatechange handler. The problem here is that, in order to wait for the AJAX request to finish you have to override the default behavior of the form.
You'll need to call preventDefault() on the form-submit event, and then submit the data manually after confirmation.
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
var confirmed = false;
var result = xmlHttp.responseText;
if (result == "clean")
confirmed = true;
else
confirmed = confirm("RESULT="+result);
if (confirmed) {
var url = "addData.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
window.location = url;
}
}
}
Also, when you're building your URL you should use encodeURIComponent.
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
I'd like to pull pictures and / or videos from another website onto my page, and i'd like to edit the looks with css. The website ofc. has rss, but i don't have an idea of how to do this. Someone told be before that i could ping the website and if there is new content, it automatically displays it on my site. How can this be done?
Thanks!
I am not quite sure if this is directly possible as it could theoretically cause a lot of traffic for the third-party website. Maybe you can read the content in your RSS-Reader and use this to update your site indirectly.
After all, aren't we talking about stealing content?
As the Rss feed is XML, the best way to do this is with Ajax, here is a sample
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "otherSites.xml";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
im trying to get a bit of html to refresh every 1 second with AJAX, I made this code my self with bits from different websites that I found. Im trying to understand how it all works.
I want to be able to refresh the page without reloading it in the browser and I want the JS function AJAXdisplay(); to run every one second with the variables I send to AJAXreturn(); when I call it.
When I call AJAXreturn(); I want it to run AJAXdisplay(); once to print out the html from my php file, on my body if the index file I want somthing like this
<body onClick=:AJAXdisplay(same variables as used when the page was made);">
</body>
here is my code:
function getHTTPObject(){
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function AJAXsend(url) {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("POST",url);
httpObject.send(null);
}
}
function AJAXreturn(url,pageName){
httpObject = getHTTPObject();
if (httpObject != null) {
if (navigator.appName != "Microsoft Internet Explorer") {
history.replaceState("", "", "index.php?page=" + pageName)
}
httpObject.open("POST",url);
httpObject.send(null);
AJAXdisplay(httpObject,url,pageName);
}
}
function AJAXdisplay(httpObjectIn,urlIn, pageNameIn){
httpObjectIn.onreadystatechange = function(){
if(httpObjectIn.readyState == 4){
document.getElementById('outputHTML').innerHTML = httpObjectIn.responseText;
AJAXdisplay('function(httpObjectIn,urlIn,pageNameIn)',1000);
}
}
}
To make javascript refresh, you should use the setInterval(); function. Here's what your looking for:
var timer = setInterval ("AJAXdisplay(variable);", 1000);
And if you ever need to stop the refresh you use:
clearInterval (timer);
I am trying to fill in a form using Javascript/ajax/php but the problem is that my function only fills in one of the needed forms and stops even tho I have gotten the second response from the server.
Code:
The function that starts filling stuff
function luePankkiviivakoodi(str) {
if (str==null) { //are we NOT injecting variables directly into the code, if not - Prompt for the barcode, and set the variable
var str = prompt("Valmis vastaanottamaan", "");
}
if (str==null) { //someone pressed abort on the prompt, we return
return;
}
newstr = str.split(' ').join(''); // remove spaces
if (str=="") { //is the string empty? -> return
return;
}
if (window.XMLHttpRequest) { //AJAX code
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
//we set some fields, no problem
document.getElementById('P_VII').value = viite;
document.getElementById('IBAN').value = saajatili;
document.getElementById('laskun_summa').value = summa;
document.getElementById('eräpäivä').value = eräpäivä;
//trigger other functions
getKassasumma(summa); //AJAX for accesing the database and calculating the sale price
DevideIntoCells(); //AJAX for accessing the database and dividing a sum into different cells
validateSumma(); //Validates the sum, and tells the user if it's OK
}
}
xmlhttp.open("GET","dataminer.php?question=pankkiviivakoodi&q="+newstr,true);//open AJAX connecttion
xmlhttp.send();//send stuff by AJAX
}
getKassasumma:
function getKassasumma(str) {
if (str=="") {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
}
}
kale = document.getElementById("TOS_K_ale").value;
xmlhttp.open("GET","dataminer.php?question=kassasumma&q="+str+"&kale="+kale.replace("%", "p")+"&nro="+document.getElementById("S_NRO").value,true);
xmlhttp.send();
}
DevideIntoCells:
function DevideIntoCells() {
str = document.getElementById('tiliöintitapa').value;
if (str==null) {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
document.getElementById("spinwheel3").style.visibility = "visible";
}
xmlhttp.onreadystatechange=function() {
//alert('OK! val= '+xmlhttp.readyState);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//alert('OK!');
eval(xmlhttp.responseText);
//alert('OK2!');
document.getElementById("spinwheel3").style.visibility = "hidden";
//alert('OK3!');
calculateSumma();
}
}
xmlhttp.open("GET","dataminer.php?question=percentages&q="+str+"&nro="+document.getElementById('S_NRO').value,true);
xmlhttp.send();
}
validateSumma (just some math):
function validateSumma() {
float = document.getElementById('summabox').value;
float = float.replace(",",".");
summa = parseFloat(float);
if (summa < 0) {
summa = 0
};
kassasummaunp = document.getElementById('laskun_summa').value;
kassasummafloat = kassasummaunp.replace(",",".");
kassasumma = parseFloat(kassasummafloat);
if (kassasumma < 0) {
kassasumma = 0
};
if (kassasumma == 0 || summa == 0) {
prosentti = "0%";
}
else {
prosentti = summa / kassasumma * 100;
prosentti = Math.round(prosentti*Math.pow(10,2))/Math.pow(10,2);
prosentti = prosentti+"%";
};
if (prosentti == "100%") {
is100 = 1;
}else {
is100 = 0;
}
document.getElementById('prosentti').innerHTML = prosentti;
if (is100 == 1) {
document.getElementById('prosentti').setAttribute("style", "color:green");
} else {
document.getElementById('prosentti').setAttribute("style", "color:red");
}
puuttuvaEuro();
}
The problem code here is getKassasumma(summa); and DevideIntoCells();. I disable one of them, and the other one works, I enable both of them, DevideIntoCells stops somewhere before document.getElementById("spinwheel3").style.visibility = "hidden";, probably at the eval(response) because getKassasumma already finished the ajax request and killed this one. same the other way around.
AJAX answers: DevideIntoCells:
var KP_osuus = parseFloat('40');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box1.5').value = newvalue;
var KP_osuus = parseFloat('60');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box2.5').value = newvalue;
AJAX answer: getKassasumma
var kassasumma = '477.99€';
document.getElementById('kassasumma').value = kassasumma;
Please ask if you need clarification!
EDIT: Just to be clear, this is NOT an AJAX problem, rather javascript.
I think you are 'swimming in it', how we say. If you begin with AJAX, I'd recommend you use a framework like jQuery and it's $.get() or $.post() functions. It will accomplish all the needed AJAX logic for you.
Try to make xmlhttp local, i.e.
var xmlhttp;
Because you are overwriting you xmlhttp you refer to in the event listeners, so when the listeners get called, they both see the same response.
at the beginning of every of your functions. For compatibility, also use send(null) instead of send().
Hi there I have Problem with my Code I just want to validate States which is generated from Ajax response.text
Here is the JQuery for State Field:
$(document).ready(function () {
var form = $("#addStudentfrm");
var state = $("#state");
var stateInfo = $("#stateInfo");
state.blur(validateStates);
state.keyup(validateStates);
function validateStates() {
if (state.val() == '') {
state.addClass("error");
stateInfo.text("Please Select/Enter State");
stateInfo.addClass("error5");
return false;
} else {
state.removeClass("error");
stateInfo.text("");
stateInfo.removeClass("error5");
return true;
}
}
});
Here PHP Function for Get All States in Respected Country:
public function getAllCountryStates($post){
$que = "Select * from ".WMX_COUNTRY." where code = '".$post[value1]."'";
$cRes = $this->executeQry($que);
$cResult = $this->getResultRow($cRes);
$cId = $cResult['id'];
$stateObj = new Admin;
$rdat = $post['opr'];
$rdtar = explode('.', $rdat);
$res = #mysql_fetch_row(mysql_query("Select * from ".$rdtar['1']." where id = ".$rdtar['0']));
$usts = $res['state'];
$result = $stateObj->selectQry(WMX_STATE,"country_id=$cId",'','');
$number = $stateObj->getTotalRow($result);
if($number > 0){
$getSelect ="<select name='state' id='state' class='textboxcss'>";
while($stateVal = $stateObj->getResultRow($result)){
$getSelect.="<option value='".$stateVal[state]."'>$stateVal[state]</option>";
}
$getSelect.="</select>";
}else{
if($usts!=''){
$getSelect = "<input type='text' name='state' id='state'class='textboxcss' value='$admnState'/>";
} else {
$getSelect = "<input type='text' name='state' id='state' class='textboxcss'/>";
}
}
echo $getSelect; }
In the Initial State Text box getting validate
but when the control comes with the Ajax Response Jquery wont validate it for Blank Entries
my Ajax Function:
function DataByPost(url,objId,postData,div_id){
var selId = objId.split('|');
var passData = postData;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX==null) {
alert("Your browser doesn't supportAJAX.");
return false
} else {
AJAX.open("POST",url,true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.onreadystatechange = function() {
if (AJAX.readyState==4 || AJAX.readyState=="complete"){
alert(AJAX.responseText);
var msg=AJAX.responseText;
var idary = new Array();
document.getElementById(selId).value = msg;
document.getElementById(selId).innerHTML = msg;
}
}
AJAX.send(passData);
}
}
//First Function
function showContent(url,arg,opr,sel_id,div_id)
{
var postData='';
var formVal=arg.split('|');
if(document.getElementById(div_id))
document.getElementById(div_id).style.display='';
if(document.getElementById(sel_id))
document.getElementById(sel_id).style.display='';
for(i=1;i<=formVal.length;i++)
var postData =postData + 'value'+i+'='+escape(formVal[i-1])+'&';
postData=postData + 'opr='+opr;
DataByPost(url,sel_id,postData,div_id);
}
I don't know exactly what is going on here without seeing the actual page, but a few things you might try:
Use jQuery to do your ajax since you're already using it. It is bug-free and cross platform, and that way you can be sure there are no bugs in the ajax part.
I would move the lines "var state = $("#state"); var stateInfo = $("#stateInfo");" inside of the function then declare the function outside of your document.ready block. That way you can be sure that every time the function gets called, it has access to the variables.
If your ajax call is replacing the input you're validating, you'll need to re-bind the events each time your ajax call finishes. With jQuery you can do this using the callback parameter.
I'm assuming number 3 is your problem, so try it first.