I have file called functionContainer.js and in that file I have written
function returnTen(){
return 10;
}
function returnName(){
return "Stack Overflow";
}
and in callAjax.js file I need to call the returnTen function and get the data via an Ajax call.
(functionContainer.js is hosted in a server)
How can I do this?
If you want to execute returnTen(); after your ajax request finishes,
then put your returnTen() function inside of a success, failure, or callback function; whichever one you choose is up to you...
Here some example with ExtJs Ajaxcall :
Ext.Ajax.request({
url: 'page.php',
params: {
id: 1
},
// scope: this,
// you can set the scope too
callback: function(opt,success,respon){
**returnTen();**
}
});
To make this method (returnTen()) callable from the client side script we need to make this static and decorate/adorn it with a WebMethod attribute.
The first thing that we need to do to be able to call the server side methods is to make the EnablePageMethods="true" in the ScriptManager control.
In Your script you can call server side js function like this:
function CallServerMethod()
{
// call the server side method here
PageMethods.returnTen();
}
Related
I'm trying to call a JavaScript function from an ApiController. I don't know if it's possible because since it's API the page which has the Js code won't be loaded. I need to read it from the file and make it work somehow I think.
The js part which I'm trying to call, this is inide a .js file called editDetail.js
var fn = Function("item", validateString);
var validateresult = fn(obj);
return validateresult;
I'm not really sure if it's possible to make this work. If it is ,how?
I'm not sure why you would want to be able to do this but all I can tell you is that what you are asking is not possible. The API controller has no access to the scripts. You could use the .success method of an ajax call (which called the API controller) to call the method you need.
EDIT:
$.ajax({
type: "GET",
url: 'yourcontroller/youraction',
contentType: "application/json",
success: function (data) {
//call the other .js method here
}
});
I'm making a site with several calls to PHP via AJAX, right now AJAX uses POST to get a echoed string from PHP and then compares that in a switch and then does what is required. Example in the code below
function submitPHP(dataForPHP){
//Runs ajax request
$.ajax({
type : "POST",
url : 'initPHP.php',
dataType : 'text',
data : dataForPHP,
success : function(data){
//Checks echoed data from PHP
switch(data){
case "LOGIN_ACCEPTED":
loggedInFunction();
break;
case "LOGIN_FAILED":
loggedInFailedFunction();
break;
}
}
});
}
I'm thinking if there is a way for the PHP to return what function (like "loggedInFunction();") I want to call instead of a string that I then have to compare and then call the function? I can change the AJAX to use JSON instead if that does it.
I've been looking around on other similar questions here on stack on most of them want to echo a whole function which is not what I want to do.
Thanks in advance!
I'd do this.
use HTTPS to perform login, HTTP really is insecure nowadays;
create a controller object with all allowed methods (actions);
call an action of that controller.
The idea of having a controller is convenient on several levels:
security: if a method is not in the controller you cannot call it, so it is a way to know what can be called and what is absolutely not possible to call;
cohesion: the methods are all next to each other and easier to maintain;
encapsulation: if there is any state it can be held easily inside the context of that object.
This is an example:
loginController = {
"acceptAction": function () {
},
"failAction": function () {
}
};
You can now call those methods from the AJAX handler. Say the server tells you what you must do. A verb so to speak, such as accept or fail. You can then do:
"success": function (data) {
loginController[data + "Action"]();
}
And that's it.
BTW: this is just the very basic MVC pattern. Oldie but goldie :)
I need to call a JavaScript function that shows a Bootstrap modal. I have the following code:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void execModal(string groupname, int zw) {
//need to generate the data first
StringBuilder sb = new StringBuilder();
Generate gen = new Generate();
sb = gen.generateDeeperTable(zw, groupname);
//insert into my placeholder
//Append the HTML string to Placeholder.
fillPH(sb);
//run javascript function <showModel> to show the modal
}
Here is how I call the execModal method form JS:
<script type="text/javascript>
function callGenDeeperTable(zw, groupname) {
PageMethods.execModal(groupname, zw);
}
</script>
The function execModal is called from a javascript function in the .aspx site.
How can I call the javascript function showModal?
Your execModal method is on the server. You have not specified where you want to invoke (call) it from, but since you've decorated it (added attributes to the method defining it...) as a WebMethod, chances are you're trying to invoke it from a (HTML) page running in a client's browser. To make this call you need a line of communication between the client that wants to run the method, and the server that holds the method. You will also notice that execModal is defined as a static method. That means that when it is invoked it will not have the instance members of the Page class, including things like fillPH (unless fillPH is static). I don't know if you're working with ASP.NET WebForms (trying to make the call from an .aspx page), or this is a service consumed by some application (method resides in an .asmx), or I guess this could even be ASP.NET MVC.
Assuming ASP.NET WebForms
Let's deal with the simplest case since there have been almost no details provided. If we assume that this method, execModal, lives in an .aspx.cs file, and you're trying to call it from the corresponding .aspx page, and this is part of an ASP.NET WebForms application...
You need to initiate the call to execModal. This requires an AJAX call from your client to your server. You can create your own AJAX framework, but there are many open source frameworks available. I will give an example below using jQuery.
You need to do the work on the server statically, or you need to use the HttpCurrent.Context to get the instance of the Page, Session, etc. The Page can be retrieved via the HttpCurrent.Context.Handler as Page.
Once the method finishes on the server, the result (success or failure), and optionally any data you want to return to the client, is sent back to the client's browser. The client portion of the application should be able to process this response with an event handler. The event handler should be associated with the XMLHttpRequest object's onreadystatechange event and process the response when the state changes to 4 (done). Frameworks, like jQuery, take care of this overhead by providing parameters in your AJAX call to specify the success/failure callbacks. Do not confuse the result (sucess/failure) of this communication process with the result of your application's processes (actual work of execModal).
Your client side (success) callback function would then just call your desired js function showModal.
Your client side AJAX call (if you were to use jQuery) would look something like this...
$.ajax({
type: "POST",
url: "Default.aspx/execModal",
data: '{groupname: "' + groupname + '", zw: ' + zw + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
showModal();
},
failure: function(response) {
alert("AJAX request failed");
}
});
This is a very basic example. You might want the server to decide what happens on success, but returning a JSON data, or a string with the name of a js function that can be executed on the client - these are just examples to get your thinking about what is possible.
Edit - account for OP's addition of PageMethods.execModal() to question
You say you're calling your server code from this...
<script type="text/javascript>
function callGenDeeperTable(zw, groupname) {
PageMethods.execModal(groupname, zw);
}
That implies that you're using ASP.NET's ScriptManager with EnablePageMethods=true. Is that correct?
That would inject the script with the PageMethods type, and define functions for each of your WebMethods. So you are using an AJAX framework - the one provided by MS. All that work of making the AJAX call is being hidden from you with PageMethods.execModal(groupname, zw). However, each of the functions generated for you (on the PageMethod object) take additional parameters for OnSuccess and OnFailure callbacks. Here is a SO answer detailing how to use the ScriptManager's PageMethod object.
The signature for any function generated on the PageMethod object corresponding to a WebMethod is...
function foo(param1, param2, param3, etc., OnSuccess, OnFailure)
In your case, you have two parameters being passed to the WebMethod, so after those two parameters you would want to supply callback functions for success and failure. showModal would be your success handler probably...
PageMethods.execModal(groupname, zw, showModal, function() { alert('failed!') });
this is what i did and worked like charm
javascript part
function buyproduct(productId)
{
PageMethods.checkifvalid(productid, OnSuccess);
}
function OnSuccess(response, userContext, methodName)
{
this[response]();
}
function functionToCallAfterwebmethod()
{
alert("Javascript Function called successfully!!");
}
Aspx.cs part
[System.Web.Services.WebMethod]
public static string checkifvalid(int productId)
{
--your any logic to check
-- pass the javascript function as return parameter
return "functionToCallAfterwebmethod"
}
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.
I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).