How to send data from aspx to php page - c#

so far i have used this code.It is working when i am sending the data from aspx to aspx.
But in case of aspx to php it is not working.....
protected void Button1_Click(object sender, EventArgs e)
{
RemotePost myremotepost = new RemotePost();
myremotepost.Url = "http://172.16.126.32/Riyas/marggroup.com/get-current-openings.php";
myremotepost.Add("field1", TextBox1.Text);
myremotepost.Post();
}
public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head>");
System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
for (int i = 0; i < Inputs.Keys.Count; i++)
{
System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
System.Web.HttpContext.Current.Response.End();
}
}
In case of php i have use this code:
<script runat="server">
function formload()
{
alert("its working");
if(Request.Form["field1"] != null ){
alert("its working");
Response.Write("field1 : " + Request.Form["field1"] + "</br>");
}
if(Request.Form["field2"] != null ){
Response.Write("field2 : " +Request.Form["field2"] + "</br>");
}
}
</script>
</head>
<body onload="JavaScript:formload()">
<script language="JavaScript">// change to text/javascript or even remove, no effect
window.onload = function() {
formload();
};
</script>
</body>
My aim is i want to send data from aspx to php not in the query string.

Modify your php script to contain the below given code and see if it works. You don't need anything else apart from the given two lines.
<?php
print_r($_POST);

Interesting...
in the onload function, you are calling formload(), which is a server side function , isn't it?
this is not correct, on client site you should only call client site javascript function.
if you want to post information to another server, no matter it is php/asp.net/jsp.
simply use a form....
in the Post function of your remotepost class, you didn't post to your remote server... just generate some html tags, and in the page load function, submit the form automatically,
it is not nice, but should work.
correct first issue first, then see how it goes.

If not in the query string, why not send it as POST data instead?

Related

How to return value from asp.net page called by jQuery Get() Method

How to return some value from asp.net page that is called using jQuery Get() method ? The get method is given below and i want the alert() should display the returned value.
The get() calls "result.aspx" page that return a string and that string i want to show in alert().
$.get("result.aspx",
{
name: "Donald Duck",
city: "India"
},
function (result, status, xhr) {
alert(result);
}
);
The result.aspx code is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadReturn();
}
}
void LoadReturn()
{
string name = Request.QueryString["name"];
string city = Request.QueryString["city"];
string returnValue="Hello Mr."+ name + " who lives in " + city;
//How to return value of returnValue to the jquery get() function.
}
How to return value of returnValue to the jquery get() function ??
Update
I tried the response.write(). It is able to return the data to jquery get() method.
Response.Write(returnValue);
Only problem is that it is also sending me the full HTML of the result.aspx page. Which i don't want.
How can i prevent the unnecessary HTML from reaching the jquery get() method?
I solved it by putting Response.End() in the end. Hope it helps others too.
void LoadReturn()
{
string name = Request.QueryString["name"];
string city = Request.QueryString["city"];
string returnValue="Hello Mr."+ name + " who lives in " + city;
Response.Write(returnValue);
Response.End();
}

div inner html using c sharp static method? how to

I have a static method where I want to get the "div" inner html I Used the following method
[WebMethod]
public static string SetFileNameU(List<string> someValues)
{
string linkmain = link.Replace("Journey=R", "Journey="+journey);
SearcResult src = new SearcResult();
src.iframesourceType(linkmain);
return linkmain;
}
and here i called non static function passing link to that fucntion
public void iframesourceType(string linksrc)
{
frame.InnerHtml = ""; //// error frame is null
}
and returns the error
object refrence not set to initialization of object
my html frame is div
<div runat="server" id= "frame" class="col-md-9">
<%--<iframe class="ifr" >
</iframe>--%>
</div>
kindly tell me how to change content my webform class is searchresult.cs and frame.innerHtml was working at form laod and can be aceesed but calling from static after ajax call in non static function it works
why static?
1-first time when i open file i use that
protected void Page_Load(object sender, EventArgs e)
{
string link = Convert.ToString(Session["url"]);
Label1.Text = link;
SomewhereInTheCode();
frame.InnerHtml = (" <iframe class='ifr' frameborder='0' src='" + link + "' > </iframe>");
}
now i am using ajax call to web method to change inner HTML as needed see the code at top and it work only at page load
div is runat server so acesed from server side as frame
You Cannot access any of the form elements in a static method. Only instanciable methods can access it.
If you want to change the content of div through web method just return the content and then assign the HTML to div in the success function of Ajax Call.
Ajax Function
$.ajax({
url : "FileName.aspx/SetFileNameU",
method : "GET"/"POST",
data : "{someValues:['value1','value2','value3']}",
success : function (data) {
$('#frame').html(data);
}
});

Response.Redirect asp didn't work after $post jquery

I do something to pass Facebook ressponse by post the value to currentpage
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
$.post('http://localhost:50790/TestPage.aspx',
{ fbid: response.id, firstname: response.first_name, lastname: response.last_name, email: response.email, bday: response.birthday },
function (result) {
});
console.log('Good to see you, ' + response.name + response.id + response.email + response.gender + response.birthday + '.');
});
}
and I do some checkin on my code behind :
protected void Page_Load(object sender, EventArgs e)
{
var fbid = Request.Form["fbid"];
var fname = Request.Form["firstname"];
var lname = Request.Form["lastname"];
var email = Request.Form["email"];
var bday = Request.Form["bday"];
if (!Page.IsPostBack)
{
if (fbid != null)
{
CheckFBLogin(fbid.ToString());
}
}
}
my testing is on CheckFBLogin if the result okay, It'll make the user login to website, else it should redirect to others page / registration page.
public void CheckFBLogin(string Fbid)
{
CustomerSelfCareSoapClient service = new CustomerSelfCareSoapClient();
service.ClientCredentials.UserName.UserName = _Username;
service.ClientCredentials.UserName.Password = _Password;
GResult result = service.CheckFBLogin(Fbid.ToString(), "");
if (result != null)
{
if (result.Code == 100)
{
//login
}
else
{
Response.Redirect("~/callback.aspx", true);
}
}
}
I dont know what happen, I usually do something like this to check login but pure asp and c#. any I idea why the page wont redirect ?
I'm able to duplicate this behavior with Mono. On my system, the problem is that the jquery $post() method actually enables the Page.IsPostBack property in code behind so that all logic in the if (!Page.IsPostBack) {} condition fails to run.
My advice would be use ASP.NET's [WebMethod] attribute alongside jquery. Dave Ward has documented this well. If you're doing a lot of asynchronous client side JSON calls, you might consider ASP.NET's MVC implementation if the scope of your project allows it.

How to call jquery function in a class file

Hi all I have created a javascript which I want to use in my entire application, so I have created a class which returns string as follows
public static string ShowAlert(string pHeader, string pMessage)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='JavaScript' type='text/javascript'>");
sb.Append("example1('" + pHeader + "','" + pMessage + "')");
sb.Append("</Script");
return sb.ToString();
}
This is my code JFunction.JS
(function example1(title, content) {
$.msgBox({
title: title,
content: content
});
})
Now on button click I am just calling as follows
Page.ClientScript.RegisterStartupScript(this.GetType(), "",ShowAlert(pHeader,pMessage) , true);
But I am unable to get the message, so is there any way to create a unique method instead of calling the script on each page,
Code Behind
public partial class call_jquery_from_class_file : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Alert.ShowAlertMessage("Testing Code", Page);
}
}
Class file Code
public class Alert
{
public static void ShowAlertMessage(string error, Page page)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("$(document).ready(function() {");
sb.AppendLine(" $(\"form\").append($(\"<div>\").attr(\"id\", \"dialog\").css(\"display\", \"none\").html('"+error+"'));");
sb.AppendLine(" $(\"#dialog\").dialog({autoOpen: true,show: \"blind\",hide: \"explode\" });");
sb.AppendLine("});");
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", sb.ToString(), true);
}
}
Hope it helps you,.
Same is working for me.That's why i suggested same.
ASP.NET Button control has Attributes property. So if you want to call javascript method on server control you just need to add "onclick" Attribute. For example you have btnAlert control:
Javascript file:
function example1(title, content) {
$.msgBox({
title: title,
content: content
});
}
ASP.NET code behind in Page Load:
btnAlert.Attributes.Add("onclick", String.Format("example1('{0}', '{1}'); return false;", "some title", "some message"));
You should add return false to prevent PostBack. BTW If you need a control only for calling client side methods you may use general html control(<button onclick='example1("<%= Resources.Title %>", "<%= Resources.Content %>")'>Example button</button>) and add your title and content by using <%= %>.

How to call C# method in javascript by using GeckoFX as the wrapper of XULRunner

I am using GeckoFX16 and xulrunner-16.0.2.en-US.win32 in my project.
The thing is, I want to call a C# method in javascript.
I am curious, is there a way to do this?
Just like below:
C# part:
private GeckoWebBrowser weBrowser;
public browser()
{
InitializeComponent();
Gecko.Xpcom.Initialize("xulrunner");
weBrowser = new GeckoWebBrowser();
weBrowser.Parent = this;
weBrowser.Dock = DockStyle.Fill;
weBrowser.Navigate("test.html");
}
public string loadData(){
//load data from local file.
return str;
}
javascript part:
<script type='text/javascript'>
var data = window.loadData();
alert(data);
</script>
I am new in this area, I’ll appreciate if it is possible!
Important update:
Currently code with event.initMessageEvent does not work because this construction has been replaced on
var event = new MessageEvent('yourEventName', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
You can use a MessageEvent to invoke code in c#, but as far as I know you can't then return a string like you're wanting to. One of the unit tests demonstrates how to invoke the c# code:
[Test]
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
I know it's awkward, but you could then use a c#-->javascript call to get data back to javascript-land. See This Question for how to do that. So your javascript would first send this message to c# land, then it would get a callback with the string value you need.
Hope that helps.
You can add message event listener to your web browser and call your method like this:
private void load()
{
browser.AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
browser.LoadHtml
(
#"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
document.dispatchEvent(event);
}
</script>
</head>
<body>
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
}
...
private void showMessage(string s)
{
MessageBox.Show(s);
}
Now you can add more msg events to your msg listener (if you need to) and fire them all in the same way.

Categories

Resources