Laravel Jquery Ui Ajax Post to Controller and get value to blade - javascript

I built and basic Jquery Ui slider:
$("#sliderNumCh").slider({
range: "min",
min: 0,
max: 20,
step: 1,
value: 20,
change : function(e, slider){
$('#sliderAppendNumCh').empty();
var getSliderVal = document.getElementById('sliderValue').value = sliderValue;
$('#sliderAppendNumCh').append(
<div class=\"form-group\" style=\"width:100%;margin:0 auto;\">
...
</div>);
},
slide : function(e , slider){
$('#number_of_chapters').val(slider.value);
},
});
My question is now how to post the slider value on each slide to my Laravel Controller.
I tried this:
$.ajax({
type: 'POST',
url: "{{Route('getAjaxRequest')}}",
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {value: getSliderVal},
success: function (option) {
console.log(getSliderVal);
}
});
route:
Route::post('create', ['as' => 'getAjaxRequest', 'uses' => 'ProductController#getAjaxRequest']);
and in my controller I tried to call and return the value like this:
public function getAjaxRequest()
{
$value = Request::get('value');
return view('productRom.edit')->with('value', $value);
}
so basically I want to get the slider value and later on return the value to a php function, to use that value for example in a loop.
I am not used to Ajax and therefor not sure what I am doing wrong.
Edit
I tried Jose Rojas suggestion:
public function getAjaxRequest()
{
$value = Request::get('value');
//do your stuff
return $slideValue;
}
And I get following error in the console:
http://localhost/myapp/public/product/edit/%7BproductID%7D 500 (Internal Server Error)
the actual url is:
http://localhost/myapp/public/product/edit/51
Edit
this is my route:
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);

If I undestand well, you want to get the value for a slide so the method in your controller instead return a view should return the value for the slide, somthing like this:
public function getAjaxRequest($productID)
{
$value = Request::get('value');
//do your stuff
return $slideValue;
}
then, in your method that receives the value, you do what you want with this value. The goal of using AJAX is load parts of web page without reloading whole web page.

Related

retrieve user from database from javascript

I am making an application in Laravel and I need to retrieve a user from the database from javascript, from its id.
Something like:
User :: find (id);
or:
DB :: table ('users') -> find (id);
but in javascript
I would consider using AJAX.
your other JS code
...
$.ajax({
type: "POST",
url: "to your controller",
data: {
'user_id' : user_id,
},
success: function (data) {
userdata1 = data.data1;
userdata2 = data.data2;
...something
}
});
And the controller would look something like this
class SomeController extends Controller
{
public function somefunction(Request $request)
{
$user = User::find($request->user_id);
... do other stuff
return response()->json([
'data1' => someValue1;
'data2' => someValue2;
]);
}
}
If you only need User's data, you can simply use route model binding and
class SomeController extends Controller
{
public function somefunction(User $user)
{
return response()->json([
'data1' => $user->name;
'data2' => $user->addr;
]);
}
}
There might be a better solution, but it works.
Don't know how exactly your code is, but if User's data has been already sent to view from controller, you can just do
var x = "<?php echo $user->somedata ?>"
in you JS code

how can send a jQuery variable value to server side in asp.net

here is my jQuery:
$(document).ready(function () {
var image = $('#man');
var legTooltip = 'LEG';
image.mapster({
fillOpacity: 0.5,
mapKey: 'alt',
fillColor: "000000",
listKey: 'alt',
scaleMap: falsee,
singleSelect: true,
toolTipClose: ["tooltip-click", "area-click", "area-mouseout"],
showToolTip: true,
onClick: function (e) {
if (e.key === 'leg') {
var **symp** = e.key;
}
},
areas: [
{
key: "leg",
toolTip: legTooltip
}],
render_highlight: {
fade: false
}
});
});
now how can i send the value of variable symp into server side cs file and save the value into another server side variable? i have little knowledge about jquery and asp.net. thanks in advance.
If I understand you right, you need to send a post request to server. You can do it by using jQuery method post (which is a shorthand Ajax function).
$.post(
"YourController/YourMethod",
{ symp },
function( response ) {
//proccess the response here
}
);
On the server side add a method in your controller which will get this value
public class YourController : Controller
{
//other methods and fields
[HttpPost]
public ActionResult YourMethod(<type of variable symp> symp)
{
//save this value wherever you want
//return result of your request, so you can proccess it on the client side
//e.g. that operation was successfully completed
}
}
Try ajax:
$.(ajax){(
url : 'url of the file in which yo want to process the data',
method: 'post or get',
data: {
var1 : value1,
var2 : value2
// these variables are available on the specified url
// use your variable(symp) here
},
success: function(response)
{
// response hold the server side response in it.
}
)}
Do not forget to include the jquery library in your code.
If the value of symp needs to be updated continuously, then Ajax would be better as Mayank Pandeys answer.
But if you only need the value on PostBack, a HiddenField would be easiest.
<asp:HiddenField ID="HiddenField1" runat="server" />
if (e.key === 'leg') {
var **symp** = e.key;
document.getElementById("<%= HiddenField1.ClientID %>").value = symp;
}
And then you can use the value of symp in code behind by getting the value from the HiddenField.
string symp = HiddenField1.Value;

Symfony3 send AJAX POST request

I want to send two variables id and commentary through an AJAX POST request.
The problem is that I don't get the POST variable but the route is reached.
JS:
$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }),
function(response)
{
}, "json");
Symfony:
public function saveCommentaryAction()
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$information = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Information')->find($_POST['id']);
$information->setCommentaire(str_replace('\n', '\\n', $_POST['commentary']));
$this->getDoctrine()->getManager()->flush();
$response = array("code" => 100, "success" => true, 'commentary' => $_POST['commentary']);
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
The error:
http://localhost/MyProject/web/app_dev.php/ajax/save/commentary/?id=61&commentary=MyCommentary.
{"code":0,"success":false}
More Symfony error:
GET Parameters
Key/Value
commentary/MyCommentary
id/61
And the routing is case needed:
ajax_savecommentary:
defaults: { _controller: CommonBundle:Default:saveCommentary }
path: /ajax/save/commentary/
options:
expose: true
Try using the request passed to the Controller Action instead of retrieve it from the container. So try this:
use Symfony\Component\HttpFoundation\Request;
...
public function saveCommentaryAction(Request $request)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$isAjax = $request->isXMLHttpRequest();
instead of this:
public function saveCommentaryAction()
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
UPDATE:
You can restrict your routing with Customized Route Matching with Conditions, as example on your case as follow:
ajax_savecommentary:
defaults: { _controller: CommonBundle:Default:saveCommentary }
path: /ajax/save/commentary/
options:
expose: true
condition: "request.isXmlHttpRequest()"
methods: [POST]
UPDATE:
There is a typo in the routing generation in the JS side:
$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }),
function(response)
{
}, "json");
you pass the data as argument of the routing.generate function so it concatenate the params as query string. so try this:
$.post(Routing.generate('ajax_savecommentary'), { id:id, commentary:commentary },
function(response)
{
}, "json");
Another advice is about to use the $request object for obtain the data instead of the superglobal PHP attribute, so use:
$request->request-get('commentary');
instead of:
$_POST['commentary']
More info here in the doc.
Hope this help

Laravel 4 can't get data from Angular Ajax

I am trying to develop my application in Laravel 4 and Angular JS, my application allows user to retrieve their Information through the system via Text Change.
Angular is used to pass data input from the user to Laravel which in turn retrieves the Information from the Database.
However Laravel is unable to retrieve the data passed from Angular.
View
<div data-ng-controller="ReservationController">
<input id='ERI' type='text' data-ng-model="scanRID" data-ng-change="queryRes()" name='exampleInput' maxlength='3' />
</div>
Angular Factory
app.factory('exampleFactory', function($http) {
var factory = {};
factory.getExample = function(scanRID) {
return $http({
method: 'GET',
url: LARAVEL_CONTROLLER + 'Example',
data: $.param(scanRID)
});
};
return factory;
});
Angular Controller
app.controller('exampleController', function($scope, $http, exampleFactory) {
$scope.queryRes = function() {
if($scope.scanRID.length == 3) {
exampleFactory.getExample($scope.scanRID)
.success(function (data) {
// Do Something Here
})
.error(function (data) {
console.log(data);
});
}
};
});
Laravel 4 Routes
Route::get('Example', 'ExampleController#show');
Laravel 4 ExampleController
class ExampleController extends \BaseController {
public function show()
{
$id = Input::get('scanRID'); // This here might be wrong. It's always empty!
$data = ExampleModel::find($id); // Able to query and retrieve.
return Response::JSON($data); // Returns empty.
}
}
Laravel 4 ExampleModel
class ExampleModel extends Eloquent {
// The id of this table is what I want, but I can't retrieve it.
protected $fillable = ['id', 'ExampleData1', 'ExampleData2'];
protected $table = 'exampleTable';
}
I have searched everywhere for a solution, it seems that everyone is able to successfully make the Ajax call. I think there is something that I am missing out that I am unaware about.
I have also tried setting CSRF Token, but however, I do not think that is an issue. So my last resort is to turn to the experts and hope someone is able to help me.
On a side note, I am fairly new to Laravel and Angular, so if you do post a solution, please explain to me the issue as I would like to learn more about Angular and Laravel.
Thank you for reviewing my issue.
You are not passing the value of scanRID by scanRID parameter instead pass only the value without parameter. So you are try to get the value from scanRID using Input::get('scanRID'); but without having scanRID parameter. that should be the case ur not getting the value :)
return $http({
method: 'GET',
url: LARAVEL_CONTROLLER + 'Example',
data: $.param({scanRID:scanRID}) //Change Here
});
OR
return $http({
method: "GET",
url: LARAVEL_CONTROLLER + 'Example',
params: {scanRID:scanRID} //Change Here
);
change like this

Is it possible to use repeating params in ngResours query

I'm using Angular with ngResource and i've got an api url:
GET http://my.com/rest/items?inState=TRANSIENT&inState=FINAL
How could I do query with two (not uniq) params 'inState'?
This is my Resource factory:
.factory('Resource', function ($resource, REST_URL) {
return {
items: $resource(REST_URL + 'rest/items',
{},
{
get: {method: "GET", params: {inState: '#inState'}}
})
};
})
And this is the way I'm call it:
//GET http://my.com/rest/items?inState=TRANSIENT
Resource.items.get({inState: 'TRANSIENT'}, function (data) {
//...
}, function (responce) {
//...
});
This is works but the problem is in how I'm send params - as object: {inState: 'TRANSIENT'}
I cannot write something like
{inState: 'TRANSIENT', inState: 'FINAL'}
beacuse of fields must be uniq
P.S. I know that it may be done with $http.
That's how to do this:
{inState: ['TRANSIENT', 'FINAL']
Example:
//GET http://my.com/rest/items?inState=TRANSIENT&inState=FINAL
Resource.items.getHistory({inState: ['TRANSIENT', 'FINAL']}, function (data) {
//...
}, function (responce) {
//...
});
Not sure if you have control over what is consuming the parameters, but if you do you could try passing the parameters as an object with an array of objects in it, like this:
{ states : [{inState : 'TRANSIENT'}, {inState : 'FINAL'}]}
Then just iterate through the states array and check each inState property.

Categories

Resources