how to pass form data to controller - javascript

I am not getting how to pass data to the controller to update data, below I have given code.
// below is my jquery which I am using to pass form data to the controller.
function editProfile(profileData){
$("#profile_name").val(profileData.name)
$("#profile_id").val(profileData.id);
$("#profile-modal-lg").modal('show');
$("#profile-form").attr('action',"text/edit/"+profileData.id);
}
// below is my route
Route::post('text/edit/{profile}', 'profileController#editProfileData')->name('profile.edit');
// inside controller I am having a function called edit profile
public function editProfileData(Profile $profile,profileRequest $request){
$profile->update($request->all());
return redirect()->back();
}

Is your form method set to 'POST'? If not, try setting the form method attribute to 'POST'. You might also want to add slash at the start of your url to target the absolute url.
$("#profile-form")
.attr('method', 'POST')
.attr('action', `/text/edit/${profileData.id}`);

Related

Inertia Manual Share State Lazily Inside Controller not Working

I'm going crazy because of this one, I have this address form in a very nested component and a route to validate the form input data. In the controller, I want to return back to the same page but share the form data to be able to fetch it in a parent component. I'm trying to follow Inertia DOCs to lazily share the data to be available to all components but for some reason this isn't working!
1- I'm submitting the form:
const submitAddressCheck = () => {
shippingDetailsForm.post(
route("cart.checkaddress", [props.webshop_slug]),
{}
);
};
2- The form gets validated as expected but it doesn't share the data globally to all components.
CartController.php
public function checkaddress(StoreAddressCheckRequest $request)
{
Inertia::share(
'testing',
fn ($request) => $request
? $request
: null
);
return redirect()->back();
}
Once I submit the form it gets validated and that's it, no new props passed, the data isn't being shared to my parent component or anything. Am I missing something?
Inertia::share() will not persist any data passed between requests. So if you share data and then redirect to another route, then your shared data will not be passed.
You are probably looking for Flash messages. With flash messages you use the with() method when redirecting to show errors, success messages, anything you like. Make sure you follow the documentation and add the code to the HandleInertiaRequests middleware.
When it is time to redirect, you do something like this:
return redirect()->back()->with('testing', $request->all());

Laravel / Php function behavior

Is there a way to pass the information obtained in a Request function to an included page? Consider the following situation - code below works as expected
public function myFunction(Request $request){
$validator = \Validator::make($request::all(), [
'myField' => 'Required',
]);
}
But what I want to do this
public function myFunction(Request $request){
include(app_path() . '/myfunction/validateThis.php')
}
Where the above file named validateThis.php has the validator code inside? Is there a way to get this (Request $request) variable passed through to the include? It returns null right now and I'm not sure if there is a workaround or not
Once the validateThis.php has been included, all you need to do is pass the request object to the function that handles the validation.
Include file that has the validate function
include 'validateThis.php'
call function with the request object passed to it
validate($request)
Create a global variable to save the $request data. Then use global <variable> in your function inside the included file.

Call Action in Controller From View and send parameter

I am trying to call a method inside a controller in MVC from a javascript action. The javascript action is supposed to invoke this method inside the controller and send some parameters to it.
My Javascript code looks like this:
location.href = '#Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)';
My Method is defined as follows:
[HttpGet]
public ActionResult MyMethod(int? MyId)
{
doSomething(MyId);
return View("MyView");
}
However, when i debug the application, when the method is called the MyId parameter is passed as null and not as the current value of the MyId parameter in my model. What can I do to correctly send or retrieve this value? Thanks!
In your route definition I suppose that the parameter is called {id} and not {MyId}:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyArea_default",
"MyArea/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
So try to be more consistent and adapt your controller action parameter name accordingly:
[HttpGet]
public ActionResult MyMethod(int? id)
{
doSomething(id);
return View("MyView");
}
Also you probably wanna use url helpers instead of hardcoding some url patterns in your javascript code:
window.location.href = '#Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';
The Url.Content helper is used to reference static resources in your site such as javascript, css and image files. For controller actions it's much better to use the Url.Action helper method.

JSON object from ASP.NET controller to view

I have a situation where a when a web page is accessed a controller action runs which retrieves the data for that page based on a user selection. I am attempting to send the data back to the page as a JSON object, however, the data opens up as one large string in an HTML page. The controller action, in a nutshell, looks like the following snippet:
Public JsonResult MyMethod(string userSelection)
{
string userData = (string) Data;
return Json(userData, “text”, JsonRequestBehavior.AllowGet);
}
I first tried to use the JQuery $.getJson() method but I think this is wrong as I believe it issues another call to the action method for the data, which is not what I want to do. What I want is to access the JSON object in JavaScript code so I can use the property data to populate fields on the web page. The basic question is what must I do in my JavaScript to receive the JSON object when the page is first rendered? I apologize if I am missing something fundamental; this is my first try.
I still had no luck today but when I left work I came up with a strategy walking to my car. A user makes a selection from a page that presents a list prior to entering the page on which I cannot figure out how to work with JsonResult. Part of the problem is the user selection contains a link that calls the controller/action that returns the JsonResult which conflicts with using $.getJson() within the page where I want to work with JsonResult. So here is my strategy: When the user makes the selection that brings them to the (problematic) page, I will call a controller/action that strictly works with (ASP) ViewData, and use the ViewData to initially present that page. Once on the page, the user can change the selection -- I will handle this with a JavaScript event that uses a $.getJason() call to a different controller/action method that works with (ASP) JsonResult. After I try this strategy I shall post my results for whomever is interested.
You want parseJSON not getJSON
http://api.jquery.com/jQuery.parseJSON/
Edit - Oh wait you are pointing your browser at the JsonResult as if it was an ActionResult? That is not going to work.
Render a proper view, and use getJSON to call the JsonResult action.
getJSON is what you are looking for. Call that on the DOM ready event which will executes once the DOM finishes loading.
$(function(){
//This code will be executed on the DOM ready ( when the page is loaded)
$.getJSON("YourControllerName/MyMethod?userSelection=someValue",function(data){
alert(data.FirstName);
alert(data.AnotherPropertyName);
});
});
getJSON is a shorthand of jQuery ajax method with datatype set as json
Assuming your JSON data you are retuning is something like this
{
"FirstName": "Scott",
"AnotherPropertyName": "SomeValue"
}
To return data like above, change your Action method like this
public JsonResult MyMethod(string userSelection)
{
var result=new { FirstName="Scott", AnotherPropertyName="Great"};
return Json(result,JsonRequestBehavior.AllowGet);
}

Send a string parameter to a controller (MVC3) from javascript (no ajax)

I have this simple javascript code:
var value = "I love programming";
window.location="Controller/Action/"+value;
In controller page, I have this:
public ActionResult(string value) {
// do something
}
The problem is value parameter from controller. This is always null.
Why ?
Is the parameter type is restricted to int? (without using ajax)
I can send an int to controller and it process the information correctly. But not string.
You may need to set up a route in global.asax to handle the string parameter, i.e:
RouteTable.Routes.MapRoute(
"ValueRoute",
"{controller}/{action}/{value}",
new
{
controller = "Yourcontroller",
action = "Youraction",
value = UrlParameter.Optional
}
);
this is all top of the head stuff, so it may not happen for you.
[update 1] as you say in the comment below, changing the parameter name from value=>id should resolve the problem without recourse to addtional routes.
[update 2] - you could also, as per sandeep's comment, opt for the name-value pair on the url, i.e. window.location="Controller/Action?value="+yourValue

Categories