send data from twig to controller using ajax in symfony 3.4 - json

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

Related

Ajax request in Symfony 3.4

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

Problem with php handling ajax in the same file

I have a serious problem, I can't receive data sent by ajax in php. I've read many tutorial about that but it still not resolved. So if you guys have the magic solution, it'll make my day.
Here is the code, note that it is in the same file problem.php.
assocStored is an array or object, and it have the right data if I check it on jvascript
window.onload = function(e){
var assocStored = JSON.parse(localStorage.getItem("associes"));
$.ajax({
type : "POST",
data : {"problem" : assocStored},
success : function(res){
console.log("action performed successfully");
}
})
}
<div>
<h3>php</h3>
<?php
var_dump ($_POST);
if( isset($_POST['problem']) ){
foreach ($_POST['problem'] as $associe) {
echo($associe["sex"]." ".$associe["firstname"]." ".$associe["lastname"]);
}
exit;
}
?>
</div>
As my comment above, I guess your request send a GET method.
In your code, you are using type is POST but type is an alias for method. You should use type if you are using versions of jQuery prior to 1.9.0.
So you can modify your ajax to here:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
success : function(res){
console.log("action performed successfully");
}
})
If it continues not working, add this code to ajax:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
beforeSend: function(req) {
if (req && req.overrideMimeType) {
req.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success : function(res){
console.log("action performed successfully");
}
})
I hope it works.

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

Pass a value from controller as JSON in codeigniter to view that contain on Angular Js

I need to use this:
http://demos.telerik.com/kendo-ui/multiselect/angular
but my problem when I try to change the url to:
read: {
url: base_url+"index.php/welcome/findAll",
}
and the function findAll in controller contain on:
public function findAll()
{
$listproduct = $this->mproduct->findAll();
echo json_encode($listproduct);
}
The list of options become empty.
You controller seems to be fine as long as it returns a valid JSON format.. in your AngularJS controller try doing:
$scope.MyFunction = function()
{
console.log("posting data....");
$http({
method : 'GET',
url : 'http://domain/controller/method_that_return_json',
headers: {'Content-Type': 'application/json'},
data : JSON.stringify({What you want to return from JSON here})
}).success(function(data) {
console.log(data);
});
}
Another aproach:
$http.get("http://www.domain.com/pathtojson)
.success(function(response) {
$scope.related = response;
});
}