HTML5 Post Request Body - ajax

function sendPost(){
alert("IN SEND POST");
var username = document.myForm.username.value;
var password = document.myForm.password.value;
alert("username"+username);
alert("password"+password);
console.log("in java script");
var url = "some url";
alert("IN url SEND POST");
var data = "<MESSAGE><HEADER><LOGIN>005693</LOGIN></HEADER><SESSION><LATITUDE>0.0</LATITUDE><LONGITUDE>0.0</LONGITUDE><APP>SRO</APP><ORG>MNM</ORG><TRANSACTION>PRELOGIN</TRANSACTION><KEY>PRELOGIN/ID</KEY><TYPE>PRELOGIN</TYPE></SESSION><PAYLOAD><PRELOGIN><ID>005693</ID><USERNAME>005693</USERNAME><PASSWORD>tech#2014</PASSWORD></PRELOGIN></PAYLOAD></MESSAGE>";
console.log("2")
var req;
if(window.XMLHttpRequest) {
console.log("2");
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
}
else if(window.ActiveXObject) {
console.log("3");
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
console.log("4");
req.onreadystatechange=function()
{
console.log("5");
if (req.readyState==4 && req.status==200)
{
console.log("ready state accepted");
xmlDoc=req.responseXML;
console.log("xmlDoc"+xmlDoc);
alert("xmlDoc"+xmlDoc);
txt="";
x=xmlDoc.getElementsByTagName("FIRSTNAME");
y=xmlDoc.getElementsByTagName("LASTNAME");
console.log("Response achieved"+x);
}
}
req.open("POST",url,true);
console.log("6");
req.setRequestHeader("Content-type","application/xml");
req.send(data);
console.log("7");
return true;
}
I get a response in rest client perfectly as i Want as seen in image
In Google Chrome --> I get status as 0 and ready state as 1 and then 4
In Internet Explorer --> I get status as 200 OK and ready state goes from 1 , 2, 3, 4 but a blank xml is returned
In rest client I get a perfect hit and an xml is returned
I tried asking question in different ways but some say its a cross origin problem
If yes please lemme know the solution via code in javascript
Please guide

Firstly, I suggest rewriting your code with jQuery's help. This would compact your code, make it cross-platform, and easier to read and maintain:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function sendPost(){
$.ajax({
url: "some url",
type: "POST",
contentType: "text/xml",
data:
"<MESSAGE><HEADER><LOGIN>005693</LOGIN></HEADER>" +
"<SESSION><LATITUDE>0.0</LATITUDE><LONGITUDE>0.0</LONGITUDE>" +
"<APP>SRO</APP><ORG>MNM</ORG><TRANSACTION>PRELOGIN</TRANSACTION>" +
"<KEY>PRELOGIN/ID</KEY><TYPE>PRELOGIN</TYPE></SESSION>" +
"<PAYLOAD><PRELOGIN><ID>005693</ID>" +
"<USERNAME>" + $("#username").val() + "</USERNAME>" +
"<PASSWORD>" + $("#password").val() + "</PASSWORD>" +
"</PRELOGIN></PAYLOAD></MESSAGE>",
dataType: 'xml',
success: function(data) {
var firstname = $(data).find("FIRSTNAME").text();
var lastname = $(data).find("LASTNAME").text();
alert('Hello ' + firstname + ' ' + lastname);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
}
</script>
Secondly, a javascript that origins from your server (e.g. www.myserver.com) can't communicate with other servers (i.e. you can't request data from www.anotherserver.com). Well you CAN, but if so you'd need to ensure the answer sent from www.anotherserver.com would be in JSONP format - and then you would just change "dataType" in the example above to "jsonp" to be able to access the result like "data.firstname" and "data.lastname".
Anyway, in your case I would create a local proxy on my own webserver (in the same folder where you have the above .HTML-file) that would forward the request to the other server and return the result. Thus:
$.ajax({
url: "myproxy.php",
type: "POST", ...
And then in myprox.php, something like this (I'm just assuming PHP here, but this could be easily ported to ASP.NET or ASP Classic):
<?php
// myproxy.php forwards the posted data to some other url, and returns the result
$clientContext = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: text/xml; charset=utf-8',
'content' => http_get_request_body()
)
));
print file_get_contents("some url", false, $clientContext);
?>
To clarify: This would make your HTML-page talk to myproxy.php (which lives on the same server [even in the same directory]), then myproxy.php talks to the server at "some url" which returns the data to myproxy.php, which in it's turn returns the data to your script.
Best of luck!

The server says it is sending text/plain data, not XML, so the browser won't populate req.responseXML. The data should be in req.responseText.

I'm not sure but can you please add a semicolon (;) at the end of the line below. There is a possibility that it doesn't work because of missing semicolon.
console.log("2")
change to
console.log("2");

Related

Charisma V.2.0.0 bundle in ASP.Net Ajax error

I've integrated the Charisma V.2.0.0 bundle in an ASP.Net C# application. All looks good until I write an .ajax call to a web service. Ajax call, a standard format, works in a basic asp.net page, but from the bundle. It seems like something in his 'bower_components'. I removed reference to bower_components/jquery and am including ajax.googleapis.com... 3.3.1.
Does anyone have experience with this problem? and what might be a solution? I like the UI Muhammad designed and would like to keep developing which is platform.
The axax call looks like this:
// Edit Client button
$(document).on("click", "[id*=btnEditClient]", function () {
// Edit selected client/Event Id - get data from Ajax
//alert($(this).val());
var clientId = $(this).val();
var clientInfo = JSON.stringify({ clientId: clientId });
alert(clientInfo);
$.ajax(
{
url: '<%= ResolveUrl("QRWebService.aspx/GetClientListService") %>',
type: "POST",
data: clientInfo,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// results
alert(result.d);
alert('no error ' + JSON.stringify(result));
$("#myModal").modal()
return true;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus);
}
});
return false;
})
and the result is 'undefined' where the web service never gets called.
The web serivce is:
[WebMethod]
public static DataSet GetClientListService()
{
// returns dataset LIST of Client Id and Name
DataSet ds = new DataSet();
SQLHelper.SqlQuery oQuery = new SQLHelper.SqlQuery();
String strSQL;
try
{
strSQL = "SELECT Clients.ClientId, ClientName FROM Clients ";
strSQL += "WHERE ClientActive=#clientActive";
ds = oQuery.GetDataSet(strSQL);
} catch(Exception ex){
errorMessage = ex.Message;
}
return ds;
} // end GetClientEventList()
Post ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)". Changing the App_Start from Permanent to:
settings.AutoRedirectMode = RedirectMode.Off;
did the trick. I hope this helps others. Thank you StackOverflow and all those who post solutions to tricky issues.

Accept application/pdf in Ext.Ajax.request

I am using Ext.Ajax.request() to make an API call which produces MediaType.MULTIPART_FORM_DATA. This is being handled in the php layer which returns the object in
header("Content-Type: application/pdf");
echo $response;
The problem is, I am not able to handle the received object in the Ext.Ajax.request() since it always handles only Json objects by default.
I tried giving Headers, AcceptType in the request, but it always goes to the failure block.
Here is the code:
Ext.Ajax.useDefaultXhrHeader = false;
var responseText;
Ext.Ajax.request({
url: '/index.php/abc/xyz?value=' + value,
method: 'GET',
waitMsg: 'Printing Label',
contentType: 'application/octet-stream' //not sure,
responseType: 'blob' //not sure,
xhr2: false //not sure,
success: function (response) {
console.log("Success!!");
return "";
},
failure: function (response) {
//Always comes here. The API returns 200
console.log("Hi here in the error");
//Raw pdf gets printed
console.log(response.responseText);
}
});
but it always goes to the failure
For this you need to check in php side because may be something you have missed. I think may be this will help you readfile
Try with this code. Hope this will help/guide you to get required result.
Ext.Ajax.request({
url: '/index.php/abc/xyz?value=' + value,
method: 'GET',
waitMsg: 'Printing Label',
cors: true,
useDefaultXhrHeader: false,
withCredentials: true,
defaultHeaders: {
'Content-Type': 'application/octet-stream;'
},
timeout:0,//If don't know how time will take server to get the file then you can put 0. if you need
success: function(response) {
//In response you will directly get the octet-stream
//For showing pdf in front end side using blob url
var byteCharacters = atob(response.responseText),
len = byteCharacters.length,
byteNumbers = new Array(len),
key = 0,
byteArray,
blob,
contentType = 'application/pdf';
//insert charcter code in {byteNumbers}
for (; key < len; key++) {
byteNumbers[key] = byteCharacters.charCodeAt(key);
}
//convert {byteNumbers} into Uint8Array
byteArray = new Uint8Array(byteNumbers);
//create blob using {byteArray}
blob = new Blob([byteArray], {
type: contentType
});
// set {src} to {iframe}
window.open(window.URL.createObjectURL(blob), '_blank');
},
failure: function(response) {
//if somthing wrong in serverside then it will come in failure.
}
});
Hope this will also help you for this question as well.

Joomla mootools Ajax request always returning response text suffixed by '[]'

I am having a peculiar problem. I am trying to validate some card numbers using AJAX. Entire process goes fine and I am getting response from the script as expected. But I am not sure why all the response texts (even if it is an empty string) will show a [] suffixed to it when I alert it on my javascript. If I give an alert directly from the javascript, it shows fine. But all the responses from AJAX gives the above mentioned output.
Can anyone give me a clue why this is happening? I might have done something stupid in my code... but not able to figure out what... Any inputs will be highly appreciated.
Thanks in advance
EDIT:
Javascript Code:
var url = '" . JURI::base() . "index.php?option=<component>&view=<view>&format=raw&task=<task>';
var a = new Request({
url: url,
data: {
'".JUtility::getToken()."': 1
},
method: 'post',
onSuccess: function(responseText) {
alert(responseText);
},
onFailure: function(xhr) {
alert('Failed');
}
}).send();
PHP Script on view.raw.php
<?php echo "Here"; ?>
This script when run, will throw the alert message as "Here[]"
---- RENDERED JAVASCRIPT CODE ---
window.addEvent('domready',function() {
if($('addpluspayment')) {
$('addpluspayment').addEvent('click', function(event) {
bbCardNum = $('bbpluscardpayment').value;
if(bbCardNum.length <= 0) {
alert('Número de tarjeta no válida');
return;
}
totalAmountToCheck = parseFloat($('taqPaymentAmount').value);
var url = 'http://mydomain.com/index.php?option=com_bbpayment&view=taqcart&format=raw&task=bbcheckpoints';
var a = new Request({
url: url,
data: {'5df1de004436f241ef112345035bab51':1,'totalAmountToCheck':totalAmountToCheck,'bbCardNum':bbCardNum},
method: 'post',
onSuccess: function(responseText) {
if(responseText == 'othercategories[]') {
alert('Entradas encontradas en otras categorías');
}
else {
alert(responseText);
}
},
onFailure: function(xhr) {
alert('Failed');
}
}).send();
});
}
});
Here, the alerts - 'Número de tarjeta no válida', 'Entradas encontradas en otras categorías' and 'Failed' (which are directly thrown from the javascript) comes up without any problems.. but all responseText alerts suffix a [], even if the PHP script echos just 'Hello' (which will throw the alert as 'Hello[]')

Joomla 2.5 Ajax component not working

I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back

jQuery Ajax Get Doesn't Pass Received Data Into Success Function at Internet Explorer

My question is when I use jQuery ajax get, I am getting data at response body however it doesn't pass into success function. How can I make it work?
I am making an ajax put but it doesn't work at ie9 (works on other browsers) so I changed it like that just for test:
$.ajax({
async : false,
type: 'PUT',
contentType: 'application/json',
url:updateUrl + "?_" + new Date().getTime(),
data: JSON.stringify(model),
cache: false,
dataType: "json",
dataFilter: function(data) {
var resp = eval('(' + data + ')');
return resp;
},
success: function(data, status, xhr) {
alert("success> " + data.property);
alert(typeof data);
r = resultResponse(data);
},
error: function(data, status, xhr) {
alert("error> " + data.responseText);
try {
r = error($.parseJSON(data.responseText));
} catch (err) {
//Handle error
}
}
});
data is alerting as undefined. My put data is sending correctly, my server side works well and send response to client however I get undefined instead of data. After some tests I realized the problem:
When I capture network communication packets at ie 9 response body is what I want. However success function can not handle it. If needed, I can give more information about my server(I could make it work when I write the data to response instead of using jackson json mapper at Java - it was working and the only difference was that was not included ta working version at response headers:
Key Value
Content-Type application/json;charset=UTF8 )
I think that the problem can be handle at client side, I think not with server side.
Any ideas?
EDIT: I tried that style:
$.ajax({url: "/url",
dataType: "text",
success: function(text) {
json = eval("(" + text + ")");
// do something with JSON
}
});
However response header is still:
Key Value
Content-Type application/json;charset=UTF8
The problem was wrong charset. It was UTF( instead of UTF-8).

Resources