Ajax request in Symfony 3.4 - json

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

Related

How can i show recived multiple json data in a laravel blade file

(Route File)
Route::post('/report/collectorSearch','reportController#collectorSearch');
(blade file)
ajax code
$('#collector_name').change(function(event) {
/* Act on the event */
var collector_id = $(this).val();
$.ajax({
url: '{{URL::to("/report/collectorSearch")}}',
type: 'POST',
data: {
collector_id:collector_id,
_token: $('#Productsignup_token').val()
},
dataType:'json',
success:function(CollectorResponse){
console.log(CollectorResponse);
}
})
});
controller
public function collectorSearch(Request $request){
$getCollector_id = $request->collector_id;
if ($getCollector_id) {
$searchs = sellproduct::where('collector_id',$getCollector_id)->get();
return response()->json($searchs);
}
}

send data from twig to controller using ajax in symfony 3.4

i want to send data from a view (Twig) to controller without refreshing the page so i used ajax , in order to pass data to a specific controller action .
this is my ajax code in the twig file :
<script>
var data = {request : $('#content').val()};
$.ajax({
type: "POST",
url: "{{ path('AjoutAjax') }}",
data: data,
success: function (data, dataType) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error : ' + errorThrown);
}
});
</script>
this is my twig file :
<div class="column text-lg">Subtotal: <span class="text-medium" id="content">
this is my controller action :
public function AjoutAjaxAction(Request $request)
{
$data = $request->request->get('request');
echo $data;
$em = $this->getDoctrine()->getManager();
$reservation = $em->getRepository('techeventBundle:Panier')->find(11);
$reservation->setTotal($data);
$em->flush();
return $this->render('#reservation/Default/afficherPanier.html.twig');
}
and this is the routing file
affichage:
path: /afficherPanier/{iduser}
defaults: { _controller: reservationBundle:Default:afficherPanier }
AjoutAjax:
path: /ajoutAjax
defaults: { _controller: reservationBundle:Default:AjoutAjax }
the problem is :
1/ it's not sending data to the controller action because when i tried with the path 'AjoutAjax' it's not showing the echo '$data' .
2/with any path should i test with 'affichage' or 'AjoutAjax' to know that is working ?
'
I'm no front-end dev but but i think you should use .html() or .text() instead of .val() on a span element
https://api.jquery.com/text/#text

Calling a REST web service spring controller from a html page, and passing the form elements alone with the call using ajax

I have a controller that creates a new user for my application (users are stored using MongoDB). I ran the code with #Path and #RequestBody annotations successfully using postman tool.
Now I have to include a UI which is mapped to my controller. I tried passing the values using ajax, and the values are getting passed(upon inspection from my browser). But the controller is not being called.
Then I tried with #RequestMapping and #RequestBody annotations but then I am getting the following warning while accessing it through Postman
WARNING: No root resource matching request path /Task1_2/Create/createUser has been found, Relative Path: /Create/createUser.
Finally, I tried with all three annotations #Path,#RequestMapping and #RequestBody then I am getting a response in Postman.
All the above were done by directly calling the controller from Postman through the URI.
But still, now I am not able to get any response on my browser while calling the HTML page which is mapped to my controller.
This is my controller
#RestController
#Path("/Create/")
#RequestMapping("/Create/")
public class CreateUser {
#POST
#Path("createUser")
#RequestMapping(value="createUser",method=RequestMethod.POST,consumes="application/json")
public Response Create(#RequestBody String request)
{
.....
BasicDBObject obj = (BasicDBObject) JSON.parse(request);
.....
output = "#Produces(\"application/json\")"+"User Created Successfully";
return Response.status(200).entity(output).build();
}
And this is my ajax function
function fun()
{
var search = { UserName: $( "input[name='UserName']" ).val(),
FirstName: $( "input[name='FirstName']" ).val(),
LastName: $( "input[name='LastName']" ).val(),
Mobile: $( "input[name='Mobile']" ).val(),
EmailId: $( "input[name='Email']" ).val()
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/Create/createUser",
data: JSON.stringify(search), // Note it is important
success :function(output) {
alert(output);
},
error: function(e){
alert('failure');
}
});
}
I have kept the HTML file(CreateUser.html) with the above script inside the WebContent folder of my project.
So
1. What am I doing wrong?
2. Should I be using #Path alone with #RequestMapping
I think it is related to your JSON format which your are sending from Ajax.
This would run
function fun()
{
var search = { UserName: $( "input[name='UserName']" ).val(),
FirstName: $( "input[name='FirstName']" ).val(),
LastName: $( "input[name='LastName']" ).val(),
Mobile: $( "input[name='Mobile']" ).val(),
EmailId: $( "input[name='Email']" ).val()
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/Create/createUser",
data: JSON.stringify({search : search }), // Note it is important
success :function(output) {
alert(output);
},
error: function(e){
alert('failure');
}
});
}

Formatting entity in json format does'nt show in view

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

Alfresco webscript: AJAX, JSON

I've successfully created a webscript to that returns a JSON response. See below:
get.js file:
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath("PATH");
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + " not found.";
status.redirect = true;
}
// construct model for response template to render
model.folder = folder;
get.json.ftl:
{"corporates" : [
<#recurse_macro node=folder depth=0/>
]
}
<#macro recurse_macro node depth>
<#list node.children?sort_by(["properties","name"]) as child>
{
"Name" : "${child.properties.name}",
"URL" : "${child.url}",
"serviceURL" : "${child.serviceUrl}",
"shareURL" : "${child.shareUrl}",
"ID" : "${child.id}",
"Type" : "${child.typeShort}"
},
<#if child.isContainer>
{
<#recurse_macro node=child depth=depth+1/>
}
</#if>
</#list>
</#macro>
This returns JSON cleanly (woohoo!), but I would like to grab the JSON from a second webscript using AJAX.
Currently, I am utilizing a typical AJAX call in my second webscript's get.html.ftl file like this:
$(document).ready(function() {
$('.submit-button').click(function(e) {
// Avoid to trigger the default action of the event.
e.preventDefault();
// Actions declared here...
$.ajax({
type: 'GET',
dataType: 'html',
url: 'PLACEHOLDER_URL_PATH',
success: function(data) {
// Shows the result into the result panel.
$('#alfresco-result').html(data);
alert('Done.');
},
error: function(data) {
// Shows the result into the result panel.
$('#alfresco-result').html("ERROR");
}
});
});
})
My question is why the AJAX call doesn't work when I use dataType: 'json'?
I would like to parse through the JSON in my AJAX call and turn it into html (e.g. an html list), but it's not accepting the JSON dataType as an acceptable input.
Any help is appreciated!
You can use POST Webscript Call using ajax like this and pass your jsonObject
dataObj:"yourJsonObject",
to dataObject
Alfresco.util.Ajax.jsonPost(
{
url: Alfresco.constants.PROXY_URI + "sample/mypostwebscript",
dataObj:"yourJsonObject",
successCallback: {
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
// Display error message and reload
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
},