I've figured out that to be able to send data cross-domain in Internet Explorer I should use the XDomainRequest.
By doing so I stumbled upon the next issue. I'm sending data from HTTP to HTTPS which gives the error SCRIPT5: Access is denied.. I tried adding header("Access-Control-Allow-Origin: *"); to the designated PHP file with no result.
Is there any way around this problem wherein I can send data from my HTTP domain to my HTTPS domain in Internet Explorer 9+?
The code I'm using right now(Which gives the script5 error):
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(); // Use Microsoft XDR
xdr.open('get', url);
xdr.onload = function () {
var dom = new ActiveXObject('Microsoft.XMLDOM'),
JSON = $.parseJSON(xdr.responseText);
dom.async = false;
if (JSON == null || typeof (JSON) == 'undefined') {
JSON = $.parseJSON(data.firstChild.textContent);
console.log(JSON);
}
successCallback(JSON); // internal function
};
xdr.onerror = function() {
_result = false;
};
xdr.send();
}
I also tried adding $.support.cors = true; with no result.
Answering my own question:
I've fixed it by using JSONP:
$.ajax({
url: url,
data: thedata,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallbackFunc',
success: function (response) {
}
});
Related
Hey guys I am using vuejs and ajax to send formData and return a json response. There's a json response comes though however I cant assign it to the vue data object. Any ideas as to why? Heres my method. I know the function is firing as it hits the other page and returns json data in the console. Message, nameExists, and error wont assign even though all our in the vue data property and is spelled correctly.
addTemplate: function() {
this.sub = true;
this.itemName = this.itemName.trim();
var addTemplateForm = document.getElementById("addTemplateForm");
var fd = new FormData(addTemplateForm);
if (this.validItemName == true /* etc...*/) {
$.ajax({
url:'addTemplateBackend.php',
type:'POST',
dataType: 'json',
data: fd,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
error: function(data){
this.message = data.message;
alert('error');
},
success: function(data){
alert('success');
this.error = data.error;
this.message = data.message;
console.log(data);
this.nameExists = data.nameExists;
if(data.success == true){
$('#successModal').modal('show');
}
}
});
}
}
You need to either bind this:
success: function (data) {
this.message = data.message;
}.bind(this)
or use ES6 "fat arrow" syntax:
success: data => {
this.message = data.message;
}
See How does the "this" keyword work?.
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.
Things tried:
commented lines regarding webdav
edited iis config file i.e added PUT,DELETE verbs
jQuery .support.cors = true;
Error: 405: method not allowed (in chrome debugger)
response is going to ajax error.
ajax call code:
jQuery.support.cors = true;
function CheckLogin() {
var user = { "UserName": $('#UserName').val(), "Password": $('#Passsword').val() };
user = JSON.stringify(user);
$.ajax({
url: 'http://localhost/MvcRazorClient/api/HomeApi/SignIn',
//here i changed the webapi route to api/controller/action
type: "PUT",
data: user,
async: false,
crossDomain: true,
contentType: "application/json",
dataType: 'json',
success: function (data) {
if (data == true) {
alert('true')
} else {
alert('false');
}
},
error: function () {
alert('er');
}
});
}
my api controller code:
[HttpPut]
public bool SignIn(User u)
//here i tried parameters as "dynamic u" and "HttpRequestMessage u". nothing worked
{
return true;
}
help please.
i didnt disable webDAV in iis .
path: Control Panel\All Control Panel Items\Programs and Features->iis->world wide web services->Common Http Features->(uncheck) webDAV
Below code is in my website:
function validateRequest() {
var $form = $('form');
if ($form.valid()) {
$.support.cors = true;
var lnkey = $('#txtloan').val();
var psw = $('#txtpsw').val();
var loanServiceUrl = #Html.Raw(Json.Encode(ConfigurationManager.AppSettings["LoanServiceURL"]));
var msg = {"loan": lnkey, "psw": psw};
$.ajax({
cache: false,
async: true,
type: "POST",
url: loanServiceUrl + "ValidateRequest",
data: JSON.stringify(msg),
contentType: "application/json; charset=utf-8",
dataType: "json", //jsonp?
success: function (response) {
$(response).each(function(i, item) {
if (item.Validated.toString().toUpperCase() == 'TRUE') {
// When validation passed
$('#divResult').load('#Url.Action("GetLoanInfo", "Validate")');
$("#btnClearStatus").show();
$('#btnGetStatus').hide();
}
});
},
error: function (errormsg) {
alert("ERROR! \n" + JSON.stringify(errormsg));
}
});
}
}
I have set following setting in IIS where my service is deployed.
When I make a POST call from website, I see two calls (probably one is pre-flight call for CORS) in fiddler. This is working fine in chrome and Safari but not in Firefox. I get HTTP 405 error. I am using Firefox 21.0.
Below is the snap shot from fiddler when service is called from firefox.
I'm using Matt Diamond's recorder.js to navigate the HTML5 audio API, and feel this question probably has an apparent answer, but i'm unable to find any specific documentation.
Question: After recording a wav file, how can I send that wav to the server via ajax? Any suggestions???
If you have the blob you'll need to turn it into a url and run the url through an ajax call.
// might be nice to set up a boolean somewhere if you have a handler object
object = new Object();
object.sendToServer = true;
// You can create a callback and set it in the config object.
var config = {
callback : myCallback
}
// in the callback, send the blob to the server if you set the property to true
function myCallback(blob){
if( object.sendToServer ){
// create an object url
// Matt actually uses this line when he creates Recorder.forceDownload()
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create a new request and send it via the objectUrl
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "blob";
request.onload = function(){
// send the blob somewhere else or handle it here
// use request.response
}
request.send();
}
}
// very important! run the following exportWAV method to trigger the callback
rec.exportWAV();
Let me know if this works.. haven't tested it but it should work. Cheers!
#jeff Skee's answer really helped but I couldn't grasps it at first, so i made something simpler with this little javascript function.
Function parameters
#blob : Blob file to send to server
#url : server side code url e.g. upload.php
#name : File index to reference at the server side file array
jQuery ajax function
function sendToServer(blob,url,name='audio'){
var formData = new FormData();
formData.append(name,blob);
$.ajax({
url:url,
type:'post',
data: formData,
contentType:false,
processData:false,
cache:false,
success: function(data){
console.log(data);
}
}); }
Server side code (upload.php)
$input = $_FILES['audio']['tmp_name'];
$output = time().'.wav';
if(move_uploaded_file($input, $output))
exit('Audio file Uploaded');
/*Display the file array if upload failed*/
exit(print_r($_FILES));
I also spent many hours trying to achieve what you are trying to do here. I was able to successfully upload the audio blob data only after implementing a FileReader and calling readAsDataURL() to convert the blob to a data: URL representing the file's data (check out MDN FileReader). Also you must POST, not GET the FormData. Here's a scoped snippet of my working code. Enjoy!
function uploadAudioFromBlob(assetID, blob)
{
var reader = new FileReader();
// this is triggered once the blob is read and readAsDataURL returns
reader.onload = function (event)
{
var formData = new FormData();
formData.append('assetID', assetID);
formData.append('audio', event.target.result);
$.ajax({
type: 'POST'
, url: 'MyMvcController/MyUploadAudioMethod'
, data: formData
, processData: false
, contentType: false
, dataType: 'json'
, cache: false
, success: function (json)
{
if (json.Success)
{
// do successful audio upload stuff
}
else
{
// handle audio upload failure reported
// back from server (I have a json.Error.Msg)
}
}
, error: function (jqXHR, textStatus, errorThrown)
{
alert('Error! '+ textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
// handle audio upload failure
}
});
}
reader.readAsDataURL(blob);
}
Both solutions above use jQuery and $.ajax()
Here's a native XMLHttpRequest solution. Just run this code wherever you have access to the blob element:
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, "filename");
xhr.open("POST","upload.php",true);
xhr.send(fd);
Server-side, upload.php is as simple as:
$input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav"; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
move_uploaded_file($input, $output)
source | live demo