I am having difficulties getting access to the values that I am sending to an ASP file from an HTML file. I am attempting to use AJAX POST method to send 3 values to a database and insert them, but to no avail.
Here is the .html code to send the values:
// Builds AJAX request and sends it to ASP page
function sendInfo(x,y,z){
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=stateChanged;
xmlhttp.open("POST","UpdateAJAX.asp",true);
xmlhttp.send("addy="+(x)+
"&lat="+(y)+
"&lng="+(z));
}
// Checks the ready state of the sent response
function stateChanged() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
else {
document.getElementById("txtHint").innerHTML="Error with ready state: " + xmlhttp.readyState + " and status: " + xmlhttp.status;
}
}
And here is the 'UpdateAJAX.asp' code:
<%
conn = Server.CreateObject("ADODB.Connection");
conn.Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" + Server.MapPath("Project.mdb"));
' var addy = Request.QueryString("addy");'
' var lat = Request.QueryString("lat");'
' var lng = Request.QueryString("lng");'
var addy = Request.Form("addy");
var lat = Request.Form("lat");
var lng = Request.Form("lng");
var sql="INSERT INTO Location_Info (Address,Latitude,Longitude)"
sql= sql + " VALUES "
sql= sql + "('" + addy + "',"
sql= sql + "'" + lat + "',"
sql= sql + "'" + lng + "')"
Response.Write(sql);
rs = conn.Execute(sql);
Response.Write("Your record has been placed into the database.");
conn.Close();
%>
I have tried both the Request.Form and Request.QueryString methods to retrieve the values from the send, but nothing gets returned. When I use Firefox Firebug to debug the code, this is what is being sent:
'addy=1232 Randall Avenue, Hammond, LA 70403, USA&lat=30.4545509&lng=-90.49790769999998'
It doesn't parse it into the individual variables either way I try and only returns error status of 500, which I have also debugged to mean:
'Data type mismatch in criteria expression.'
When attempting to send the sql statement, as the values are all undefined.
If someone can provide any advice as to how to get the values into the variables, it would be greatly appreciated.
You need to set the Content-Type header of your http request to application/x-www-form-urlencoded. Before you call xmlhttp.send(...), add this line:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Related
This Ajax is sending some data to php file and getting back the response that is showed in my html. Everything is working fine but sometimes I have been getting Error 500 response from php file. I know why and it is ok because as you can see after error 500 I'm calling the Ajax function again.
My question is. Is it possible to return from php file also some data after getting error 500? By data I mean variable returned from php file when the error occured.
function tr() {
var vysledok = document.getElementById('vysledok_body');
var text= document.getElementById('source').value;
var languageFrom = document.getElementById("src").value;
var languageTo = document.getElementById("dst").value;
vysledok.innerHTML="";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', "https://.... someurl.php?
from=" + languageFrom + "&to=" + languageTo + "&text=" + text, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
console.log(obj.ip);
vysledok.innerHTML = "<p class='bdr'>"+obj.text+"</p>";
}
if(xmlhttp.status == 500) {
//console.log('nejde');
tr();
}
}
};
xmlhttp.send(null);
}
That depends entirely on what is causing the error. What you can do is catching the error if it is caused by an exception and in the catch block handle it the way you want.
For example you can return a value in the catch block and set the response code to 500 from PHP.
If however your script crashes with a fatal error that is not handled you can't change the return value there, but could still configure your web server to deliver a custom error page that can be read by your JS.
I am trying to do http GET request for a MS flow using XMLHttpRequest in java script but getting the above error.
I know this is because of the url.Can anyone help me what is the exact issue with my url.
var finalurl = "https://prod4-30.centralindia.logic.azure.com:443/workflows/ed30ad9219a940fa8e5af317cf697e4c/triggers/manual/paths/invoke?api-version=2016-06-01&sp=/triggers/manual/run&sv=1.0&sig=ctQe3OAscgTfzDgji9gS_B43lvHEV4JP-hGdaxu46wg";
function DohttpRequest(greeting) {
alert(greeting);
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', '" + finalurl + "', false);
xmlHttp.send(null);
var jsonResponse = JSON.parse(xmlHttp.responseText);
console.log(jsonResponse);
alert(xmlHttp.responseText);
}
I am doing the GET request in sharePoint using the custom action. The definition of the custom action with CommandAction is as below
UserCustomAction SPToDBAction = collUserCustomAction.Add();
SPToDBAction.Location = "CommandUI.Ribbon.ListView";
SPToDBAction.Sequence = 10001;
SPToDBAction.Title = "SPToDBAction";
string location = "<CommandUIDefinition Location=\"Ribbon.ListItem.Actions.Controls._children\">";
SPToDBAction.CommandUIExtension = #"<CommandUIExtension><CommandUIDefinitions>"
+ location
+ "<Button Id=\"InvokeAction.Button\" TemplateAlias=\"o1\" Command=\"EditFormButtonCommand\" CommandType=\"General\" LabelText=\"Sync SP To DB\" Image32by32=\"data:image/png;base64,iVB= \" />"
+ "</CommandUIDefinition>"
+ "</CommandUIDefinitions>"
+ "<CommandUIHandlers>"
//+ "<CommandUIHandler Command =\"EditFormButtonCommand\" CommandAction = \"javascript:alert('Custom List ECB custom Action')\" />"
+ "<CommandUIHandler Command =\"EditFormButtonCommand\" CommandAction = \"javascript:DohttpRequest('Are you sure to sync the Items from Sharepoint to Database'); function DohttpRequest(greeting){ alert(greeting); var xmlHttp = new XMLHttpRequest(); xmlHttp.open( 'GET', '" + finalurl + "', true ); xmlHttp.send( null ); var jsonResponse = JSON.parse( xmlHttp.responseText); console.log(jsonResponse); alert( xmlHttp.responseText);}\" />"
+ "</CommandUIHandlers></CommandUIExtension>";
SPToDBAction.Update();
Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.
With asynchronous request you need to wait for server answer, for do that you need to work with XMLHttpRequest onreadystatechange property, so in the end your function code will look like this...
function DohttpRequest(greeting) {
alert(greeting);
let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let jsonResponse = JSON.parse(this.responseText);
console.log(jsonResponse);
alert(this.responseText);
}
};
xmlHttp.open('GET', '" + finalurl + "', true);
xmlHttp.send();
}
Hope it helps...
I'm not sure why this is happening but I will try to explain as much as I already know.
I have a website that allows you to log in with an account stored on a database. Each user can update their own set of data that is also in the same database.
When a user changes data Javascript will post an XMLHttpRequest to a php file on the server. The data is JSON encoded and is decoded in the php file and then stores the data on the database.
The problem is whenever I log into a specific account no data is sent. The string is empty after the request is sent. The post works and the php file runs but no data is present. Here is my code for sending the request in JS:
function sendXMLHttpRequest(data, phpfile){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.open('POST', phpfile, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (this.responseText !== null)
document.getElementById('saveresponse').innerHTML = xhr.responseText;
else
alert("Ajax error: No data received");
}else alert("Ajax error: " + this.status);
}
};
xhr.send(data);
}
On the php side:
session_start();
$mysql = new Mysql();
$data = json_decode($_POST['stringData']);
echo 'Data: ' . $data . "<br />";
Normally when I echo the data is returns Array which is what I want but it doesn't echo anything when ever I log into this one specific account, the data sent is just a string where stringData is a JSON. Is there a way to see if anything IS stored there? Also if nothing is being sent why could this be? Any suggestions for my code?
Make sure the request doesn't get cached by adding a random parameter:
querystring = 'validate=' + validate+ "&rand=" + new Date().getTime();
I am working on a web app that sends some data to a website. The website updates the data to its database and returns a json array that replaces my webapp page. I am using ajax for making the query. I need to know how to prevent the overwriting of my webpage. The server is not mine so there is possibly a same origin policy problem.
I have checked the xmlhttp.readystate and xmlhttp.status, they are 4 and 0 respectively. According to some posts on stackoverflow the 0 status occurs due to the origin policy but I couldn't get a solution for this because usually the people with this problem had access to changes on the server side programming.
I want to read the json and extract values for my app but if I use the xmlhttp.responseText the server returns a blank string.
Any help is much appreciated.
Thanks
My code:
function sendAndReceive() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
document.getElementById("postevent").innerHTML = "state changed";
document.getElementById("postevent").innerHTML = "" + xmlhttp.readyState + " " + xmlhttp.status;
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("postevent").innerHTML = "success response";
document.getElementById("postevent").innerHTML = "this is it" + xmlhttp.responseText;
}
}
var url = "http://simple.ap.ernet.in/api/home/resource.php/resource/node?";
url += "key=" + document.getElementById("key").value + "&";
url += "datasetId=" + document.getElementById("datasetId").value + "&";
url += "localId=" + document.getElementById("localId").value + "&";
url += "nodeName=" + document.getElementById("nodeName").value + "&";
url += "nodeDesc=" + document.getElementById("nodeDesc").value + "&";
url += "lat=" + document.getElementById("lat").value + "&";
url += "long=" + document.getElementById("long").value;
document.getElementById("postevent").innerHTML = url;
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
The only known workaround is to let the browser think there is only one origin. The easiest is to put a proxy on your own server relaying to the other server. If your own server is in Apache, you may use mod_proxy (see this question).
But note that if the other server doesn't allow cross-origin requests, it's probably against its policy to do that. And if it's a big server, it may very well detect it and ban your server's IP.
Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.