My jquery for onclick,
$(document).ready(function () {
$("#submitSave").on("click", function () {
var confirmPassword = $("#txtLgnPasswordConfirmReset").val();
var passwordReset = {
UserName: $("#txtLgnUsername").val(),
Password: $("#hdnOldPassword").val(),
NewPassword: $("#txtLgnPasswordReset").val()
}
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset
});
});
});
Below is my Controller action method which is called on 'ON CLICK' by above jquery,
[HttpPost]
public ActionResult PasswordReset(User user)
{
if (_lfAPI.PasswordReset(user))
{
return RedirectToRoute(Constants.Login);
}
return View();
}
If my, if(condition) in the above method returns true, I want to show a notify message...
My notify message,
notifyMessage.showNotifyMessage('info', 'Your password has been reset.Please login with your new password.', false)
Thanks in advance...
you can handle this in ajax success callback as
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset,
success: function(data) {
if (data == true) {
//show success msg
}
}
});
Use success callback in your ajax call.
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset ,
success: function (resp) {
if (resp == "true") {
// do your stuff here
notifyMessage.showNotifyMessage('info', 'Your password has been reset.Please login with your new password.', false)
}
},
});
});
Related
Firstly, I've been stuck between method and type as if I've defined method in form so I don't have to define it in ajax, and if so? ajax gives undefined in console.
Secondly, The following code gives 405 POST method not allowed.
Also, When I do succeed trying bunch of things ajax refreshes the whole page, I want to post data to server without refreshing the page.
Any help would do!!
Controller Function
public function storeDevSkill(Request $request, $user_id)
{
$this->validate($request,
[
'dev_skill_name' => 'required',
'dev_skill_exp' => 'required',
]);
try {
$data = array(
'dev_id' => $user_id,
'dev_skill_name' => $request->dev_skill_name,
'dev_skill_exp' => $request->dev_skill_exp,
);
DevSkill::create($data);
return back();
} catch (\Exception $exception) {
return back()->withError($exception->getMessage())->withInput();
}
}
Route:
Route::post('/developer/create/skill/{user_id}', 'SuperAdminControllers\DeveloperController#storeDevSkill')->name('store.developer.skill');
Form:
<form id="form_skill" method="POST" enctype="multipart/form-data" action= "{{route('store.developer.skill',$user->user_id)}}">
Button:
<button type="submit" id="addskillSubmit" value="{{$user->user_id}}" style="display: none;" class="btn btn-primary">Save</button>
Script:
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
console.log("Ajax Call")
event.preventDefault();
var action_url = '';
var user_id = $(this).attr('value');
console.log(action_url)
$.ajax({
url: action_url,
type: "post",
data: $(this).serialize(),
// dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
// var table = $('#addskilltable').DataTable();
// table.ajax.reload();
console.log(response.success)
}
}
});
});
});
</script>
You need to pass action attribute from the form to your ajax call like so
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
console.log(response.success)
}
}
});
});
});
</script>
Give it a try and see if that changes anything.
$(document).on('submit', '#form_skill', function(e){
e.preventDefault();
var nFormId = '#'+ $(this).attr('id');
var formData = $(this).serialize();
var url = $(this).attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function (response) {
console.log(response);
$(nFormId)[0].reset();
},
error: function (jqXHR, exception) {
},
beforeSend: function () {
},
complete: function () {
}
});
});
Hope this answer help you.
I'm creating a modal when I click I will pass the id and action to the serverside to save a logs.
Here is my sample code but can't get it to work. I'm using a usercontrol.
$("a.modal_show2").click(function () {
$(this).each(function () {
if ($(this)) {
var storecheckid = $(this).attr("id");
$.ajax({
type: "POST",
url: "TalkTalk.aspx/saveLogs",
data: {
action: 'video_tag',
clickedlinktag: storecheckid
},
dataType: "text",
success: function (response) {
console.log(response);
}
});
}
});
});
[System.Web.Services.WebMethod]
public static string saveLogs(string action, string clickedlinktag)
{
DataHelper.InsertLogs("TalkTalk", Convert.ToInt16(clickedlinktag), Convert.ToInt16(TwwId));
return clickedlinktag;
}
Thanks
data: JSON.stringify({ action: 'video_tag', clickedlinktag: storecheckid })
// response is a wrapper for your data. your data is in `d`.
success: function (response) {
console.log(response.d);
}
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}
I am new to MVC and trying out the ajax functionality on my website. Whenever, I run my ajax function it returns 500 in alert.
This is my controller code
[HttpPost]
public ActionResult JsonNewsfeed(int id)
{
var db = new dekhosaleEntities1();
sale s = db.sales.First(m => m.sale_id == id);
List<sale> sale1 = db.sales.ToList();
saleviewmodel model = new saleviewmodel
{
currentsale = s,
Sales = sale1
};
return Json(model);
}
This is my Jquery ajax function
$('.b1').click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: '#Url.Action("JsonNewsfeed", "Home")',
data:"{ id: 5}",
success: function (data) {
alert(data);
},
error: function (response) {
alert(response.status);
}
});
});
public ActionResult JsonNewsfeed(int id)
{
try
{
....logic here....
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//TODO: log exception
return new HttpStatusCodeResult(401, ex.Message);
}
}
you could also return like this instead:
return Content(jsonObject.ToString(), "application/json");
or
return Content("Your message",...
Then in your ajax call change the success to:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/someDir/someAjaxControllerMethod",
data: jStr,
success: function (json) {
...do something...
var s = JSON.stringify(json);
alert(s);
},
error: function (event) {
alert(event.statusText);
}
});
Try to correct you ajax request ...
like URL...(url: 'Url.Action("JsonNewsfeed", "Home")')
data (data: {id:id}) (if needed check that too)
here is the reference..
Documentation: http://api.jquery.com/jquery.ajax/
I have written one ajax post request on aspx page which will call web method written in its code behind class.This method return url to redirect..All is working fine till success function of ajax call but in success function I'm redirecting to another page ex.
window.location.assign(data.d)
I have checked data.d result via alert in success function which is showing correct url but its not rediecting to that page..Plz help..
Full code is here..
This is script:
<script type="text/javascript">
jQuery(document).ready(function() {
$('#loginbtn').click(function() {
var userName = document.getElementById('uid').value;
var password = document.getElementById('pwd').value;
$.ajax({
type: "POST",
url: "testAjax.aspx/Authenticate",
data: JSON.stringify({ userName: userName, password: password }),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { window.location.assign(data.d); },
error: function(e) {
alert(e.valueOf());
}
});
//alert("dsf");
});
});
</script>
and following is the web method:
[WebMethod]
public static string Authenticate(string userName, string password)
{
try
{
return "Home.aspx";
}
catch (Exception ex)
{
return string.Empty;
}
}
Please note: If I uncomment alert("dsf"),all works fine it redirects successfully to Home.aspx..But without this alert it wont redirect.
try this
success: function(data) { window.location=data.ToString(); }
Try this
<script type="text/javascript">
jQuery(document).ready(function() {
$('#loginbtn').click(function() {
var userName = document.getElementById('uid').value;
var password = document.getElementById('pwd').value;
$.ajax({
type: "POST",
url: "testAjax.aspx/Authenticate",
data: JSON.stringify({ userName: userName, password: password }),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { window.location=data.d; },
error: function(e) {
alert(e.valueOf());
}
});
//alert("dsf");
});
});
</script>