I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?
window.setTimeout(function() {
alert("test");
$.ajax({
type: "POST",
url: "'.$this->createUrl("/operator/createViopNode/").'",
data: {
id: '.$bc_id.',
callid:"'.$num.'",
taskid:'.$this->taskid.'
},
success: function(msg){
var ifrm = document.getElementById("frame");
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(msg);
ifrm.document.close();
},
error: function (jqXHR, textStatus, errorThrown){
alert("" + textStatus + ", " + errorThrown);
}
});
}, parseInt('.$tps_call.'));
I need to write above js function inside controller action method, how to write this ?
Index.csHtml
function abc()
{
alert("called")
}
now Ajax Call function
function ExecuteAjax(URL,Data,Success)
{
try {
$.ajax({
type: "post",
url: URL,
data: Data,
contentType: "json",
success: function (data) { if (typeof Success == "function") { Success(data); } }
})
} catch (e) {
alert(e.message)
}
}
Call ajax like this
ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
eval(data.script);
});
return from controller
if(demo=="true")//put condition here whatever you want
{
string strscript="abc();";
}
protected JObject jobj = new JObject();
jobj.Add("Script", strscript);
return Json(jobj);
Execute js function when controller return success
You should register your javascript function like this:
function actionTest(){
$cs = Yii::app()->clientScript;
$cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
$this->render('any_view');
}
source
Related
I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA
I need to execute an ajax function, the detail here is that i want to execute this function until another ajax function return success.
This is the function that will i have to wait to return success (try..catch block)
Ajaxfunction1
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
try {
var jsonObject = JSON.parse(msg);
console.debug(msg);
//SendToDMS(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
},
failure : function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
}
});
I want something like this:
while ( Ajaxfunction1 != success ) { // while the previous ajax function not return success execute this another ajax function
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
// something on success
},
failure : function(msg) {
// something when comes an error
}
});
}
How can I accomplish this? Thanks for your help
You can use the returned Deferred from $.ajax and check it's state() to see if it's resolved, rejected or pending, so something like this with a recursive function should do what you want.
var waitFor = $.ajax({
type : "GET",
url : url,
data : parameters
}).done(function(msg) {
try {
var jsonObject = JSON.parse(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
}).fail(function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
});
(function rec() {
$.ajax({
type : "GET",
url : url,
data : parameters
}).always(function() {
if (waitFor.state() != 'resolved') rec();
}).done(function(msg) {
// something on success
}).fail(function(msg) {
// something when comes an error
});
})();
How I can get variable value from jsonp response and use it in other script function?
In first function I have one value that I am getting from jsonp response. I am assigning this value to variable ( var userId ) in first function.
How I can get userId value and use it in second script function???
<script>
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () {
if ($('#username').val().length > 0 && $('#password').val().length > 0) {
console.log($('#check-user').serialize());
$.ajax({
url: 'http://localhost/check.php',
data: $('#check-user').serialize(),
type: 'POST',
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (result, status, err) {
if(result.login){
$.mobile.changePage( "#output", { transition: "slideup", changeHash: false });
var userID = //// HERE I NEED TO GET USER ID FROM jsonp response!!!!
});
}
else{
alert("An error occurred: " + status + "nError: " + err.status);
}
},
error: function (request, error) {
}
});
} else {
alert('Please fill all necessary fields');
}
event.preventDefault();
});
var output = $('#output');
var userid = ////HERE I NEED TO SET USER ID!!!!!!!!!!!!
$.ajax({
url: 'http://localhost/data.php?user='+userid,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.lat+'<br>'
+ item.long+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
you can use the global variable assignment feature of js
Declare your variable outside of any function.
<script>
var userId;
function foo(){
//..
}
</script>
OR Use the window object to assign the global variable from inside a function
<script>
function foo() {
window.userID = ...;
}
</script>
more info available here
My variable data in function ShowFavorits is undefined even do that my ajax call do return a json string.
<script type="text/javascript">
$(document).ready(function () {
ShowFavorits();
function AjaxGet() {
var param = "{'_userID': '1337'}";
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
contentType: "application/json;",
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
return (data.d);
}
},
error: function (data) {
//error
}
});
}
function ShowFavorits() {
var data = AjaxGet();
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});
[WebMethod]
public string GetFavorits(string _userID)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = int.MaxValue;
string JsonData = string.Empty;
var db = new ModelDataContext();
var list = db.table.Where(x => x.userID == _userID).OrderBy(x=> x.TimePin).ToList();
JsonData = jss.Serialize(list);
return (JsonData);
}
Why cant i return the result from my ajax?
Hope someone can help me, have been stuck for hours now debugging this.
Thanks in advance.
The call to $.ajax in AjaxGet is asynchronous: the function returns undefined because the ajax call hasn't finished.
You should move the call to ShowFavourits into the ajax success function so that it executes once the ajax call is complete/successful
<script type="text/javascript">
$(document).ready(function () {
// Kick-off the ajax request
AjaxGet();
function AjaxGet() {
var param = {_userID: '1337'};
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
ShowFavorits(data.d); // Pass the data to the template
}
}
});
}
function ShowFavorits(data) {
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});
I want to repeatedly count time and update the current time every one minute. My code doesn't work. Firebug console says the final line function getStatus() is not defined. How to call this function repeatedly?
jQuery(document).ready(function($){
$(function() {
getStatus();
});
function getStatus() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url : ajaxurl,
data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
success: function(response) {
if(response == "false") {
alert("failed")
}
else {
$("#message").html(response)
}
}
});
setTimeout("getStatus()",60000);
}
},(jQuery));
your issue is getStatus is wrapped in another callback. either do window.getStatus = function(){}, or turn your code to this:
jQuery(document).ready(function($){
var getStatus = function() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url : ajaxurl,
data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
success: function(response) {
if(response == "false") {
alert("failed")
}
else {
$("#message").html(response)
}
}
});
setTimeout(getStatus,60000);
};
$(function() {
getStatus();
});
},(jQuery));
Passing a string to setTimeout will make it eval the string, which you should avoid, and generally not required by your code
You could use setInterval(getStatus, 60000) instead perhaps, but otherwise you should use setTimeout(getStatus, 60000). Do not use a string as the function callback but rather the named function.
Use setInterval(function, milliseconds)
jQuery(document).ready(function ($) {
var getStatus = function() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url: ajaxurl,
data: {
action: "update_edit_lock",
post_id: post_id,
nonce: nonce
},
success: function (response) {
if (response == "false") {
alert("failed")
} else {
$("#message").html(response)
}
}
});
}
setInterval(getStatus, 1000);
}, (jQuery));