Hi I am new to Laravel having a situation like: I have a HTML form and loading some HTML like "partial.blade.php" using AJAX in Same form, that is working perfectly with static HTML but,
I want to send a JS Array of object with AJAX Request to Dynamically loading HTML Content like: Drop down in same form
Could any Guide me how Can i Pass JS Array to that piece of HTML so i can Render that Array in "partial.blade.php"
here is my code
this is main form HTML & Array i want to pass with this AJAX Request
var dataArray = $('#data1').val();
code included at last in HTML Form Page
$.ajax({
url: "add-property/residential",
type: 'GET',
dataType: 'html',
data: { dataArr: dataArray },
contentType: false,
processData: false,
success: function(response) {
console.log(response);
$('#dynamicForm').html(response);
//alert(response);
},
error: function(response) {
console.log(response);
alert('Error....!');
}
});
here is my Route
Route::any('admin/add-property/residential',function() { return view('admin.residential'); });
all i want to receive that JS array in this piece of HTML that is dynamically loading
When you want to return the contents of a view() to an AJAX request, you can store the view as a variable and return in a JSON response:
public function apiResponse(){
$html = view("admin.residential")->render();
return response()->json(["html" => $html]);
}
In your AJAX request, you can access this as response.html:
success: function(response) {
$("#dynamicForm").html(response.html);
}
To pass a variable from AJAX to the view, you can use the request object. At the top of your routes/api (or routes/web.php, whichever you're using) add use Illuminate\Http\Request;, then in your Route inject that into the function:
<?php
use Illuminate\Http\Request;
...
Route::any('admin/add-property/residential',function(Request $request){
...
});
Not that $request is available, you can access the data being sent in the AJAX request via $request->input("dataArr");, and pass that to the view partial using ->with();:
Route::any('admin/add-property/residential',function(Request $request){
$dataArr = $request->input("dataArr");
$html = view("admin.residential")->with(["dataArr" => $dataArr])->render();
return response()->json(["html" => $html]);
});
According to this
Instead of return view('admin.residential');
You need to do this: return (string) View::make('admin.residential');
Edit
If you want to receive data from the ajax, and then load the view, you could do something like this:
Import the Request.
use Illuminate\Support\Facades\Response;
Make your rote point to a specific method on a controller.
Route::any('admin/add-property/residential',"YourController#returnView");
Make your function to handle the data
public function returnView(Request $request){
$data = $request->all(); // Here you will have all the data you send via AJ
//Make sure the $data has all the necessary parameter to load the view
$view = View::make('my_view', $data);//Here you will pass the data to the view
return response()->json(["html" => $$view->render()]); // Using #TimLewis return
}
Related
I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.
I have a javascript function that sends to a Controller some information (mostly vars like arrays and ids) to be inserted in a table, the problem is after the insertion is completed I want to return to a different view with a data array and i cant seem to do this (I think its because of the ajax request)
Javascript Code
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
window.location.replace(data.url);
}
});
}); // end form.submit
Function Prepare PostData()
var file_data=$('input:file')[0].files;
var postdata=new FormData();
postdata.append('_token',token);
postdata.append('startFrom',startFrom);
postdata.append('idList',idList);
postdata.append('nomeCampos',nomeCampos);
postdata.append('posicaoCampos',posicaoCampos);
postdata.append('file',file_data[0]);
return postdata;
Controller Expected Code
Do all inserts and functions and in the end
$data = array('listNome' => $listName, 'contacts' => $contacts, 'errors' => $erro);
return view("XPTO", $data);
You should not return a view from an ajax call, because you'd get the view processed code as a parameter to the ajax callback. Think of an ajax call as an async 'behind the scenes' call to the server in which you pass parameters and get some other parameters back
You should instead return a JSON response from the controller with all the parameters you'll need to call the route from JS, and parse it in your success callback. For example:
Controller
//here you should store all the parameters you need in your JS calback
$data = array('status' => 'ok', 'url' => $redirect_url );
JS
success:function(data)
{
//data will contain the parameters you set in the controller, so you can use them to call the route
if ( data.status == 'ok' )
window.location.replace(data.url);
}
Just elaborating previous answer , Ajax call controllers are used to supply some data behind the scenes and standard controllers are used to control the view so best practise is to return data (JSON) form Ajax controller to the same view which requested the data. while the standard controller should be used to control the views.
SOLVED
Not the most elegant solution but what I did was set the array with errors as an session variable and get that session var in the specific controller I need.
Controller
$request->session()->put('importErrors',$erro);
$response = array('status' =>'success','url' => '/ListarContactos/'.$idList);
return response()->json($response);
JavaScript
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
if(data.status=='success'){
window.location.replace(data.url);
}
}
});
}); // end form.submit
XPTOController
$errorArray= $request->session()->get('importErrors');
After using it you can destroy the session variable or keep it(depending if you need it or not).
I have a simple ajax request which get from server a generated HTML, like:
$.ajax({
url: '/GetData'
type: "POST",
dataType: "html",
data: ...,
success: function(data) {
// here I want to change `name` attributes of inputs
// before print on page
// but it doesn't work, so, how to manage this ?
$(data).find("input[name='test']").prop("name", "anotherValue");
$("myDiv").prepend($(data));
}
});
and my action is simple:
[HttpPost]
public ActionResult GetData(){
return PartialView("myview", new MyModel());
}
I want to change input name attributes before print them in html page. If I do in success function (see above) then no change is made.
Why ? To to achieve this ?
try something like
$("input").each(function() {
if($(this).prop("name") == "test") $(this).prop("name", "anotherValue");
});
Data cannot be edited unless you append them to the DOM
So, use String.Replace function
var removed=data.replace("name='test'","anotherValue")
.replace('name="test"',"anotherValue");
$("myDiv").prepend(removed);
or do this
$(data).prependTo("myDiv").find("input[name='test']").prop("name", "anotherValue");
I have integrated jQuery into a Spring MVC application. I have a form on my JSP page and I am doing an ajax POST to send the form to the controller:
$("#myform").submit(function() {
$.ajax({
type : 'POST',
url : '/MyApp/search/searchResults',
data : $(this).serialize(),
dataType: 'html',
success : function(data) {
$("#tabs-4").append(data);
}
});
return false;
});
The success function will load the data into a new tab. What I am finding is that data returns the HTML of my original page (from which I submitted). Instead, I would like to be able to parse the ModelAndView object that is being returned from the controller. For example:
${searchResults.searchStr}
Is it normal for data to return the page HTML? Is there anyway that I can parse the ModelAndView object in the success function, and then pass it to my new tab div?
Here is my Controller code:
#RequestMapping(value = "/searchResults", method = RequestMethod.POST)
public ModelAndView searchResults(
#ModelAttribute(value = "search") SearchVO search,
BindingResult result) {
// Set the view and search object
ModelAndView mv = new ModelAndView("newSearch");
mv.addObject("searchResults", searchResults);
return mv;
}
Thanks!
Yes you can return the html content from the controller to your ajax function. If you are interested in to use the instance in the jsp you would have to serialize it in to json and send it. Using jquery you could render it on the jsp. For example,
//Controller
public #ResponseBody<Class_name> search(...){
return searchResults;
}
//jsp
function renderResult(){
$.ajax({
url:'url',
dataType:'json',
...
..
success: function(data, status, xhr){
$.each(data, function(k, v){
$('#my_div').append(...k,v...);
}
}
});
}
Looking at your requirement I would suggest you to use the first method where you return the html itself and the jsp page which you return could be render with the searchResults.
I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)