JSON to HTML (Codeigniter) - html

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

Related

Loading data in twig from controller using AJAX in symfony 3.4

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

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:

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

Passing Json from Controller to View

I have a database of movies, and I am looking to create a Json, and then access that json in my view. I have successfully created the json within the controller using the following code:
var movies = from m in db.Movies
select m;
string jsonData = JsonConvert.SerializeObject(movies);
This creates a json, which I have passed to the Console via writeline, and it generates the following JSON:
[{"ID":1,"Title":"When Harry Met Sally","ReleaseDate":"1989-01-11T00:00:00","Genre":"Romantic Comedy","Price":7.99,"Rating":"PG","Review":79.90},
{"ID":2,"Title":"Ghostbusters ","ReleaseDate":"1984-03-13T00:00:00","Genre":"Comedy","Price":8.99,"Rating":"PG","Review":94.90},
{"ID":3,"Title":"Ghostbusters 2","ReleaseDate":"1986-02-23T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"15","Review":89.90},
{"ID":4,"Title":"Rio Bravo","ReleaseDate":"1959-04-15T00:00:00","Genre":"Western","Price":3.99,"Rating":"U","Review":91.90},
{"ID":5,"Title":"The Hangover","ReleaseDate":"2008-01-01T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"18","Review":83.80},
{"ID":6,"Title":"Test","ReleaseDate":"2013-06-01T00:00:00","Genre":"Action","Price":10.00,"Rating":"18","Review":89.00}]
I then want to access that json in my view, and print it to my view. I have tried the following Ajax code, but I can't seem to get the json data to display.
<button id="test">Test</button>
<div class="inner"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" + jsonData + "</p>");
});
});
});
});
</script>
Any ideas? What am I doing wrong?
if we are talking about ASP.NET MVC then you can do this:
action code:
[HttpGet]
public JsonResult Index(int? PageId)
{
//other your code goes here
var movies = from m in db.Movies
select m;
return Json(new {result = movies}),JsonRequestBehavior.AllowGet);
}
client code:
$.ajax({
type: "GET",
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
content: "application/json",
cache : false
}).done(function (serverdata) {
if(result.result.length > 0)
{
$.each(result.result, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
}
else
{
alert("No movies in result");
}
}).fail(function (jqXHR, textStatus) {
alert("Internal server error." + "\n" + jqXHR.statusText );
});
try: -
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
method: 'GET',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
var jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
});
});
});
</script>

Json responseText empty and statusText as error

From mvc 4 action:
[HttpPost]
public ActionResult DoStuff(string str)
{
// Do some things
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = someCondition == true ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return Json(
new {
object1 = 1,
object2 = someArray[0],
object3 = someArray[1],
object4 = someValue == 4 ? 1 : 0
}
);
}
In jquery ajax:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
var _response = $.parseJSON(data);
}, function (data) {
var _response = $.parseJSON(data.responseText);
});
data.responseText is empty ("") and statusText is "error". It is not always happening. I have observed that it is happening randomly. Why?
Your data is already being converted to an object from JSON, so you do not need to parse it again. Try this:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
// use data here...
alert(data.object1);
}, function () {
alert('request failed');
});