This is the view, the success function should make changes in the <p id="mondiv"></p>tags.
<input type="button" value="Refuser" class="refuser" id="{{ demande.id }}">
<p id="mondiv"></p>
<script>
$(".refuser").click(function () {
$.ajax({
url: '{{ path('verifier_demandes') }}',
type: 'POST',
data: {'id_demande': this.id},
dataType: 'json',
success: function (data) {
$.each(data,function (i,e) {
$('#mondiv').append('<ul>'
+'<li>'+e.id+'</li>'
+'<li>'+e.etat+'</li>'
+'<li>'+e.user.nom+'</li>'
+'<li>'+e.user.prenom+'</li>'
+'<li>'+e.user.username+'</li>'
+'</ul>');
})
},
error: function(data) {
alert('error');
}
})
}
);
This is the controller, the entity gets deleted like intended but since then i can't change my view element ( the success function )
if($request->isXmlHttpRequest())
{
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
$gerant = new Gerant();
$gerant = $em->getRepository("GestionBoutiquesBundle:Gerant")->findOneBy(array('id' => $id_gerant));
$em->remove($gerant);
$em->flush();
$demandes = new Gerant();
$demandes=$em->getRepository('GestionBoutiquesBundle:Gerant')->findBy(array('etat'=>false));
$ser= new Serializer(array(new ObjectNormalizer()));
$data=$ser->normalize($demandes);
return new JsonResponse($data);
}
}
I have looked from both sides, the controller sending back the Json response, and from the view, but couldn't find any result.
EDIT: knowing that the $demandes i'm trying to send back with Json is an array of users, each user has an id, etat, nom, prenom, username..
You made a POST request so you should be able to access to the post data as follow:
$id_gerant = $request->request->get('id_demande');
if($id_gerant) {
....
instead of:
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
....
As described here in the doc Symfony Request Object
Hope this help
Related
i am using symfony 3.4 , i want to execute a controller action on a button click in my twig template , that's why i used ajax for that :
first i added the ajax route :
ajax_route:
path: /ajax_request
defaults: { _controller: offerBundle:Default:ajax }
methods: [post]
then the controller action :
public function ajaxAction(Request $request)
{
$personnage = $request->request->get('personnage');
dump($request->request);
$wishlist = new wishlist();
$wishlist->setUserid($personnage);
$wishlist->setOfferid(1);
$em=$this->getDoctrine()->getManager();
$em->persist($wishlist);
$em->flush();
}
the ajax part :
<script>
$('.btn').click( function(){
var personnage = 3;
$.ajax({
url: "{{ path('ajax_route') }}",
type: "POST",
dataType: "json",
data: {
"personnage": personnage
},
async: true,
success: function (data)
{
console.log(data)
}
})
});
</script>
this is my html button :
<button id="wishlist" class="btn">add to wishlist</button>
what happens when i click on the button is i do get this error log :
1 AJAX request
Method :POST Type:xhr Status:500 URL:/ajax_request
and the 'var_dump' in the controller dosen't display anything
Your mistake is on the route.
path(): Generates a relative URL path given a route name and parameters.
url() : Generates an absolute URL given a route name and parameters.
in this line use
url: "{{ url('ajax_route') }}",
Instead
url: "{{ path('ajax_route') }}",
and your controller
use Symfony\Component\HttpFoundation\JsonResponse;
*
*
public function ajaxAction(Request $request)
$arrayAjax = array("position" => "fasle");
{
if (($request->getMethod() == Request::METHOD_POST) && ($request->isXmlHttpRequest())) {
$personnage = $request->request->get('personnage');
dump($request->request);
$wishlist = new wishlist();
$wishlist->setUserid($personnage);
$wishlist->setOfferid(1);
$em=$this->getDoctrine()->getManager();
$em->persist($wishlist);
$em->flush();
$arrayAjax = array("position" => "true");
}
return new JsonResponse($arrayAjax2);
}
I have trouble storing a JSON file in my DynamoDB table with the help of my Lambda function and my API Gateway on AWS. I have the following piece of code which gets executed once I press a button on my HTML site:
$('#submit').on('click', function(){
var example = {"number":"121212"};
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify(example),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
When pressed the website reloads, hence I assume function has successfully executed. However my problem is that the data does not arrive in the correct format in the lambda function and hence does not execute properly. When checking in CloudWatch it is shown as { number: '121212' } instead of {"number":"121212"}. Any idea how I can make sure that the value 'arrives' has a valid JSON format in my Lambda function?
Here's my Lambda function:
exports.handler = function index(e, ctx, callback) {
var params = {
Item: { number: e.number },
TableName: 'collectionOfNumbers'
};
docCLient.put(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
If I'm reading this right, e.number is the value of the JSON parameter 'number' that you are passing in, e.g. '121212'. I'm making the assumption from the usage that docClient is putItem under the hood.
I think your Item param should look like:
Item: {"number": {N: e.number}}
See AWS Docs for info regarding PutItem https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html
Developing with laravel 5.4.
In the web file I have this route:
Route::get('cart/calcShipping/{shipping_method}', 'CartController#calcShipping');
I have a view with ajax call like this:
$.ajax({
type: "GET",
headers: { 'X-XSRF-TOKEN' : $_token },
url: '{{ url("cart/calcShipping") }}' + '/1',
success: function(data) {
$('#shippingCost').val(data);
$('#shippingCostText').text(data);
}
});
In my controller I have this function (I do some calculations that I did not include in the example. For testing I'm sending back hard coded values):
public function calcShipping($shipping_method)
{
return response()->json(['shipping_cost' => 100, 'order_total' => 200]);
}
The problem is I get [object Object] back on these lines, instead of the values:
$('#shippingCost').val(data);
$('#shippingCostText').text(data);
What am I doing wrong?
Thanks
My mistake, duh, I have this call in two places, and in one of them I was only calling data.... pffff....
Basically I'm trying to pass the value of my dropbox to a get action.
The submit-button re-directs to the correct action , but what is the correct way to add the value of the dropbox with the re-direction?
My view:
#model TrackerModel
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Get, new { ???}))
{
<div>
<strong>#Html.LabelFor(m => m.CustomerName)</strong>
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #class = "customer-picker" })
</div>
<button class="styledbutton" onclick="window.location.href='/Tracker/Index'">Cancel</button>
<button type="submit" value="submit" id="selectCustomer-button" class="styledbutton">Submit</button>
}
[HttpGet]
public ActionResult MyAction(IPrincipal user, Tracker model)
Customer-picker
$(document).ready(function () {
CustomerPicker();
});
function CustomerPicker() {
$('.customer-picker').select2({
placeholder: 'Select customer',
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: '/JsonData/GetCustomers',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
query: term // search term
};
},
results: function (data) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data };
}
},
formatResult: function (data) {
return data;
},
formatSelection: function (data) {
return data;
}
});
}
I was expecting the value to be within my Tracker model parameter in the action, but this returns nulls. Also I'm not sure what to place in the "new" parameter in the form tag?
I also tried the following but all I get returning to the controller is text:"".
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #id = "selectedCustomer", #class = "customer-picker" })
<script type="text/javascript">
$(function () {
$("#Form1").submit(function (e) {
alert("boo");
e.preventDefault();
var selectCustValue = $("#selectedCustomer").val();
$.ajax({
url: '/CalibrationViewer/SentMultipleCalsToCustomer',
data: { text: selectCustValue }
});
});
});
OK got it,
var selectCustValue = $("#s2id_CustomerName span").text();
Found another piece of code the used the customer-picker and the javascript associated with view used the above.
I viewed the page source and it still show's both id and name as CustomerName, it has something to do with the "Select 2" helper.
I may get slated for marking this as the answer, considering I should have figured it out earlier, but there you have it !
I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});