How to show response from AJAX call to Spring controller method? - javascript

How do I display the response of a call to a Spring MVC Controller returning HTML? In my Javascript code I make a (GET) call to my Spring Controller. From what I can make is that the response from the call is HTML. I guess I need to replace 'alert(response)' with Javascript to display the html.
My Javascript code:
$('#parcelsTable').on( 'click', 'tr', function () {
var data = table.row( this ).data();
$.ajax({
url:"/parcel/showFormForUpdate",
type:"GET",
data:{parcelId:data.parcelId},
success: function(response){
alert(response)
}
});
} );
My controller code in Spring:
#GetMapping("/showFormForUpdate")
public String showFormForUpdate(#RequestParam("parcelId") int theId, Model theModel) {
Parcel theParcel = parcelService.findById(theId);
theModel.addAttribute("theParcel", theParcel);
return "parcel-form";
}
Here "parcel-form" is the name of a template.

$('#parcelsTable').on( 'click', 'tr', function () {
var data = table.row( this ).data();
$.ajax({
url:"/parcel/showFormForUpdate",
type:"GET",
data:{parcelId:data.parcelId},
success: function(response){
$.get(response.html, function(data, status){
$("#ID").html(data);
});
}
});
} );
response.html is the page you want to show on the success of get request. Just make a get request to the response.html file or any template file and put this file in any div where you want to show it.
Hope that it works

Related

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:
Route::get('/plots', 'PlotController#index');
Route::get('/plots/{testId}', 'PlotController#getData');
The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:
GET http://homestead.test/plots/1 500 (Internal Server Error)
I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?
EDIT:
After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:
return $request->test_id;
It actually returns a more complex structure:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:
public function getData(Request $request) {
Log::debug("made it to PlotController.php#getData");
Log::debug("test_id="+$request->testId);
And here is the log output:
[2020-02-23 16:43:52] laravel.DEBUG: made it to
PlotController.php#getData
The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:
testId=49 jquery.min.js:2 GET
http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server
Error)
Any ideas?
The easiest way is to get the data in Laravel Request. At least that's how I do it.
So your route shouldn't contain any parameter for that.
Your route will look like this:
Route::get('get-data-by-id', 'PlotController#getData')->name('get.data.by.id');
Your ajax should be like this:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
In your controller's getData() function just use Laravel Request to fetch the data.
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
Make it post from Get for easier
At Web.php
Route::post('/list/plots', 'PlotController#getData')->name('getData');
At Blade file Ajax Request :
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
At Controller :
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
Try this. Hopefully work for you

how to fetch specific row from database using jquery in laravel and bind it textbox field

i want to fetch specific row data form database based on id using jquery ajax in laravel 5.4,but it does not work. no error from laravel framwork,
this my jquery part.
$(document).ready(function(){
$('#batch').change(function(){
var batch_id=$(this).val();
$.ajax({
url:"<?php echo route('selectbatch')?>",
method:'post',
data:{batch_id:batch_id},
success:function(data)
{
$("#test").html(data.batch);
}
});
});
});
and this is my controller part.
public function selectBatchinfo(Request $request)
{
$bid=$request->input('batch_id');
$batchinfo=DB::table('batches')->where('id',$bid)->pluck('s_amt');
$data = view('register',compact('batches'))->render();
return response()->json(['batch'=>$data]);
}
code of your view similar to like this. pass token with post method.
$(document).ready(function(){
$('#batch').change(function(){
var batch_id=$(this).val();
$.ajax({
url:"{{ route('selectbatch')}}",
method:'post',
data:{batch_id:batch_id,'_token':"{{csrf_token()}}"},
success:function(data)
{
$("#test").html(data.batch);
}
});
});
});
in your controller
public function selectBatchinfo(Request $request)
{
$bid=$request->batch_id;
$batchinfo=DB::table('batches')->where('id',$bid)->pluck('s_amt');
return $batchinfo;
}
in your route file
Route::post('selectbatch','YOUR_CONTROLLER#selectBatchinfo')->name('selectbatch');
try this it may work for you.

Class Yii is not found when posting a variable with ajax

I want to get a variable from ajax to php. I'm using the Yii framework.
So my problem is, when I want to transfer a variable from ajax to a php script I get this error:
Fatal error: Class 'Yii' not found in
/var/www/vhosts/adappter.de/comamos/protected/views/store/search_area.php
on line 44 store.js:1308:13
This is how my Ajax Call looks like
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "../protected/views/store/search_area.php",
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
and this is my php script to line 44
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION['search_type']='';
if (isset($_GET['s'])){
$_SESSION['kr_search_address']=$_GET['s'];
$_SESSION['search_type']='kr_search_address';
}
unset($_SESSION['kr_item']);
unset($_SESSION['kr_merchant_id']);
$marker=Yii::app()->functions->getOptionAdmin('map_marker');
if (!empty($marker)){
echo CHtml::hiddenField('map_marker',$marker);
}
?>
The jQuery call is only when I click on a checkbox. So the value of the selected box gets pushed in an array. I want to return the array to the php script.
When I'm loading the site, I don't get such an error. So I don't know why this error occurs.
You need to use controller with action. Not only view file. You try to call view file from web. But it is wrong, because all code in protected directory. All requests must processing from index file. In index file connected framework. Here a small example. Controller:
class SiteController extends Controller
public function actionTest()
{
//... example
echo CHtml::button('test');
}
js:
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "/site/test", // url for your action
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});

Global update data returned by ajax

I've a code like this:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
I want to update the data returned by ajax using some global method
the code for updating a data will be loaded from the different file, so it can't be stored inside the current $.get function.
once data is updated by some global function, $.get should receive an updated code, not the original one
data should be updated for the HTML data only, not json or any other type of data
I know there's a global function available to handle success on ajax calls:
$(document).ajaxSuccess(function() {
$( ".log" ).text( "Triggered ajaxSuccess handler." );
});
The problem is, this function just receives data, I'm not sure how the data can be updated through this function.
Any ideas?
I guess you can use ajaxSetup function and set filter here like this:
$.ajaxSetup({
converters: {
'text html': function (data) {
console.log('haha! I\'ve stolen your data!');
console.log(data.substring(0,100));
return 'no data :)';
}
}
});
$.get('http://fiddle.jshell.net')
.success(function(data) {
console.log('I got:' + data);
});
In this DEMO only html data will be changed.
EDIT:
I used filter for text html (contains 2 identifiers: from type and to type) because it is mentioned in jQuery docs:
{"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}
As I see it defines covertion from text to html. Usually there is no conversion, but you can add your own, which can modify data as you want.
EDIT2
If you want you can use the following "durty hack":
var originalFunc = $.get;
$.get = function() {
return originalFunc.apply(window, arguments)
.then(function(data) {
return 'no data again :)';
});
};
One more DEMO.
Or, dataFilter as follows:
$.ajaxSetup({
dataFilter: function(data) {
//console.log(data);
return 'sorry, guys, I lost data again';
}
});
$.get('http://fiddle.jshell.net')
.success(function(data) {
console.log('I got:' + data);
});
Next Demo.

How to export a model function from a controller to a view in Laravel 4

I am trying to display some data from my database that is dependent on some input from the user. I am using an ajax request to get the data, send it back to a function in my controller, and then export it back to my view. I would like to collect this data and display it without going to another view (I just hide the previous form and unhide the new form).
Here is the relevant code:
Javascript:
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
Controller functions:
public function pick_favorite() {
$fbid=Input::get('fbid');
return Artist::specific_artist($fbid);
}
public function getWelcome() {
return View::make('fans.welcome')
->with('artists', Artist::artists_all())
->with('favorite_artist', Artist::favorite_artist())
->with('pick', FansController::pick_favorite());
}
Model function:
public static function specific_artist($fbid) {
$specific_artist = DB::table('artists')
->where('artists.fbid', '=', $fbid)
->get();
return $specific_artist;
}
The view is on the "welcome" page. My question is how do I display the model data in my view and make sure it is printing out the correct data from the fbid input?
I tried something like this:
#foreach($pick as $p)
<span class="artist_text">{{$p->stage_name}}</span>
<br>
<span class="artist_city">{{$p->city}}</span>
#endforeach
but this is not printing out anything. Any ideas?
i see lots of issues here.
Server side:
public function pick_favorite().... what does it do? it just returns some data.
in public function getWelcome() { , you wrote, FansController::pick_favorite(). supposing both are the same method, you are accessing a static method whilst the method is non static. you are getting an error for this but you are not seeing it because you didn't define fail().
and i don't see what the point of declaring a method which does nothing else then a model call which you can do directly.
e.g let's say i have a fooModel
public function index(){}
in controller, i can just write,
public function bar()
{
$model = new fooModel;
return View::make(array('param1'=>$model->index()));
}
or if i declare index() method in fooModel as static, then i can write,
public function bar()
{
return View::make(array('param1'=>fooModel::index()));
}
Client side:
now in your javascript,
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
why it should print any data? you didn't asked the script to print anything. where is your .done or .success param in your code?
If you look at your console, you'l get lots of php errors, i am almost sure of.
an advice, you need to lear some basics. e.g. jquery ajax call.
a basic ajax call can be
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
implement it in your code and then see what errors it throws.
Conclusion:
1st one will be (supposing rest of your codes are ok) the static error. if you want to call it as static, declare it as static. but a static function in controller? i don't see any purpose of it.
and then start the debug. your problem is both client and server side. deal one by one.

Categories