Data from response is symbols unable to set to iframe - javascript

I want to check if a response was successful from an Api and then put it in the iframe.
If I call it twice like this... it works.
function getPDF(fileDirectorGuid) {
if ($('#viewDownloadWindow').is(":visible")) {
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
success: function (data) {
if (data == null) {
alert("failed");
}
else {
$('#pdfFrame').attr('src', $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
}
however I don't want to call this twice and this doesn't work out like I thought
function getPDF(fileDirectorGuid) {
if ($('#viewDownloadWindow').is(":visible")) {
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
success: function (data) {
if (data == null) {
alert("failed");
}
else {
$('#pdfFrame').attr('src', data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
}
When viewing this in the debugger data looks like this
"%PDF-1.6
1 0 obj
<<
/Length 2 0 R
/Filter /FlateDecode
>>
stream
x��[�%Iv�wO�����H�|��8&`%ِږ8�.���D�J�h ��^of�Z�;wsj�g�<�4��O�X�Nq���c��������l����������7��?����>���S������4��>�y||��z�<J����Gݏ�c�?C����6�����?
so on and so forth.

The src attribute of an iframe is a url, you're setting the actual pdf data. You can use a blob url to achieve your goal
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
xhr:function(){
var xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function (data) {
if (data == null) {
alert("failed");
}
else {
var url = window.URL.createObjectURL(data);
$('#pdfFrame').attr('src', url);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});

Related

Setting up Ajax Promise

I have a function to add a record to database that uses Ajax with C# web service. Prior to updating DB I call another function to validate input that also uses Ajax. So, I need the validate function to finish before continuing with the one adding the record.
I know due to asynchronous nature of ajax I have to use promise/deferred but just can't get my head wrapped around it to set it up properly.
Updated
function validate() {
var deferred = $.Deferred();
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
}).done(function (result) {debugger
if (!result || result.d === "") {
isValid = false;
}
else {
var duplicate = JSON.parse(result.d);
switch (duplicate) {
case DuplicateData.Name:
isValid = false;
break;
case DuplicateData.ID:
isValid = false;
break;
}
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
deferred.resolve(isValid);
return deferred.promise();
//return isValid;
}
$(document).on("click", "#btnAdd", function (event) {debugger
$.when(validate())
.then(function(isValid) {
if (isValid) {
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
}).done(function (result) {
addNewRecord();
)}.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
}
})
});
function addNewRecord(){
// add record to DB
}
As you are only dealing with a boolean result, there is no reason to return a value, you can just resolve or reject the deferred.
function validate() {
var $defer = $.Deferred(function() {
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
})
.done(function (result) {
// If there's no result
if (!result || !result.d) {
$defer.reject();
}
else {
// This call shouldn't be necessary, as dataType: "json" will call it for you
// Unless you double-encoded it.
var duplicate = JSON.parse(result.d);
// Not sure about this part, what's DuplicatedData and what does result.d contain?
switch (duplicate) {
case DuplicateData.Name:
case DuplicateData.ID:
$defer.reject();
}
}
// Everything checks out, resolve the promise
$defer.resolve();
})
.fail(function (jqXHR, textStatus, errorThrown) {
// If there was a network or server error
// alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
$defer.reject();
});
});
return $defer;
}
$('form').on("click", "#btnAdd", function (event) {
validate()
.done(function() {
// If the validation passes
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
})
.done(function (result) {
// Creation successful
addNewRecord();
}).fail(function (jqXHR, textStatus, errorThrown) {
// Creation failed
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
})
.fail(function(reason) {
// Called in case of a validation error
console.log("Validation error");
});
});

Ajax Uncaught TypeError: Cannot read property 'length' of undefined

I want to populate my select box with json data from an external url.
I keep getting
Uncaught TypeError: Cannot read property 'length' of undefined
below is my json response
{"ecoachlabs":{
"status":"201",
"msg":"Form data loaded successfully.",
"categories":[
{"id":"2","category":"church"},{"id":"3","category":"financial institution"},
{"id":"4","category":"old students association"},
{"id":"1","category":"school"},
{"id":"5","category":"tertiary"}
],
"storage":[
{"id":"1","category":"100MB"},{"id":"2","category":"250MB"},
{"id":"3","category":"500MB"},{"id":"4","category":"2GB"},
{"id":"5","category":"3GB"},{"id":"6","category":"5GB"}
]
}}
below is my ajax post code
$(document).ready(function() {
$("#institution_category").click(function() {
var formData = {
load_request_form_data: "1"
}; //Array
$.ajax({
url: "http://api.ecoachlabs.com/v1/requests/api.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
console.log(data.ecoachlabs.categories); //data - response from server
$.each(data.categories, function(i, v) {
$('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
});
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
});
You do a console log of onsole.log(data.ecoachlabs.categories); and then use data.categories. Change data.categories to data.ecoachlabs.categories to parse the object correctly, otherwise you will get undefined. See the working snippet below please:
var formData = {
load_request_form_data: "1"
}; //Array
$.ajax({
url: "http://api.ecoachlabs.com/v1/requests/api.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
console.log(data.ecoachlabs.categories); //data - response from server
$.each(data.ecoachlabs.categories, function(i, v) {
$('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
});
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='institution_category'>
</select>
Check if exist before continue
if (!data || !data.length) return;
<script type="text/javascript">
$(document).ready(function() {
$("#institution_category").click(function(){
var formData = {load_request_form_data:"1"}; //Array
$.ajax({
url : "http://api.ecoachlabs.com/v1/requests/api.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
if (!data || !data.length) return; // data not always exist or not always contains ecoachlabs/categories
console.log(data.ecoachlabs.categories);//data - response from server
$.each(data.categories, function(i, v){
$('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
});
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
});
});
</script>

How to make the right yii2 validation manually?

It should be on the page where a list of users , open the modal window for editing . This page should not be updated . Clicking on the link opens a modal window ActiveForm after the data filled by AJAX. How can I transfer that is now id like to pass validation . With help yii.ActiveForms.js or something else?
public function actionEditUser($id) {
if (!Yii::$app->user->isGuest && Yii::$app->user->identity->role == 2) {
$model = new EditUserForm();
$model->id = (int) $id;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->updateUser()) {
return Yii::$app->response->redirect(Url::to(Yii::$app->request->referrer, true));
} else {
$user = $this->findModel($id);
$model->login = $user->login;
$model->email = $user->email;
$model->fullName = $user->full_name;
return $this->renderAjax('editModalUserForm', [
'model' => $model,
]);
}
}
return Yii::$app->response->redirect(Url::to('site/sign-in', true));
}
InitEditUser: function (event) {
var target = $(event.target);
var id = target.attr('id');
var url = 'http://' + window.location.hostname + '/users/' + id;
var urlGet = window.location.href;
$.ajax({
type: 'GET',
url: urlGet,
data: 'id=' + id,
success: function (data, textStatus, jqXHR) {
console.log('ok');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
$('#editUser').modal('show');
$.ajax({
type: 'GET',
url: url,
success: function (data, textStatus, jqXHR) {
console.log(data);
$('#editUserInput').val(data.login);
$('#editUserFullNameInput').val(data.full_name);
$('#editUserEmailInput').val(data.email);
$('#editUserForm').on('beforeSubmit', function () {
console.log("a");
return false;
});
$('#editUserForm').on('afterValidate', function () {
console.log("b");
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
},
};
InitEditUser: function (event) {
var target = $(event.target);
var id = target.attr('id');
var url = 'http://' + window.location.hostname + '/users/' + id;
var urlGet = window.location.href;
$.ajax({
type: 'GET',
url: urlGet,
data: 'id=' + id,
success: function (data, textStatus, jqXHR) {
console.log('ok');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
$('#editUser').modal('show');
$.ajax({
type: 'GET',
url: url,
success: function (data, textStatus, jqXHR) {
console.log(data);
$('#editUserInput').val(data.login);
$('#editUserFullNameInput').val(data.full_name);
$('#editUserEmailInput').val(data.email);
$('#editUserForm').on('beforeSubmit', function () {
console.log("a");
return false;
});
$('#editUserForm').on('afterValidate', function () {
console.log("b");
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
},
};

JavaScript Display Loader while Controller Response

Hi I have a JQuery Function that is calling a controller when
Controller Response (success()) it is loading an iFrame;
Basically; converter is returning success function after 30 seconds, for that reason I am trying to display a loading image using
beforeSend: function()
{
},
Function I tried a lots but its not working; Could you please give me advice how can I achieve it. My code are given bellow:
var callController = function (FirstName, documentId, fileName, packet) {
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&packet=" + packet,
cache: false,
async: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
event.preventDefault();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
}
});
};
you can show your loader right after or before $.ajax({...}) but you should never use async:false, this is the root of evil, it will freeze the browser while the request has not succeeded.
like this:
var callController = function (FirstName, documentId, fileName, SL) {
//here
showLoader();
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&SL=" + SL,
cache: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
//hide Here
hideLoader();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
//hide Here
hideLoader();
}
});
}

how to call javascript function from jQuery ajax?

I have jQuery ajax call to get results from the server, and in success, the code should call javascript function which is not in jQuery region code, so I got error in firebug: that the call of function doesnt have reference.
here is my code (see the ajax call in function addGMarker):
function test1234(res) {
PreInfo = res;
popupContentHTML = deviceMoreinfo_callBack_ForGoogle(PreInfo);
var sum = '<p>Please, Select <b>[Sensors Reading List]</b> tab to view vehcile sensors reading, and select <b>[Device Communication Commands]</b> tab to send commands for the device:</p><br/>';
var tabs = [
new MaxContentTab('Sensors Reading List', maxContentDiv),
new MaxContentTab('Device Communication Commands', maxContentDivForCommands)];
this.openMaxContentTabsHtml(map, popupContentHTML, sum, tabs, { maxTitle: "Sensors and Features" });
var iw = map.getTabbedMaxContent();
iw.id = this.id;
GEvent.addListener(iw, 'selecttab', function (tab) {
var node = tab.getContentNode();
switch (tab.getLabel()) {
case 'Sensors Reading List':
maxContentDiv.innerHTML = '<IMG SRC="../../../images/FullModeIcons/LoadingImage.gif" /> Loading...';
//GetSensorsReading(this.id, ClientID, "En", GetSensorsReading_CallBack);
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/GetSensorsReading",
data: "{Device_ID: '" + this.id + "', ClientID: '" + ClientID + "', Page_ID: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
GetSensorsReading_CallBack(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
break;
case 'Device Communication Commands':
maxContentDivForCommands.innerHTML = '<IMG SRC="../../../images/FullModeIcons/LoadingImage.gif" /> Loading...';
//GetContorolableSensors(this.id, ClientID, "En", GetContorolableSensors_CallBack);
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/GetContorolableSensors",
data: "{Device_ID: '" + this.id + "', ClientID: '" + ClientID + "', Page_ID: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
GetContorolableSensors_CallBack(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
break;
}
});
}
function addGMarker(ID, point, Marker_Icon) {
icon = new GIcon(G_DEFAULT_ICON);
if (_IconClientID == "0") {
if (Marker_Icon == "blue") {
if (ID == FollowVechicleID) {
icon.image = "../../Images/Icons/" + _Follow_Icon;
}
else {
icon.image = "../../Images/Icons/" + _Normal_Icon;
}
if (ID == FollowVechicleID) {
ShowLastThreePositions();
}
}
else {
icon.image = "../../Images/Icons/" + _Speed_Icon;
}
}
else {
if (Marker_Icon == "blue") {
if (ID == FollowVechicleID) {
icon.image = "../../Images/Icons/ClientsIcons/" + _Follow_Icon;
}
else {
icon.image = "../../Images/Icons/ClientsIcons/" + _Normal_Icon;
}
}
else if (Marker_Icon == "red") {
icon.image = "../../Images/Icons/ClientsIcons/" + _Speed_Icon;
}
}
icon.iconSize = new GSize(32, 32);
icon.dragCrossSize = new GSize(0, 0);
icon.shadowSize = new GSize(32, 32);
icon.iconAnchor = new GPoint(5, 5);
marker = new GMarker(point, icon);
marker.id = ID;
GEvent.addListener(marker, 'click',
function() {
popupContentHTML = Device_Option_forGoogle(this.id);
this.openInfoWindowHtml(popupContentHTML);
}
);
GEvent.addListener(marker, 'mouseover',
function() {
//PreInfo = getDeviceInfoForPopUp(this.id, ClientID, "En");
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/getDeviceInfoForPopUp",
data: "{deviceID: '" + this.id + "', IDclient: '" + ClientID + "', Page: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
test1234(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
});
var markers = [];
markers.push(marker);
mgr.addMarkers(markers, 0);
mgr.refresh();
ClientPOI.refresh();
POImgr.refresh();
}
It's the same code for calling Javascript function from jQuery. It's working fine. The problem is elsewhere in your code.
This might not be the exact solution, but given not to divert from the solution.
function test1234(res) {
alert(res)
}
function Test() {
jQuery.ajax({
type: "POST",
url: "/TestWebApp/ProcessServlet.do",
success: function (res) {
alert(res);
test1234(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
}

Categories

Resources