Loading data in twig from controller using AJAX in symfony 3.4 - json

i am trying to load data in twig from controller using AJAX ,
this is my controller action:
public function ajaxAction(Request $request) {
$students = $this->getDoctrine()
->getRepository('techeventBundle:event')
->findAll();
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
echo "request successfull";
$jsonData = array();
$idx = 0;
foreach($students as $student) {
$temp = array(
'name' => $student->getTitre(),
'address' => $student->getDescription(),
);
$jsonData[$idx++] = $temp;
}
return new JsonResponse($jsonData);
} else {
return $this->render('#reservation/Default/ajax.html.twig');
}
}
this is my twig file :
<!-- test Ajax --->
<button id="loadstudent">load events</button>
<div id="student">
<div id="name"></div>
<div id="address"></div>
</div>
<!-- test Ajax --->
<script language = "javascript"
src = "https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script language = "javascript">
$(document).ready(function(){
$("#loadstudent").on("click", function(event){
$.ajax({
url: '/student/ajax',
type: 'POST',
dataType: 'json',
async: true,
success: function(data, status) {
var e = $('<tr><th>Name</th><th>Address</th></tr>');
$('#student').html('');
$('#student').append(e);
for(i = 0; i < data.length; i++) {
student = data[i];
var e = $('<tr><td id = "name"></td><td id = "address"></td></tr>');
$('#name', e).html(student['name']);
$('#address', e).html(student['address']);
$('#student').append(e);
alert('Ajax request success');
}
},
error : function(xhr, textStatus, errorThrown) {
alert('Ajax request failed.');
}
});
});
});
</script>
let me describe to you the problem , when i click on the button ("#loadstudent") it shows up the 'Ajax request failed ' alert , added to that if you have seen in my action code i have added echo "request successfull"; after that :
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
it's not displaying that , which means that it's not getting into the condition ! help please i am stuck in this problem since one week ,

Add a route name in the controller #Route("/student/ajax", name="get-students")
Example:
/**
* #Route("/student/ajax", name="get-students")
*/
public function ajaxAction(Request $request) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$jsonData = array(
array(
'name' => 'name1',
'address' => 'addres1',
),
array(
'name' => 'name2',
'address' => 'addres2',
),
);
return new JsonResponse($jsonData);
} else {
return $this->render('#reservation/Default/ajax.html.twig');
}
}
Now, in $.ajax send the request to route name url: "{{ path('get-students') }}"
<script language = "javascript">
$(document).ready(function () {
$("#loadstudent").on("click", function (event) {
$.ajax({
url: "{{ path('get-students') }}",
type: 'POST',
dataType: 'json',
async: true,
success: function (data, status) {
var e = $('<tr><th>Name</th><th>Address</th></tr>');
$('#student').html('');
$('#student').append(e);
for (i = 0; i < data.length; i++) {
student = data[i];
var e = $('<tr><td id = "name"></td><td id = "address"></td></tr>');
$('#name', e).html(student['name']);
$('#address', e).html(student['address']);
$('#student').append(e);
alert('Ajax request success');
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr, textStatus, errorThrown);
alert('Ajax request failed.');
}
});
});
});
</script>
Twig file output:
Name Address
name1 addres1
name2 addres2

Related

I am getting error sending status code in laravel apide

When sending response code in laravel api, validation does not enter.
I can view it from the network, but when I send the status code, the console prints an error and I cannot print the validations on the blade page. If I don't send status code I can print validations.
Following my code: StudentController
public function store(Request $request): object
{
$validate = Validator::make($request->all(),[
'name' => 'required',
'course' => 'required',
]);
$data = [
'name' => $request->name,
'course' => $request->course,
];
if ($validate->fails()){
return response()->json(['success' => false, 'errors' => $validate->messages()->all()],422);
}
Student::insert($data);
return response()->json(['success' => true, 'message' => "Registration Successful"]);
}
ajax
$(document).ready(function (){
$('#createBtn').on('click',function (e) {
e.preventDefault();
let form = $('#student-add').serialize();
$.ajax({
'url': "{{ route('students.store') }}",
'data': form,
'type': "POST",
success:function (result) {
$('#ajax-validate ul').text("");
if(result.success === true){
console.log("True");
}else {
result.errors.forEach(function (item) {
$('#ajax-validate ul').append('<li>'+item+'</li>');
});
}
}
});
});
});
console
network
You have your response.errors.forEach inside of your success: function(), but 422 (or any 400) code doesn't get handled by the success function, but rather the error function:
$(document).ready(function () {
$('#createBtn').on('click', function (e) {
e.preventDefault();
let form = $('#student-add').serialize();
$.ajax({
url: "{{ route('students.store') }}",
data: form,
type: 'POST',
success: function (result) {
if (result.success === true) {
// Do whatever on `2XX` HTTP Codes
}
},
error: function (response) {
if (response.status === 422) {
let responseJson = response.responseJSON ? response.responseJSON : { errors: [] };
$('#ajax-validate ul').text('');
responseJson.errors.forEach(function (item) {
$('#ajax-validate ul').append('<li>'+item+'</li>');
});
} else {
console.log('Unhandled Error:', response)
}
}
});
});
});
Now when an 422 error is explicitly triggered, you code can properly handle the validation errors.

How to fetch particular data in column from JSON with keys

I am not sure how to fetch particular data in column from JSON with the help of keys. From ajax request i am getting data from the server but i want to store it in sqlite as the columns in server
$("#xxx").click(function()
{
var e = $("#mob").val();
var p = $("#key").val();
myDB.transaction(function(transaction)
{
transaction.executeSql('CREATE TABLE IF NOT EXISTS User_data (data)', [],
function(tx, result)
{
navigator.notification.alert("table created");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
$.ajax
({
url: "http://192.168.1.4/sms/android.php",
type: "GET",
datatype: "json",
data: { type:'login', phone: e, name: p },
ContentType: "application/json",
success: function(response)
{
var valuesInArray = JSON.stringify(response);
var user_data = JSON.parse(valuesInArray);
for(var item in user_data.Users)
{
myDB.transaction(function(transaction)
{
transaction.executeSql('INSERT INTO User_data (id,date_closed) VALUES (item.id,item.date_closed)', [],
function(tx, result)
{
navigator.notification.alert("data inserted");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
}
},
error: function(e)
{
alert('Got ERROR: ' + JSON.stringify(e));
}
});
});
here is the image of the data i am getting from the server
DATA IN ALERT BOX
here, i want to fetch each column in the database.
Thankx in advance.
<?php
header('Access-Control-Allow-Origin:*');
pg_connect("host=localhost port=5432 dbname=** user=** password=***");
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$mobile = $_GET['phone'];
$key = $_GET['name'];
$query = "select * from crm_lead where phone='$mobile' and id='$key'";
$result = pg_query($query);
while($myrow = pg_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('Users' => $recipes));
echo "'".$output."';";
}
}
else
{
echo "invalid";
}
pg_close();
?>
Why can't you use the response object directly since it's already a Json object?
var users = response.Users;
for(var i=0; i < users.length;i++)
{
var id = users[i].id;
//do something with id
}
$.ajax
({
url: "http://182.70.240.81:82/sms/android.php",
type: "GET",
datatype: "json",
data: { type: 'login', phone: 9770869868, name: 14 },
ContentType: "application/json",
success: function (response) {
var simpleJson = JSON.parse(response);
var shortName = 'db_test';
var version = '1.0';
var displayName = 'Test Information';
var maxSize = 65536; // in bytes
var db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(function (txe) {
txe.executeSql('DROP TABLE User_data');
txe.executeSql('CREATE TABLE User_data(id INTEGER,date_closed TEXT)');
db.transaction(function (txe1) {
for (var i = 0; i < simpleJson.Users.length; i++) {
txe1.executeSql('INSERT INTO User_data (id,date_closed) VALUES (' + simpleJson.Users[i].id + ',"' + simpleJson.Users[i].date_closed + '")', [],
function (tx, result) {
alert("data inserted");
},
function (error) {
alert("error, table exists");
});
}
});
});
}
});
Remove Single Qoutaion from your json:

Redirect to diffrent action when reciving json results in my script

i'm getting a list view json results and I would like to redirect to a different view and display the results according to my json
( I hope i'm clear) this what i'm did
<script type="text/javascript">
$(document).ready(function () {
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "Home/GetSubjectsName",
data: "{'term': '" + request.term + "' }",
dataType: 'json',
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
}
var url = '#Url.Action("bla", "blaaaa")';
}))
}
});
},
minLength: 2,
});
});
my jsonlook like this :
public JsonResult GetSubjectsName(string term)
{
var results = db.subjects.Where(s => term == null ||
s.SubjectName.ToLower().Contains(term.ToLower())).Select(x => new
{ id = x.SubjectId, value = x.SubjectName }).Distinct().ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
and the action I would like to display the results is this (instead of partial view)
public ActionResult bla(string term)
{
IEnumerable serach = from sub in db.subjects.Where(t => t.SubjectName.Contains(term)).Distinct()
select new SearchResultsViewModel
{
Created = sub.Created,
Gender = sub.Gender,
OccupationDecription = sub.OccupationDecription,
Image = sub.Image,
SubjectName = sub.SubjectName
};
ViewBag.term = term;
return RedirectToAction("bla", "home", serach.ToList());
}
my View :
#model IEnumerable<MyProJect.ViewModels.SearchResultsViewModel>
foreach ....
what I need is to go to a different action and display the data
Here's some code that might help. Your post is still a bit unclear, so I'm filling in the missing pieces according to what you have described. I've made no attempt at designing the form layout.
Home/Index.cshtml:
#using( Html.BeginForm("bla") ) {
#Html.LabelFor(model => model.term)
#Html.EditorFor(model => model.term)
<button type="submit">Submit</button>
}
<script type="text/javascript">
jQuery(function ($) {
$("#term").autocomplete({ source: '#Url.Action("GetSubjectsName")', autoFocus: true, minLength: 2 });
});
</script>
Your autocomplete should be changed to:
public JsonResult GetSubjectsName(string term)
{
return Json(db.subjects
.Where(s => term == null ||
s.SubjectName.ToLower()
.Contains(term.ToLower()))
.OrderBy(x => x.SubjectName)
.Select(x => x.SubjectName)
.Distinct(), JsonRequestBehavior.AllowGet);
}
As far as I can tell, everything else should work as intended.

How to display form errors after ajax query and JsonResponse

I have a form to add product using jquery and ajax. Adding proucts work fine but I'd like to know how to display form errors with JsonRespone
This is the jquery code
$(document).on('submit', "#form-add", function (e) {
e.preventDefault();
$.ajax({
type: 'post',
dataType: 'json',
data: $(this).serialize(),
url: Routing.generate('admin_add_product'),
success: function (msg) {
},
error: function(msg){
// do something to display errors
}
});
return false;
});
and this is the action
public function addAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
if ($request->isXmlHttpRequest()) {
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($product);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Your product has been added to your cart.');
$response = new JsonResponse();
return $response;
} else {
// return errors
}
}
}
}

JSON to HTML (Codeigniter)

public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
foreach($result as $r){
echo json_encode($r);
}
}
}
$(document).ready(function(){
$('#getMem').keyup(function(e){
var name = {
ajax: 1,
name: $('#getMem').val()
}
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data){
$('#freshMem').html(data.first_name);
},
error: function(){
alert('Error.');
}
});
});
});
This works fine if the result from database returns only one row, if more than one generates error, can anyone please tell me how to solve this
Use the Output class to tell the browser that JSON is being returned. The problem is that you are json_encodeing multiple objects in your foreach loop. Just json_encode the array returned from your model
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
$this->output
->set_content_type('application/json')
->set_output(json_encode(array("response" => $result)));
}
}
$(document).ready(function(){
$('#getMem').keyup(function(e){
var name = {
ajax: 1,
name: $('#getMem').val()
}
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data)
{
var __html = '';
$.each(data.response, function (a, b)
{
__html += '<p>'+b.first_name+'</p>';
});
$('#freshMem').html(__html);
},
error: function()
{
alert('Error.');
}
});
});
});
Try this:
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data){
json_data = $.parseJSON(data);
$.each(json_data, function(i,item){
$('#freshMem').append(item.first_name);
});
},
error: function(){
alert('Error.');
}
});
You have to iterate over returned array.
Also you need to change your controller code:
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
// assuming that $result is array...
$json = json_encode($result);
echo $json;
/*foreach($result as $r){
echo json_encode($r);
}*/
}
}