Submit issues with form that interact with an API - javascript

I have a form that interacts with an API, I used a simple auto submit:
<script type="text/javascript">
window.setTimeout(function(){
document.getElementById('formSubmit').submit();
},1000*20);
</script>
and it worked great in the testing environment. We moved into a new environment and the setup of the hardware was slightly different, realized that didn't work and altered it. Now my auto submit isn't working. The API developers suggested I use watchdog instead so I applied a code according from #Drakes and modified it to interact with my application. This also did not work. I am a noob with Watchdog, and most things in the development world, did I skip a set up with watchdog that wasn't referenced in the previous question?
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
setInterval(function(){ watchdog(); }, 20000);

I think you haven't posted the field values [Fields of the form]. The AJAX code you have used is checking if some value got changed or not every 20 second. But as much as I can understand you wanted to submit your form every 20 second. In that case the AJAX post code need some editing. May be the following thing can solve your problem. Here I am assuming your form having two fields and hence two values are getting submitted. If you have more then you have to modify it as per your requirement.
EDITED MY TESTCODE (This is tested)
The html code along with the AJAX script is as follows -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
function watchdog(value1,value2) {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// write any code as this block will be executed only after form succesfully submitted.
document.getElementById("showresponse").innerHTML = xmlhttp.responseText;
console.log(xmlhttp.responseText);// You can use this responseText as per your wish
}
}
xmlhttp.open("POST","process.php?value1="+value1+"&value2="+value2,true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
window.setInterval(function(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
// thus store all required field values in variables ,
//here as instance I am assuming the form has two fields , hence posting two values
watchdog(value1,value2);
}, 20000);
function submitIt(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
watchdog(value1,value2);
}
</script>
</head>
<body>
<form id="formSubmit">
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<button type="button" onclick="submitIt();">Submit</button>
</form>
<div id="showresponse"></div>
</body>
</html>
The php code of process.php will be as follows -->
<?php
if(isset($_REQUEST['value1']) && isset($_REQUEST['value1']))
{
$value1 = $_REQUEST['value1'];
$value2 = $_REQUEST['value2'];
echo "Values are respectively : " .$value1." and ".$value2;
}
else
{
echo "Data not found";
}
?>
While testing the above code sample dont forget to keep both html and process.php files in same folder and then test it. The above shown "Run Code snippet" button will not show you any effect of the php code as it only runs html and javascript. So to test it properly you should keep it on some server - local or online .

Related

xmlhttp.open does not seem to do anything in MVC structure

I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.

Ajax watch database for changes and execute code

My goal is to more or less send out requests to a php file, giving it parameters like so;
<!DOCTYPE html>
<html>
<head>
<script>
function onsubmit()
{
var id = $_SESSION['user']['id'];
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
window.WhateverVariable = xmlhttp.responseText;
}
}
xmlhttp.open("GET","clientrequest.php?id="+id,true);
xmlhttp.send();
}
</script>
</head>
<body>
</body>
</html>
and keep sending out requests untill my php script returns x value, which will be passed into the window.WhateverVariable, and when the WhateverVariable is equal to 'x' I wish to execute some code;
however, I can achieve this, but when the code is executed, the request is still going meaning the response text will be 'x' and will continuously destroy then re-execute the code, any way to get past this?
if ( the_mini_game_is_not_open() )
{
// send the regular ajax request
} else {
// send the ajax request but with the message that the mini game is open through parameters maybe like ?open=1
}
And on server side deal with this like:
if ( isset ( $_GET['open'] ) && $_GET['open'] === 1 )
{
// pause it or whatever...
} else {
// show the regular results
}
This was what I understood. Sorry if that's not what you want

Insert Javascript Code into HTML from PHP response [duplicate]

This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Hi I am trying to insert a JavaScript code in my HTML document using the following AJAX-PHP code inside the function called exJS(), following is the content of the function exJS()
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
This what ajax.php is
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
Now whenever I execute this function exJS() the alert doesn't work but when I view the source code using F12 and see the contents of the div#myDiv" I see that the entire script is embedded inside the div but still the JavaScript for some reason is not getting registered.
I even tried accessing the JavaScript variable testVAR, I see the variable in the source code when I hit F12 but when I try to access that variable I get an error, that no such variable is defined.
Please note that it is simple example so there is no error and that the PHP code is echoing just fine, all the contents are returned from the PHP code, when I view the code and see what are the content of the div element the entire PHP echo content is present there but still not executing.
Also if I open the ajax.php file directly it works fine, I mean I get the alert message, but the same thing doesn't happen when I execute the function jsEx() the JavaScript code gets inserted into myDiv but nothing happens, no alert.
BTW jQuery has a specific AJAX function to get a script: http://api.jquery.com/jquery.getscript/
If you want to avoid jQuery a workaround would be to make it so you echo an iframe and from that Iframe you link to the PHP generating the actual Javascript.
E.G. a sample ajax.php
if( isset($_GET['getscript']) ){
header('Content-type: application/javascript'); #or header('Content-type: text/javascript');
echo 'alert("The script is working.")';
exit;
}
echo '<iframe src="ajax.php?getscript=1" frameborder="0"/>';
?>
try this:
tested in my WAMP (win 7, php 5.4) & works fine in IE11,Chrome,Safari,FireFox and Opera (I don't have any other ;-) )
index.html:
<head>
<title>Testing DYNAMIC JS</title>
<script type="text/javascript">
function exJS(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var script = document.createElement('script');
script.onload = function() {
// alert("Script loaded and ready");
};
script.setAttribute("type","text/javascript");
script.text = xmlhttp.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
}
</script>
</head>
<body onload="exJS();">
</body>
</html>
in ajax.php try:
<?php
echo 'alert("Hello World"); var testVAR = "Hello World";';
?>
if you want to run script from within a div:
use:
javaScript:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var MyDiv=document.getElementById("myDiv");
var arr = MyDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML);
}
and php:
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
hope it'll help you.

XMLHttpRequest returns no response & XML error

I am trying to submit XML data using XMLHttpRequest to an external API which returns response as XML.
I have written the following code but it is not getting any response. Though I am getting 200 http response. In Firebug i get response tab empty while the XML tab shows me this error "XML Parsing Error: no element found Location: moz-nullprincipal"
Can anyone please point the problem, I am running it on my local machine. Below is my complete code.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
var data;
data='<?xml version="1.0" encoding="utf-8" ?>';
data=data+'<LeadImportDatagram>';
data=data+'<CompanyKey>302455</CompanyKey>';
data=data+'<LeadInfo>;'
data=data+'<Category>Gutters Drains</Category>';
data=data+'<Subcategory>Broken Gutter Repair</Subcategory>';
data=data+'<OfferName>First month free with one year contract</OfferName>';
data=data+'<Contact>Graham Carpenter</Contact>';
data=data+'<Company>Union Boxing Company</Company>';
data=data+'<Address>34 Railroad Rd.</Address>';
data=data+'<Address2></Address2>';
data=data+'<City>Newark</City>';
data=data+'<State>DE</State>';
data=data+'<Zip>34852</Zip>';
data=data+'<Country>United States</Country>';
data=data+'<Phone>800-842-2345</Phone>';
data=data+'<PhoneExt>113</PhoneExt>';
data=data+'<AltPhone>315-342-5468</AltPhone>';
data=data+'<AltPhoneExt></AltPhoneExt>';
data=data+'<Mobile>315-985-4984</Mobile>';
data=data+'<MobileExt></MobileExt>';
data=data+'<Fax>800-842-2346</Fax>';
data=data+'<FaxExt></FaxExt>';
data=data+'<EMail>graham#unionboxing.com</EMail>';
data=data+'<PotentialValue>900</PotentialValue>';
data=data+'<Comment>We are looking for a reliable and prompt pest control provider.</Comment>';
data=data+'<SourceCode>LEADFCTRY</SourceCode>';
data=data+'<SourceDescription>Lead Factory Lead Distributors</SourceDescription>';
data=data+'<SourceType>1</SourceType>';
data=data+'<SourceClassCode>AGGREGATOR</SourceClassCode>';
data=data+'<SourceClassDescription>Service Aggregators</SourceClassDescription>';
data=data+'<TimeRange>9am-5pm</TimeRange>';
data=data+'<SEligibleDate>10/1/08</SEligibleDate>';
data=data+'<EEligibleDate>10/31/08</EEligibleDate>';
data=data+'<LeadCost>27.00</LeadCost>';
data=data+'<ProviderID>9843</ProviderID>';
data=data+'<Questions>';
data=data+'<QuestionNode>';
data=data+'<Question>Have you previously had service done by Ace Pest Control?</Question>';
data=data+'<Answer>No</Answer>';
data=data+'</QuestionNode>';
data=data+'<QuestionNode>';
data=data+'<Question>Are you currently receiving service from any other pest control operator?</Question>';
data=data+'<Answer>No</Answer>';
data=data+'</QuestionNode>';
data=data+'<QuestionNode>';
data=data+'<Question>When was the first time you noticed your pest problem?</Question>';
data=data+'<Answer>We first noticed the problem in July 2006 when we saw damage to one of the walls in the basement.</Answer>';
data=data+'</QuestionNode>';
data=data+'</Questions>';
data=data+'</LeadInfo>';
data=data+'</LeadImportDatagram>';
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
//xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp=new ActiveXObject("MSXML2.ServerXMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
alert("Ready state: "+xmlhttp.readyState)
alert("Status: "+xmlhttp.status)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseXML;
} else if (xmlhttp.status==404) {
alert("XML could not be found");
}
}
xmlhttp.open("POST","http://www80.mypestpac.com/xml/importlead.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-type","text/xml");
xmlhttp.send(data);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
data='<?xml version="1.0" encoding="utf-8" ?>';
data=data+'<LeadImportDatagram>';
data=data+'<CompanyKey>302455</CompanyKey>';
data=data+'<LeadInfo>;'
Line 13 has to be
data=data+'<LeadInfo>';
instead of
data=data+'<LeadInfo>;'
That is causing the XML error you get.

Problem with Sending XML Requests

Writing a basic XML file reader into an HTML page. I am having trouble reading from the XML file. Here's my set up: I have three text fields and a button. When the button is pressed, the request is put in to grab three pieces of XML and to populate the three text fields. However, I am running into trouble with the status of the request. I am getting the status code 0, instead of 200. According to my research (http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/282972), I think it has to do with cross domain blocking. I have tried putting the source XML both locally and on a server.
<html>
<head>
<script type="text/javascript">
function displayQuotes()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
//if (xmlhttp.readyState==4 && xmlhttp.status==200)
//{
document.getElementById("quote1").innerHTML=xmlhttp.status;
  //}
}
xmlhttp.open("GET","http://filebox.vt.edu/users/yiuleung/project5/letter.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("quote1").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("quote2").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("quote3").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body>
<div id="quote1" style="margin:0;padding:0;position:absolute;left:65px;top:319px;width:250px;height:16px;text-align:left;z-index:2;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 1</font></div>
<div id="quote2" style="margin:0;padding:0;position:absolute;left:65px;top:389px;width:250px;height:16px;text-align:left;z-index:3;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 2</font></div>
<div id="quote3" style="margin:0;padding:0;position:absolute;left:65px;top:458px;width:250px;height:16px;text-align:left;z-index:4;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 3</font></div>
<input type="button" id="shuffle_button" name="" value="Shuffle" onClick=displayQuotes() style="position:absolute;left:316px;top:228px;width:96px;height:25px;font-family:Arial;font-size:13px;z-index:10">
</body>
</html>
You use xmlhttp.open("GET","letter.xml",true); - it open XMLHttpRequest in async mode. But next two lines of your code expected to work in sync mode. You need to switch to sync mode: xmlhttp.open("GET","letter.xml",false); or (better) to modify code for work in async mode, as in example below:
function displayQuotes()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","letter.xml",true);
xmlhttp.onreadystatechange=function() {
console.info(xmlhttp.readyState,"|",xmlhttp.status,"|",xmlhttp.statusText); // for debugging only
if(xmlhttp.readyState===4&&xmlhttp.status===200) {
// HTTP OK
xmlDoc=xmlhttp.responseXML; // maybe var xmlDoc ???
document.getElementById("quote1").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("quote2").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("quote3").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
};
xmlhttp.send(null);
}
Using XMLHttpRequest in MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Categories

Resources