i am building asp .net website using jQuery and jQueryMobile framework. after succesfull login i am able to see contents of next page but the URL remains the same i.e. /Login.aspx
When i press F5 then only URL changes.
Login.aspx
<div data-role="content">
<form id="frmLogin" method="post" runat="server" action="Login.aspx">
<div data-role="fieldcontain">
<input type="text" name="txtUserName" id="txtUserName" placeholder="User Name" value="" runat="server" /><br />
<input type="password" name="txtUserPass" id="txtUserPass" placeholder="Password" value="" runat="server" />
<br />
<button id="cmdLogin" type="button">Login</button>
</div>
</form>
<div id="divDialog"></div>
</div>
JavaScript called when clicked on cmdLogin Login button
$('#cmdLogin').click(function () {
$.ajax({
url: 'ajaxExecute.aspx?Fn=VUSR',
type: 'POST',
context: document.body,
data: 'User=' + $('#txtUserName').val() + '&Pass=' + $('#txtUserPass').val(),
cache: false,
success: function (response) {
alert(f);
if (response == '1') {
f.submit();
}
else {
/*
Print Error
*/
}
}
});
});
Login Code Behind
Login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
routeToDefaultPage();
}
}
private void routeToDefaultPage()
{
Response.Redirect("Piechart.aspx");
}
What is problem here ?
When i do inspect element after login successful (Contents of Piecharts.aspx but URL is Login.aspx) . i see following in head section
<base href="http://localhost:49712/Login.aspx">
Are you sure to have flag ispostback assigned to true when you click. A break point on this line could help you?
Try this:
Response.Redirect("Piechart.aspx");
Response.End();
What about jquery redirect after ajax call?
Try to add this after ajax call success. header( 'Location: Piechart.aspx' ); ?
$('#cmdLogin').click(function () {
$.ajax({
url: 'ajaxExecute.aspx?Fn=VUSR',
type: 'POST',
context: document.body,
data: 'User=' + $('#txtUserName').val() + '&Pass=' + $('#txtUserPass').val(),
cache: false,
success: function (response) {
// redirects page after login successful
header( 'Location: Piechart.aspx' );
alert(f);
if (response == '1') {
f.submit();
}
else {
/*
Print Error
*/
}
}
});
});
This works for me...!!
$.mobile.changePage( "/Piecharts.aspx", {
transition: "pop"
});
Related
I've got a really strange problem where my ajax post request works fine the first time after the page has loaded but if I submit my form again without doing a page refresh then the contents are returned to the whole page instead of just updating the DIV. I've spent days on this looking for answers and through trial and error and I suspect the issue relates to Request.Headers["X-Requested-With"] being empty on 2nd submit. Note that I am returning a View Component to the ajax request and my ajax code is in a separate js file.
View Component (this contains the form that gets submitted and gets replaced when the ajax request returns. It works correctly after the page has been loaded or refreshed)
#model MSIC.Models.ClientViewModels.VisitMovementViewModel
#{
bool inProgress = (bool)ViewData["inProgress"];
}
<form asp-controller="Client" asp-action="VisitMovement" asp-route-id="#Model.VisitMovementID" id="formVisitAction" method="post" onsubmit="AjaxSubmit(this)">
<input asp-for="VisitID" type="hidden" />
<input asp-for="StageNo" type="hidden" />
<input type="hidden" id="replaceID" name="replaceID" value="#ClientVisit" />
<input type="hidden" id="submitAction" name="submitAction" />
<div class="col-md-9 no-padding">
<input type="text" id="visitMovementComment" name="visitMovementComment" class="form-control" placeholder="Comment..." required>
</div>
<div class="input-group col-md-3">
<input type="text" id="visitMovementBoothNo" name="visitMovementBoothNo" class="form-control" placeholder="Booth..." required>
<div class="input-group-btn">
<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" #((inProgress) ? "" : "disabled")>Action <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right">
#if (Model.Buttons != null)
{
foreach (var item in Model.Buttons)
{
if (item.beforeDivider)
{
<li><button type="#item.Type" name="#item.Name" class="btn btn-link btn-block btn-flat" value="#item.Value" onclick="#item.OnClick">#item.Text</button></li>
}
}
<li role="separator" class="divider"></li>
foreach (var item in Model.Buttons)
{
if (!item.beforeDivider)
{
<li><button type="#item.Type" name="#item.Name" class="btn btn-link btn-block btn-flat" value="#item.Value" onclick="#item.OnClick">#item.Text</button></li>
}
}
}
</ul>
</div>
</div>
</form>
Ajax Request located in separate JS file (when debugging this everything runs through as expected the first time however after the View Component is returned and the form is submitted the 2nd time the success, error, complete functions never fire and the returned data loads in the whole page)
function AjaxSubmit(form) {
$form = $(form);
var replaceID = $('input#replaceID', $form).val();
var formData = $form.serialize();
if (!$form[0].checkValidity()) {
return false;
}
$form.submit(function (e) {
e.preventDefault();
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: formData,
async: true,
processData: false,
cache: false,
success: function (data) {
$(replaceID).html(data);
},
error: function (xhr, status, error) {
console.log(xhr.status + " - " + error);
},
complete: function (data) {
console.log(data);
}
});
});
}
Action Method (I suspect the issue may be related to the Request.Headers["X-Requested-With"] being Empty on the 2nd submit and therefore MVC does not realise this is an ajax request hence returns the result to the page instead of returning it to the ajax request)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VisitMovement(int id, int submitAction, int? visitMovementBoothNo, string visitMovementComment, VisitMovementViewModel model)
{
var test1 = Request.ContentType; //1ST REQUEST = "application/x-www-form-urlencoded; charset=UTF-8", 2ND REQUEST = "application/x-www-form-urlencoded"
var test2 = Request.Headers["X-Requested-With"]; //1ST REQUEST = "XMLHttpRequest", 2ND REQUEST = Empty
try
{
if (ModelState.IsValid)
{
bool complete = false;
switch (submitAction)
{
case 2: //Proceed to Stage 2
model.StageNo = 2;
break;
case 3: //Proceed to Stage 3
model.StageNo = 3;
break;
case 4: //Complete Visit
complete = true;
break;
default:
return BadRequest("Could not determine action.");
}
await visitAPI.VisitMovement(id, model.VisitID, submitAction, model.StageNo, visitMovementBoothNo, visitMovementComment, complete);
return ViewComponent("ClientVisit", new { visitID = model.VisitID });
}
else
{
return BadRequest(ModelState);
}
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
If my assumption is correct why is the ajax request not sending the the correct headers when it is submitted the 2nd time and how can i fix it? If not what else could be going wrong?
I think the problem was the form submit event was being lost when the data/view component returned. I solved the problem by changing my ajax post to below...
$(document).on('submit', 'form.ajax-form', function (e) {
var replaceID = $('input#replaceID', $(this)).val();
var replaceType = $('input#replaceType', $(this)).val();
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
async: true,
processData: false,
cache: false,
success: function (data) {
$(replaceID).html(data);
},
error: function (xhr, status, error) {
AjaxOnFailure(xhr, status, error);
}
});
});
#{
var db = Database.Open("CMS");
//retrieving the username of the user from the session
var session_username = Session["session_username"];
//get the details of the user from the database
var getuserdetailscommand = "SELECT * from student where student_username = #0";
var getuserdetailsdata = db.Query(getuserdetailscommand, session_username);
var statusfirstname = "";
var statuslastname = "";
var statusavatar = "";
foreach(var row in getuserdetailsdata){
statusfirstname = row.student_firstname;
statuslastname = row.student_lastname;
statusavatar = row.student_avatar;
}
//on submit execute the following queries
if(IsPost){
if(Request["button"] == "sharestatus"){
//retrieve the data from the form input fields
var statusbody = Request.Form["statusbody"];
var statususername = session_username;
//insert the status for the username into the database
var insertcommand = "INSERT into status(status_body, status_date, status_username, status_firstname, status_lastname, status_avatar) VALUES (#0, #1, #2, #3, #4, #5)";
db.Execute(insertcommand, statusbody, DateTime.Now, session_username, statusfirstname, statuslastname, statusavatar);
}
}
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function get() {
$.post('statusupdateform.cshtml', { name: form.name.value }
}
</script>
<form class="status-form" role="form" action="" enctype="multipart/form-data" method="post" name="form">
<div class="form-body">
<div class="form-group">
<textarea class="form-control" placeholder="What's on your mind?" name="statusbody"></textarea>
</div>
</div>
<div class="form-footer">
<div class="pull-right actions">
<button class="btn btn-primary" name="button" value="sharestatus" onclick="event.preventDefault();get();return false;">Share</button>
</div>
</div>
</form>
This is the code in my cshtml file. I want to submit the form using ajax so that the whole page doesn't get refreshed everytime a user submits anything.
The C# code necessary to run the form is also provided in the code.
Any help how can I submit the for using ajax?
Thank you!
Use Javascript or JQuery for this.
E.g. add script tag with link to jquery code file and then use $.get or $.post to make ajax call.
You should remove
method="post"
From the form as this will make the full page submit. Also you can find more information on how to do this in the Jquery documentation.
See the bottom of this link for an example:
http://api.jquery.com/jquery.post/
Use This to perform your operations
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.
Here is my code:
<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'APPID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('myJSString').value = me.name;
alert(document.getElementById('myJSString').value);
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;
// document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewTitlesStatus_ChangedRowsIndicesHiddenField').value = uid;
// alert('yyy');
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result" class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />
</form>
</div>
</div>
</body>
</html>
You can see there is no server control so how i can get NAME,UID variables in code behind.
Thanks
You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.
Html
<asp:hiddenfield id="ValueHiddenField" runat="server"/>
Javascript
document.getElementById('ValueHiddenField').value = "yourValue";
Code behind
string yourValue = ValueHiddenField.Value;
Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: {'yourParam': '123'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Code behind
[WebMethod]
public static void YourMethod(string yourParam)
{
//your code goes here
}
I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:
Page Method in your code-behind file (call it default.aspx for discussion's sake):
[WebMethod]
public static string SaveData(string name, string uid)
{
// Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}
jQuery call to default.aspx's SaveData method:
$.ajax({
type: "POST",
url: "default.aspx/SaveData",
data: "{'name':'John', 'uid':'ABC123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.
For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods
You can use following method:
<script language="javascript" type="text/javascript">
function returnString() {
var val = 'sampleValue';
return val;
}
</script>
C# Code to get the return value of the above function:
ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");
Or simply as Adil said, can use hidden field and assign value:
<asp:HiddenField ID="hField" Value="0" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="returnString();"
Text="Button" onclick="Button1_Click" />
script for assigning value:
<script language="javascript" type="text/javascript">
function returnString() {
debugger;
document.getElementById("hField").value = "sampleValue";
}
</script>
I am attempting to call a function through a view using jquery.. originally i was using razor's #html.BeignForm but for the web it needs to be converted to jquery
i don't know if i'm on the right path, however this is what i have in razor that's currently working.
#foreach(var up in Model)
{
#up._id
using (#Html.BeginForm("DQPost", "Disqus", new { ID = up._id }, FormMethod.Post))
{
<h7>The thread ID</h7>
<input type="text" name="ThreadID" /><br />
<h7>The message </h7>
<input type="text" name="Message" /><br />
<input type="submit" value="Post Comment"/>
}
}
what i'm trying to do is change the submit to button that then fires off the jquery. and this is the jquery i currently have written out.
<script type="text/javascript">
$(document).ready(function () {
$('#post').click(function () {
var dataToSend = { ID: ID, MethodName: 'DQPost', Message: message };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
});
});
</script>
any help would be greatly appreciated.
You are wrong here,$('#post').
$('#post').click(function () {
Post is not an identifier., so, you could declare your own. You could try something like
<input type="submit" id="submitButton" value="Post Comment"/>
Then,
$('#submitButton').click(function () {
will work fine.
Looks like you want to intercept the form submission so you can handle submit yourself with AJAX. If I'm reading that right, instead of attaching to the button's event, attach to the form's event:
$("#my-form-id").submit(function() {
// do my AJAX stuff
return false; // this will prevent the form from being submitted like normal
});
I have 2 dropdownlist which is already binded on pageload , i want to rebind these two dropdownlist after firing a ajax function.Here i have written a sql server stored procedure to get the data which is needed to dropdownlists.But how i will get the value to dropdownlist,so that it can bind the new data using ajax function.The screen is developed by using Asp.net C# coding.
Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl