laravel: view not shown after ajax post - javascript

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.

Related

Dynamically inserting HTML into View through AJAX with JS Array in LARAVEL

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
}

Change input name attributes after getting html data from action through AJAX in ASP.NET MVC

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");

pass ID when button is clicked to Action link

I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)
<a class="" href="/LaborerSearchByName/Index">
<img src="/Content/images/b7.png" id="b7"
onclick="bb7();"
onmouseover="bigImg(this)"
onmouseout="normalImg(this)">
</a>
The call for action link
#Html.Action("Menu", "MenuItem", new { id = "MenuId"})
"MenuId" must by a dynamic value based on which button is clicked.
Here goes my solution, use Html.ActionLink() -
#Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { #id = "MenuId" })
Then say you have image control like this -
<img src="/Content/images/b7.png" id="b7"/>
Then you have simple JQuery script to replace query string in this way -
<script>
$(document).ready(function () {
$("#b7").click(function () {
$("#MenuId").attr("href","/MenuItem/Menu/" + this.id);
});
});
</script>
In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7
UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
public JsonResult GetJson(string MenuId)
{
List<string> urls = new List<string>();
urls.Add("https://google.com");
urls.Add("https://bing.com");
return Json(urls, JsonRequestBehavior.AllowGet);
}
Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.MenuId = $("#Menu").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {ou parse data
// This is how we parse returned json string
$.each(data, function (i, item) {
alert(data[i]);
});
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
When you run the code, you should see following view -
When you enter the value and click on anchor tag -
And as a result, you will get all the results parsed -
You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

Symfony2 and jquery ajax

I am developing an application using Symfony2 and Jquery as a JavaScript FW. I am using Twig for the templates. I render a template from the controller and after making a selection using the cursor in the template I would like the value of the selected tag to be returned to the controller when submitting using a submit button in the mentioned template.
I use the next Jquery function:
$("MatchedTag").click(function ()
{
$(this).toggleClass("highlight");
var IdOfTag = this.id;
$.ajax({
url: "{{ path('AcmeAcmeBundle_myaction') }}",
type: "POST",
data: { "tag_id" : idOfTag },
success: function(data) {
//(success) do something...
//variable "data" contains data returned by the controller.
}
});
});
I guess in the controller, in myaction I should use something like $_POST["tag_id"] or getrequest() , bindrequest() to get the value but I dont really know how. Could someone give me an example. Thanks.
You can try to get this parameter by :
$request->request->get('tag_id');
Update
simple action
namespace Acme\HelloBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class HelloController
{
public function indexAction($name)
{
$myParam = $request->request->get('tag_id');
// write your code here
}
}

Categories

Resources