Using server side PHP code from client side C# - c#

I have a server side PHP script that looks like this
class MyObject {
function GetResult($input){
//some code
return $result;
}
}
I want to instantiate this object and call the GetResult function from client side c# application and get the get the result. How can i do so?

You can use Ajax call to hit on that PHP page and get the results from that PHP page.
Just use JQuery Ajax function like this and make object initialization in PHP page only.
$.ajax({
type: "POST",
url: "example.php",
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
}
});

Related

FileUpload formData in ASP.NET WebForms

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.

Invoking a c# webservice using jquery

I am trying to create a webservice that takes data, posts it to a database, and returns the result. I know how to write all the C# code that does that, but it is the communication that I am having problems with. At the moment, I am just trying to invoke the service and get back "Hello World" (I start with something simple since I have no idea what I'm doing)...
My Jquery:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
alert("Success");
$("#log").html(msg);
alert(msg);
}
});
My Webservice:
public class PersonService : System.Web.Services.WebService
{
~
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
~
}
After using chrome to Inspect the Element, and selecting the Network tab, finding my webservice, it shows me that the result was:
<?xml version="1.0" encoding="utf-8"?>
<string>Hello World</string>
So, it seems that the service executed successfully, but the success function does not fire, and there are no errors in the console. What is going on? Also, why is the result in XML?
Do I need to use Web Services, or could I just post the variables via AJAX to an ASPX page that would process it the same way it would a form submission?
Using jQuery to Consume ASP.NET JSON Web Services ยป Encosia
$(document).ready(function() {
$.ajax({
type: "POST",
url: "RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Hide the fake progress indicator graphic.
$('#RSSContent').removeClass('loading');
// Insert the returned HTML into the <div>.
$('#RSSContent').html(msg.d);
}
});
});
Also, you're missing [ScriptMethod] on your web service method and [ScriptService] on your service class.
[WebService]
[ScriptService]
public class PersonService : WebService
{
[ScriptMethod]
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
}

asp.net call WebMethod from Javascript asyncronous

I am trying to build an asp.net(c#) page that updates some state texts every second.
Now I have implemented an button that calls another PageMethod which restarts something and takes a little while. The problem is, that when I call the restart PageMethod , the update PageMethod can't update as long as the restart method is proceeding...
I wrote a little example to show what I mean:
WebMethods in my Page:
[WebMethod]
public static string Update()
{
//return "a" to see when the Update PageMethod succeeded
return "a";
}
[WebMethod]
public static string Restart()
{
//the restart will take a while
Thread.Sleep(2000);
//return "a" to see when the Restart PageMethod succeeded
return "a";
}
the html elements to update:
<p id="update" style="float:left;"></p>
<p id="restart" style="float:right;"></p>
the Pagemethod calls:
callUpdate()
function callUpdate() {
PageMethods.Update(function (text) {
//itself+text from pagemethod
$('#update').text($('#update').text() + text);
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
PageMethods.Restart(function (text) {
//itself+text from pagemethod
$('#restart').text($('#restart').text() + text);
});
setTimeout(callRestart, 1000);
}
Note: The Update is also called every second after it finished, just to see how it works
To clarify: I want the PageMethods to execute independent to that the other PageMethod has finished.
I also flew over some links like:
http://esskar.wordpress.com/2009/06/30/implementing-iasyncresult-aka-namedpipeclientstream-beginconnect/
http://msdn.microsoft.com/en-us/library/aa480516.aspx
But I don't think this is what I need (?)
And I really don't know how to call that from Javascript (BeginXXX and Endxxx)
*EDIT: *
Regarding to Massimiliano Peluso, the js code would look like this:
callUpdate()
function callUpdate() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Update",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#update').text($('#update').text() + msg.d);
}
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Restart",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#restart').text($('#restart').text() + msg.d);
}
});
setTimeout(callRestart, 1000);
}
Note: when I run the Page with the new js, there is exactly the same problem as before: The Update method can do nothing until the Restart method is finished.
you should call the page methods using an Async call instead.
have a look at the below. It is a generic way to call a page method using JQuery
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
you should use this code to replace the page method calls
PageMethods.Restart(function (text))
PageMethods.Update(function (text))
It's because an Request only Proceeds when no other Request is processing.
Thats because two Processes can't acess to the same SessionState (Sessionstate is not Threadsafe).
So to achieve that Requests are processed at the same time, you have to set EnableSessionState in the #Page directive to either 'ReadOnly' or 'false'

Sending variable to a C# inside Javascript code

Javascript Code:
function jsfunction ()
{
var sayi = 9999;
alert('<%= cfunction("'+sayi+'")%>');
}
C# Code:
public string cfunction(string gelen)
{
return gelen;
}
Normally,There is should be 9999 value which is send to C# code from javascript code,but,this value returning as '+sayi+'.
Also,that's gives me alert 9999.What am I wrong?
By the time JavaScript runs, the C# code has already been executed. Learn you page life cycle.
If you want to call a serverside function to get data, you need to learn about Ajax.
C# (server-side) can generate markup for client side, client side can't call back up to server-side without some kind of Ajax type web request.
To do what you're looking for you can create a C# webmethod
[WebMethod()]
public static string cfunction(string gelen)
{
return gelen;
}
And consume the webmethod with a client-side jQuery.ajax() method (You'll need the jQuery library script if you don't have it already)
function jsfunction() {
var sayi = 9999;
$.ajax({
type: "POST",
url: "YOUR-ASPX-PAGE.aspx/cfunction",
data: "{gelen:'" + sayi + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
You can use scriptmethod attribute to invoke server side method from your javascript code. But you must understand the mechanism behind it so that u can debug and modify accordingly.
http://www.chadscharf.com/index.php/2009/11/creating-a-page-method-scriptmethod-within-an-ascx-user-control-using-ajax-json-base-classes-and-reflection/

jQuery Ajax passing the Form Collection

I was wondering if it is possible to pass the forms collection from within an ajax method in jQuery?
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});
If it is possible to pass in the forms collection then when it arrives at the method within c# how to you read it in?
You can do something like this:
var form = $("#myForm").serialize();
$.post("/Home/MyUrl", form, function(returnHtml)
{
//callback
});
Then on the C# side you should be able to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyUrl(FormCollection collection)
{
//do what you gotta do
}
I think this should work.
EDIT: I just noticed that I simply assumed you were referring to ASP.NET MVC. If not, let me know as this answer is specific to MVC.
You can use the Ajax.BeginForm method from ASP.NET MVC. It will use Microsoft's ajax to do the request, but you can have a JQuery method execute upon completion. Or you can use an UpdatePanel and register a javascript to run with the ScriptManager once the UpdatePanel loads. Another thing you could try is using a jquery like the following: $(':input') to get a collection of all input, textarea, select and button elements(JQuery documentation), and pass that as the data into your request.
Got this working all okay, and it returns the input form collection in the FormCollection
input = $(':input')
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: input,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});

Categories

Resources