I found similar questions to mine, but in all of those examples, the variable was part of the model. I am trying to pass a variable that is created in javascript, which is not part of the model.
Code:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "##mymail.ca";
/* Check directory to see if this email exists */
#Html.Action("CheckDirectory", "Home", new { email = ???});
}
});
Is there a way to fill in the ??? with the email above?
You can pass your value as a GET parameter in the controller URL:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "##mymail.ca";
/* Check directory to see if this email exists */
window.location.href = '/CheckDirectory/Home?email=' + email;
}
});
To answer your question of
Is there a way to fill in the ??? with the email above?
No. The Razor code is similar to, say, PHP, or any other server-side templating language - it's evaluated on the server before the response is sent. So, if you had something like
#Url.Action("checkdirectory", "home")
in your script, assuming it's directly in a view, it would get replaced by a generated URL, like
/home/checkdirectory
Your code, which uses
#Html.Action("checkdirectory", "home")
actually executes a separate action, and injects the response as a string into the view where it's called. Probably not what you were intending.
So, let's try to get you on the right path. Assuming your controller action looks something like
[HttpGet]
public ActionResult CheckDirectory(string email = "")
{
bool exists = false;
if(!string.IsNullOrWhiteSpace(email))
{
exists = YourCodeToVerifyEmail(email);
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
You could, using jQuery (because XMLHttpRequests are not fun to normalize), do something like
$(function(){
var url = '#Url.Action("checkdirectory", "home")';
var data = { email : $('#email').val() };
$.get(url, data)
.done(function(response, status, jqxhr) {
if(response.exists === true) {
/* your "email exists" action */
}
else {
/* your "email doesn't exist" action */
}
})
.fail(function(jqxhr, status, errorThrown) {
/* do something when request errors */
});
});
This assumes you have an <input /> element with an id of email. Adjust accordingly. Also, the Url helper can only be used within a view; if you're doing this in a separate JavaScript file, replace it with a hard-coded string (or whatever else works for you).
Edit:
Since it seems I didn't entirely get what you were trying to do, here's an example of returning a different view based on the "type" of user:
public ActionResult ScheduleMe(string email = "")
{
if(!string.IsNullOrWhiteSpace(email))
{
ActionResult response = null;
var userType = YourCodeToVerifyEmail(email);
// Assuming userType would be strings like below
switch(userType)
{
case "STAFF":
response = View("StaffScheduler");
break;
case "STUDENT":
response = View("StudentScheduler");
break;
default:
response = View("ReadOnlyScheduler");
break;
}
return response;
}
return View("NoEmail");
}
This assumes you would have 4 possible views: the three you mentioned, plus an "error" view when no email parameter was given (you could also handle that by redirecting to another action). This variation also assumes a user has somehow navigated to something like hxxp://yourdomain.tld/home/scheduleme?email=peter#innotech.com
Related
I am trying to verify username and other fields while creating a change password page.The problem is AJAX call in Jquery script is not hitting my controller.i tried giving hard coded path also in url field of the ajax request.
Below is my Script
this checkUname function is triggering on onblur event from one of the input field.
<script type="text/javascript">
function checkUname()
{
// get the form values
var uName = $('#username').val();
var secQues = $('#secQues').val();
var secAns = $('#secAns').val();
var dataObject = JSON.stringify({
'uName' : uName,
'secQues': secQues,
'secAns' : secAns
});
$.ajax({
url:"validateCredentials.do" ,
type: "POST" ,
data: dataObject ,
contentType: "application/json; charset=utf-8" ,
dataType : 'json' ,
success: function(response)
{
alert(response);
} ,
error: function()
{
alert('Error fetching record.... Sorry..');
}
});
}
</script>
This is my MVC controller
#Controller
public class ArsController
{
#RequestMapping(value="validateCredentials.do", method = RequestMethod.POST)
public String changePass(#RequestParam("uName") String uName ,#RequestParam("secQues")String secQues,
#RequestParam("secAns") String secAns)
{
System.out.println("AJAX request");
Users dummyUSer = null;
String msg = null;
try
{
dummyUSer = servObj.findUser(uName);
}
catch (ArsException e)
{
System.out.println("error occurred while validating user data during password change");
e.printStackTrace();
}
if(dummyUSer == null)
{
msg = "No user exists with this username";
}
else
{
if(!secQues.equals(dummyUSer.getSecQues()))
{
msg = "Security question is not correct";
}
else
{
if(!secAns.equals(dummyUSer.getSecAns()))
{
msg = "Security answer does not match";
}
}
}
return msg;
}
Instead of using RequestParam in controller, you should use String. Because when we are posting JSON data it will not come as individual parameters in Request, instead it will be received as String in your controller. Once you get the String convert it to JSON object and then get your values accordingly.
try remove content-type and data-type.
You are not sending a json that should be parsed in a object, you are sending controller's parameters.
The way to do that is using an object in the Ajax 's data (as you did) but without the content-type or data-type that saying "I'm sending one json parameter"
I have this jquery code in my view file
$('#ticket-ticket_impact_id').change(function() {
var priority = $('#ticket-ticket_priority_id :selected').val();
var impact = $('#ticket-ticket_impact_id :selected').val();
if ($('#ticket-ticket_priority_id').val() == '' || $('#ticket-ticket_impact_id').val() == '') {
} else {
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' + priority + '&ticket_impact_id=' + impact);
}
})
$('#ticket-ticket_priority_id').change(function() {
var priority = $('#ticket-ticket_priority_id :selected').val();
var impact = $('#ticket-ticket_impact_id :selected').val();
if ($('#ticket-ticket_priority_id').val() == '' || $('#ticket-ticket_impact_id').val() == '') {
} else {
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' + priority + '&ticket_impact_id=' + impact);
}
})
from here the value the of priority and impact id is sent to the controller/ajax function
public function actionAjaxTicketSla(){
$ticket_priority_id=$_REQUEST['ticket_priority_id'];
//var_dump($ticket_priority_id);die();
$ticket_impact_id=$_REQUEST['ticket_impact_id'];
if(Sla::find()->where(['ticket_priority_id'=>$ticket_priority_id,'ticket_impact_id'=>$ticket_impact_id])->exists())
{
} else{
echo '<script type="text/javascript">alert("No sla defined!");</script>';
}
}
I am not able to even echo something in response here don't know whats wrong here any help would be appreciated.
response
You are mixing POST , GET and REQUEST
in ajax you use a POST but don't send nothins as POST param
instead you pass param in url as GET params
and in action you look for REQUEST but not for GET (or post)
And you access directly to the $_REQUEST instead of using yii2 method for this
You should rethink you code ..
anyway just as a first step
looking to your ajax call you could use the param you pass as get param
public function actionAjaxTicketSla(){
$request = Yii::$app->request;
$get = $request->get();
$ticket_priority_id=$get['ticket_priority_id'];
//var_dump($ticket_priority_id);die();
$ticket_impact_id=$get['ticket_impact_id'];
if(Sla::find()->where(['ticket_priority_id'=>$ticket_priority_id,'ticket_impact_id'=>$ticket_impact_id])->exists())
{
echo 'OK';
} else{
echo 'No sla defined';
}
}
and in client post
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' +
priority + '&ticket_impact_id=' + impact,
function(data){
if (data !='OK') {
alert(data);
}
});
Try Echo in the If condition also and share the "response" (of page) from Network console.
Sending javascript code from the PHP server to js isn't a good practice. What you are doing is essentially making a call to the server and sending it the data and not doing anything with the resposne you've received.
Try to create a proper callback function like shown in this example,
Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):
function returnData(param) {
console.log(param);
}
Now add that callback function as a parameter to your AJAX function, and lets run it:
function getCartProduct(id, callback){
$.post('sever.php',
function(data){
callback(data);
});
}
getCartProduct(id, returnData);
Also the server's response is treated as a string in javascript. To evaluate it as a javascript syntax, pass the string into the eval() method.
eval('alert("this works");');
I'm having an issue where a modal window pops up in my browser after I return to the View from the controller. Here's what the window says (in Chrome):
It contains the html code from Index.cshtml page.
Here is the code in my controller:
public ActionResult Save(Events changedEvent,FormCollection actionValues)
{
string action_type = actionValues["!nativeeditor_status"];
var eventText = actionValues["text"];
var eventStart = actionValues["start_date"];
var eventEnd = actionValues["end_date"];
try
{
switch (action_type)
{
case "inserted":
if (User.IsInRole("Admin"))
db.Event.Add(changedEvent);
Send(eventText, eventStart, eventEnd);
break;
case "deleted":
//changedEvent = db.Event.SingleOrDefault(ev => ev.Id == source_id);
changedEvent = db.Event.SingleOrDefault(ev => ev.text == eventText);
db.Event.Remove(changedEvent);
break;
default: // update
//changedEvent = db.Event.SingleOrDefault(ev => ev.Id == source_id);
changedEvent = db.Event.SingleOrDefault(ev => ev.text == eventText);
UpdateModel(changedEvent);
break;
}
db.SaveChanges();
}
catch (Exception)
{
action_type = "error";
}
return RedirectToAction("Index", "Home");
}
Here is the code from my Index.cshtml page that handles saving to the database:
function init() {
var dp = new dataProcessor("/Home/Save");
dp.init(scheduler);
dp.setTransactionMode("POST", false);
}
I'm still fairly new to MVC and have completed a few tutorials but I have never ran into this behavior before. I was thinking I have to handle the callback from the controller but all my searching hasn't yielded anything so far. I'm hoping someone from this fine community can point me in the right direction.
Thank you for taking the time to read!
You won't be able to redirect from your C# controller if you are using an AJAX request (your dataProcessor is making an AJAX POST request internally).
You have two options:
1) Not to use your dataProcessor, and make a request to the server using the default C# MVC binding like this: https://stackoverflow.com/a/7856996/3638529. With this method, you will be able to return a RedirectToAction() and the user will be returned correctly, but this will probably change your infrastructure a lot.
2) Change your controller to return the url to redirect.
First change your save method to return something like this:
public ActionResult Save(Events changedEvent,FormCollection actionValues)
{
...
return Json(new {success = true, url = Url.Action("Index", "Home")});
}
Then change your JavaScript method to make something like this when your AJAX request is complete:
function myAwesomeSuccessCallback(response) {
if (response.success) {
window.location = response.url;
}
else {
//show error
}
}
I posted on the dhtmlx forum and I was able to get a solution from one of their support staff. I'm posting his answer in full below:
Hello,
here is what happens in your code
1) when you change something in scheduler (e.g. create/delete/modify event), scheduler sends a POST request to Home/Save, as defined in dataProcessor inside init() function()
2) dataProcessor sends post request and expects the server response to match a certain format of json or xml https://docs.dhtmlx.com/dataprocessor__ ... nsedetails
3) Your Save action outputs the html page instead of the expected response, this line:
return RedirectToAction("Index", "Home");
4) client-side fails to parse it as a valid response and pops up a message.
In order to fix the issue, you need to return a valid response from the Save action, it can be done by replacing your current response - return
CODE: SELECT ALL
RedirectToAction("Index", "Home"); //with this:
return Content(
new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(
new System.Collections.Generic.Dictionary<string, string>
{
{"action", action_type},
{"tid", eventId}
}
)
);
// will send response like this {"action":"updated", "tid":"5"} - which is valid response
Please note "tid" - eventId part, if you insert event into db - you have to send new database event it back to the client. If it's any other operation - you can either return the same id as came from the client or omit "tid" field from the response.
This did the trick for me. Thank you all for your comments and I hope my question helps someone else in the future.
This is my action:
[HttpGet]
public virtual ActionResult DesignItemsList(int dealId, string sort)
{
return View(MVC.Designer.Views._DesignItems, _designerService.GetDesignItems(dealId, sort));
}
The GetDesignItems() method is working correctly.
$(document).ready(function() {
$('.product__filtr__form__select').change(function(e) {
var sort = $(this).val();
var urlFilter = $('#url-filterPanel-hidden-field').val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
$.ajax({
type: "GET",
data: {
dealId: dealId,
sort: sort
},
url: urlItems,
success: function (result) {
console.log(result);
$('#Product-Items-Container').html(result);
}
});
});
});
Request is working too, but I don't receive the response and get only 500 code.
500 error code means, Internal server error. Your action method failed to process thie request you sent.
Since it is a GET action method, You may add the query string parameters to the url.
var sort = $(this).val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
urlItems = urlItems+"?dealId="+dealId+"&sort"+sort;
//Let's write to console to verify the url is correct.
console.log(urlItems);
$.get(urlItems,function(res){
console.log('result from server',res);
$('#Product-Items-Container').html(res);
});
Try to replace the view name inside your controller:
return View("YourControllerView", _designerService.GetDesignItems(dealId, sort));
Because I was tested your ajax request and find out that it works fine.
And pay attention to view location. This view must be located inside the directory with the same name as your controller or inside the shared dictory
I work on an ASP.NET MVC project.
I have to pass two parameters to an action in my controller. the first is a serializable object, and the second one is an integer.
First time I tried to pass only one parameter, the serializable object. There is no problem, but when I add the second parameter, the serializable object doesn't delivered (null value), but the integer parameter delivered successfully.
this is my action look like :
[HttpPost]
public bool MyAction(MySerializableObject myData, int intParameter)
{..}
and this is how I try to pass the parameters :
$('#submit-button').click(function () {
var formData = $("#MyForm").serialize();
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, { myData: formData, intParameter: '5005' }, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});
});
Anyone can explain about it ? how can it happens and how to solve the problem ?
thanks.
this may be a bit of a longshot but have you tried swapping the order of the parameters around (IE public bool MyAction(int intParameter, MySerializableObject myData) The reason im asking is that it may be that your client side serialize isnt working quite right.
If not your best bet is to take a look at whats actally getting posted to the server. Open up firebugs net tab or similar in webkit and take a look at whats actually going back to the server.
You could use the following plugin (serializeObject) instead of .serialize:
var formData = $('#MyForm').serializeObject();
// add some data to the request that was not present in the form
formData['intParameter'] = 5005;
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, formData, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});