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);
}
});
}
Related
The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}
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");
}
});
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) {
}
});
},
};
I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :
"use strict";
$(document).ready(function(){
function searchWikipedia(searchCriteria){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);
}
$('#btn').click(function searchCriteria() {
var searchCriteria = $("input[name=Wikipedia]").val();
searchWikipedia(searchCriteria);
})
function processResult(apiResult){
if (apiResult.query.pages[-1]){
console.log("No results");
} else {
for (var i = 0; i < apiResult.length; i++){
$('#display-result').append('<p>'+apiResult+'</p>');
}
}
}
});
So far nothing appends to my html and there's no errors in my console.
#Ali Mamedov's answer is the way to go (it's from Wikipedia)
But the wikipedia link is missing the http:. Also, you can handle the response on your function:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: processResult
});
});
});
function processResult(apiResult){
for (var i = 0; i < apiResult.query.search.length; i++){
$('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
}
}
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, item) {
if (i == 1) {
var searchData = item[0];
WikipediaAPIGetContent(searchData);
}
});
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
function WikipediaAPIGetContent(search) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=" + search + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
// remove links as they will not work
blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });
// remove any references
blurb.find('sup').remove();
// remove cite error
blurb.find('.mw-ext-cite-error').remove();
$('#results').html($(blurb).find('p'));
$('#results').html(blurb);
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
</script>
Try this sample:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: function (x) {
console.log('title', x.query.search[0].title);
}
});
});
});
Source
This will show the query result with image:
$(document).ready(function(){
$('#btn').click(function() {
var search_text = $("input[name=Wikipedia]").val();
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
$.getJSON( url + search_text +'&callback=?',function(data){
for(var key in data.query.pages){
var titleArt = data.query.pages[key].title;
var extractArt = data.query.pages[key].extract;
var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
var imgArt;
if(data.query.pages[key].hasOwnProperty('thumbnail')){
imgArt = data.query.pages[key].thumbnail.source;
} else {
imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
}
var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></div></div>';
$('#display-result').append(contentHTML);
}
});
});
});
function Wiki(lang) {
this.lang = lang || "fr";
this.inuse = false;
}
Wiki.prototype.research = function(s, callback) {
if (this.inuse) {
console.error("Wiki est déjà en cours d'utilisation !");
} else {
this.inuse = true;
var r = new XMLHttpRequest();
r.onload = function() {
Wiki.prototype.inuse = false;
var j = JSON.parse(r.responseText);
callback(j);
}
r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
r.send();
}
}
var c = new Wiki();
c.research("Victor Hugo", function(result) {
console.log(result);
});
//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
console.log(result);
}
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();
}
});
}