call/answer between PHP and ASP.NET - c#

Is it possible to submit an email address through a text area of an HTMLpage integrated in ASP.net page and send this to a PHP script that control if is actually a valid email address and send answer back to the ASP page so I can get an alert: VALID or NOT VALID.
I have 2 webspeace with two different websites: ASP.net and one in PHP.
The ASP.net page has a Webform in HTML. I would like to use this to send the email to the PHP script. which rune the validation and send back the status to the ASP page that would answer through an alert, "mail valid" or "not valid."
The idea I have is that the script (after the validation control) has to send back an answer throw an URL to the ASP page and the ASP page would "listen"/ "get" this URL as a variable in order to diplay with an alert the result of the PHP SCRIPT
PHP side:
<form action="http://www.exemple.com/scripts/mailvalidation.php" method="post" id="webform">
SCRIPT PHP ? (maybe using the PHP FILTER_VALIDATE_EMAIL) ?
ASP.NET ?
Any suggestion=?

Sounds like a perfect place to use AJAX. It is independent of the language you use. PHP, ASP.NET, JSP it is all the same. All that is needed is simple JavaScript or Jquery.
In your ASP Page,
<form id="myform">
<input type="email" id="email" name="email" />
<button>Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="application/javascript">
$(document).ready(function(){
var formvars = $("#myform").serialize();
var url = "http://www.example.com/your_page.php?" + formvars;
$.ajax({
url: url,
cache:'false',
dataType: 'text',
type:"GET",
success: function(data){
//alert( data );
alert( data );
if(data =="1")
alert("VALID");
else
alert("IN VALID");
},
error: function(data){
alert('error; '+ eval(error));
}
});
});
</script>
In your php script,
<?php
$email = $_REQUEST["email"]
if($email, FILTER_VALIDATE_EMAIL))
echo "1";
else
echo "0";
?>
Good luck.

I would say if the issue is of passing value from asp to php, then use querystring to pass value from one page to another.
But as far as your comment goes...you can directly use ASP to insert the records in MYSQL without passing through PHP.
YOu can use the following as the reference:
http://www.codeproject.com/Articles/36484/Working-C-code-for-MySql-Stored-Procedures-IN-OUT

in php file use:
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$msg='valid';
}
else{ $msg='invalid'; }
$urlVar='email='.$_POST['email'].'&msg='.$msg;
header("location: hostname/PageName.asp?$urlVar");
then in asp you can use above code and execute your msg in if condition as shown:
if(Request.QueryString("msg") != ' ' && Request.QueryString("email") != ''){
}
I am not good in asp but hope you get concept to handle it

I would suggest, validate email in asp.net. There is lot you can do to validate email in asp.net. Like use Regular Expression - refer this, or use EmailValidator to validate. Also check this link - Email Address Validation for ASP.NET
Following is an example of the above.
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
But if you are interested to know how to communicate between asp.net and php, then you can check following.
Have php page that accepts email as get request, php page can use FILTER_VALIDATE_EMAIL to validate email or any other custom validation you want to add.
Then use jQuery ajax in asp.net webform to invoke that page with get request and from php page send required message and success handler trap the output , display that to asp.net page.
EDIT
After checking your comment, you need to insert to mysql from asp.net. And that is pretty much doable. You need to have mysql connector for .net and use that library to make CRUD operation. Since answer or actual code snippet is not in scope of current question, i am posting links that will be helpful for you.
Following are some of link -
LINK1
LINK2

Related

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

Call C# function from Javascript in aspx webform and then reload page

Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.

sending mail from outside of a website or asp.net application

is it possible to post data from an html page using Jquery to another asp.net website ?
say www.site1.com/mail.html - > www.site2.com/mailServ.aspx
using jquery ajax i could use this code to post to code behind [webmethod]
so instead of code within same website(site2) it will be sent from site1
this is the code i am using to post the form data to a web method within same website application
function jQuerySendMailCsCodeBehind(resluts) {
var SentClientinfo = []
SentClientinfo.push({ key: "SentClientinfo", value: resluts });
var CurrpageURL = "default.aspx/"; <---
var WebmethodName = "StartTest";
var StageIdentifyer = "stage1";
var Post_TargetUrl = CurrpageURL + WebmethodName;
jQueryAajaxNoPostBack(Post_TargetUrl, SentClientinfo, StageIdentifyer);
}
i tried to post from outside of application
so i just used
var CurrpageURL = "http://www.site2.com/default.aspx/";
from the other site (site1) html website non asp.net but the idea did not work in reality (:
so is there an option that a webForms application/ asp.net website
will accept requests from another website code of ajax/jquery ?
By default, JavaScript is not allowed to access other domains than the one it originated from for security reasons. You don't want the JavaScripts on my site to access your bank's web site, with your bank login cookie if you happen to be looking at my site while being logged in to the bank.
One way to work around it is JsonP, but as far as I've understood it it's mostly for retrieving data.
What you're probably looking for is Cross Origin Resource Sharing or short CORS. To implement that, your site2 would need to set a Access-Control-Allow-Origin header and the users would be required to use a browser that supports CORS (not all do, see the wikipedia page for info).
You cannot make cross-website requests with javascript. You need to use jsonp
jQuery supports jsonp, see the following example
$.ajax({
type: 'GET',
url: 'http://githubbadge.appspot.com/badge/torvalds',
dataType: 'jsonp',
success: function(json) {
var result = '<h3>' + json.user.login + '</h3>' +
'<p>Languages: ' + json.languages + '</p>' +
'<p>Followers: ' + json.user.followers + '</p>';
$('#badge').append(result);
}
});

Html Tag in textbox/input text

When I input some html tag like < b> or < test> (without the space after "<") in my TextBoxes, When I submit the form I got the issue:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server.
The status code returned from the server was: 500
I don't want to set the "ValidateRequest" false, because of security problems.
I thought in make some kind of javascript function inserting a space after "<", this could work...I guess.
Any idea?
You can escape your input using javascript before posting it back.
See existing answers:
Escaping HTML strings with jQuery
Escape HTML using jQuery
Fastest method to escape HTML tags as HTML entities?
On the c# side use HttpUtility.HtmlDecode(string) to decode your text back.
You can escape/unescape your html content using JavaScript (jQuery) as shown below:
<script>
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function htmlDecode(value) {
return $('<div/>').html(value).text();
}
</script>

PageMethods in ASP.NET failed to work if you have ASP.NET Routing Implemented

I have a web method:
[System.Web.Services.WebMethod]
public static string getCharacterstics(int product_id, int lang_id)
{
// code goes here...
}
I want to access it using PageMethods like:
(Provided the condition that i have Enable PageMethods in ScriptManager):
<script type="text/javascript">
$(document).ready(
function () {
$('#characterstics').html("loading");
// '<%= product_id_property %>' , '<%= this.LanguageID %>'
PageMethods.getCharacterstics(0 ,0 , OnSave);
}
);
function OnSave(result) {
}
</script>
I get the error "the http verb post to access path.. is not allowed"
I googled it and search the SO too but does not get any solution regarding to it Based on ASP.NET Routing.
What i believe is that because of asp.net routing the service methods are not accessible.
In addition i think i cannot even use JSON because of asp.net routing too.
Any help is appreciated.
Updated:
If i run the page with this url:
http://localhost:2606/searchdetail.aspx
The web method executed successfully.
Now
I have routing like this:
routes.MapPageRoute("searchdetail", "searchdetail/{ID}", "~/searchdetail.aspx");
routes.MapPageRoute("searchdetail", "searchdetail", "~/searchdetail.aspx");
The set_path() will work only for case 2 i.e without ID but does not work with case 1
if i try
http://localhost:2606/searchdetail
It works fine
but if i try to use:
http://localhost:2606/searchdetail/123
It gives error that object expected.
So set_path() is the option what should i write.
Currently, WebMethods don't work transparently with the Routing framework. There is a work around. You have to access the PageMethods directly by doing the following in your javascript:
PageMethods.set_path('/the/path/to/your/page.aspx');
PageMethods.YourMethod(params, onSuccess, onFailure);
I hope this helps.
I kept running into this myself. With routing enabled, if I added a value to the path, it would start to fail again. This solution is a bit of a hack, but it seems to be working consistently.
Create a server control hyperlink where the navigate url refers to itself, then once the control renders, grab the href and use it for set_path
This gets around the issue of set_path not referring to the correct location if you called
<asp:HyperLink ID="hlPage" runat="server" NavigateUrl="~/user.aspx" ClientIDMode="Static"></asp:HyperLink>
<script>
$(document).ready(function () {PageMethods.set_path($('#hlPage').attr('href'));})
</script>

Categories