getJSON not working correctly with codeigniter - php

I am trying to implement AJAX call method into my website using codeigniter, the reason why i want to use AJAX so i can get live updates from the database
The click button works and displays all of the JSON data but the issue is when i try and display a specific array it does not recognize it, it seems to be iterating through every single character.
Also another wierd thing is when the alert is being called i can see the html and head tags I want to be able to print specific arrays for example the array id"
Things i have done to try and work it out
i have alerted the datatype and found out it was a string
i have managed to get ajax to work in regular PHP rather then codeigniter so their is nothing wrong with the database
I have also tried to use jQuery.parseJSON so i can force it to be json but then the script did not run
I used JSONlint and apprently its a valid JSON
Any help would be appreciated
Consolelog
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAXpGbk1wkkaPiv_qkBevxAP9s4kk0oiiU&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
[
[
{
"id": "1",
"postcode": "NW6",
"imgurl": "hello.jpeg",
"from_user": "henny",
"created_at": "2013-03-18 23:03:00"
},
{
"id": "2",
"postcode": "NW2",
"imgurl": "test.jpeg",
"from_user": "belly",
"created_at": "2013-03-15 23:03:00"
}
]
]
Controller
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arrays = array($queryresults);
echo json_encode($arrays);
}
View
<script type='text/javascript' language='javascript'>
$('#getdata').click(function (data) {
$.ajax({
url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
type: 'POST',
cache: 'false',
datatype: 'json'
}).done(function (data) {
alert(data);
});
});
</script>
json_encode
[
[
{
"id": "1",
"postcode": "NW6",
"imgurl": "hello.jpeg",
"from_user": "henny",
"created_at": "2013-03-18 23:03:00"
},
{
"id": "2",
"postcode": "NW2",
"imgurl": "test.jpeg",
"from_user": "belly",
"created_at": "2013-03-15 23:03:00"
}
]
]

You need to send the correct response headers back (application/json) from your controller function.
Try changing your controller to the following:
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arrays = array($queryresults);
$this->output->set_content_type('application/json')
->set_output(json_encode($arrays));
}

Related

POST Nested Json to API With Jquery Ajax & Get Response With PHP

I want to Post a Json string or PHP array to a Restful API and get the response without reloading the page. So, I want to use Ajax and/or jquery. So far, I'm failing miserably. my code is below.
I've tried several jquery methods - some using stringify and others just sending raw json. I'm not getting enough response or error of any kind to know where I need to look to solve the problem.
$(".avm_zip").on("click", function() {
$.ajax({
url: "REMOVED",
type: "POST",
data: {
"Header": {
"UserId": "REMOVED",
"Password": "REMOVED",
"SourceApplication": "Dev Service Tester"
},
"Property": {
"StreetAddress": "10345 W Briar Oaks Dr # E",
"City": "Stanton",
"State": "CA",
"Zip": "90680",
"APN": null,
"PropertyType": null
},
"Order": {
"CustomerOrderReference": "Test LITE",
"PreferenceTableName": "VeroLITE TEST",
"Price": null,
"Credit": null,
"AdditionalFields": null
}
},
dataType:'json',
success: function (response) {
alert("Success");
},
error: function(error){
alert("Something went wrong");
},
});
The API is more robust and centered on XML. Getting the basic call & retrieval set up using Json had challenges because of this. So, it is possible that is bleeding over into this effort.

How to pass and get data from Ajax to PHP using Data-tables

I'm trying to use Data-tables but I need to pass a value from Ajax to PHP file.
the Ajax part is like this:
<script>
$(document).ready(function() {
var oTable =
$('#user-list').DataTable({
"serverSide": true,
"ajax": {
"url": "assets/server_processing_reminders.php",
"data": {
"CurrentFlag": 1
}
},
"columnDefs": [{
"width": "6%",
"targets": 0
}],
"order": [
[1, "asc"]
]
});
});
</script>
on the server side Im trying to get the variable "CurrentFlag" using:
<?php
if (isset($_GET["CurrentFlag"])){
$cf = $_GET["CurrentFlag"];
}
echo $cf;
but the php file is not printing out the value send.
Thanks for any help
Please use $_REQUEST instead of $_GET like this :
if(isset($_REQUEST["CurrentFlag"]))
{
$cf = $_REQUEST["CurrentFlag"];
}
echo $cf;
OR
If you want print data using $_GET method please add type:GET under ajax call
You need to provide request type as GET as shown here.
"ajax" : {
"url": "assets/server_processing_reminders.php",
type: "GET",
"data": {
"CurrentFlag": 1
}
}
Use Jquery for better code and results.
Learn Ajax using this link :
https://www.w3schools.com/js/js_ajax_intro.asp

am chart pie chart not reading json file data?

when we pass static list of data like [{category":"a","data:"3"},"category":"b","data":"1"}]
then its working fine, but when we pass page url like {"url": "abc.php","format": "json"} in dataprovider section then chart not populate.
This is my code:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider":{ "
url": "abc.php",
"format": "json" },
"labelRadius": -35,
"labelText": "[[percents]]%",
"titleField": "category",
"valueField": "column-1",
"allLabels": [],
"balloon": {},
"legend": {
"enabled": true,
"align": "center",
"markerType": "circle" }
});
Any solution?
Using amCharts with "static" data
If you have "static" data, use the dataProvider setting, like this:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider": [{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}],
// ...
});
Using amCharts with AJAX data
If you want the data to be loaded using AJAX, one way is to make use of amCharts' Data Loader plugin.
Make sure to include it in your HTML:
<script src="amcharts/plugins/dataloader/dataloader.min.js" type="text/javascript"></script>
Leave out the dataProvider setting, and use dataLoader instead.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"dataLoader": {
"url": "abc.php",
"format": "json"
},
// ...
});
Your abc.php file should return valid JSON, like this:
[{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}]
You can find a complete list of options for the Data Loader plugin here: https://www.amcharts.com/kbase/using-data-loader-plugin/.

Datatable - JSON not being shown of size larger than 4KB

I am using data table to display data returned by a SQL Server 2008 procedure called in Codeigniter via Ajax($POST). Initially I made a very simple procedure with no input parameters, it only returns a list of JSON objects.
Below are my questions and my Codeigniter function returning JSON, AJAX function and JSON structure returned by my Codeigniter function:
1) JSON not returned for chunk larger than 4KB, it simply converts to HTML:
2) What if one of my procedure returns lets say 5000+ record and i want to display it in data table, is my way of doing it right? Or i should use some other best practices:
Codeigniter Function:
public function executeProc()
{
$sqlsrvr = $this->load->database('test', true);
// Get the input values of the procedure
$arr = array();
parse_str($_POST['str'],$arr);
//get Procedure Name
$procName = $_POST['procName'];
$sp ='exec secondProc';
$query = $sqlsrvr->query($sp);//->result();
$jawad = $query->result_array();
$this->output->set_header('Content-type: application/json');
echo json_encode($jawad);
}
AJAX Function
$(document).on('click','#executeProc',function(e){
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
e.preventDefault();
var jawad = $( ".jawad" ).serialize();
$.post('<?=base_url();?>command/executeProc',
{str:jawad,procName:$('#procName').val()},
function(html){
//loading data table on return
$('#example').dataTable( {
"data": html,
"columns": [
{ "data": "AppointmentID" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "AppointmentDate" }
]
} );
});
});
JSON Sample:
[
{
"AppointmentID": "1",
"FirstName": "Test",
"LastName": "test",
"AppointmentDate": "2013-01-12"
},
{
"AppointmentID": "2",
"FirstName": "dfg",
"LastName": "dfg",
"AppointmentDate": "2013-01-01"
}
]
-----AFTER EDIT------
STRANGE BEHAVIOR(JSON tab converts to HTML for larger records)
FOR 40 records that get displayed on data table
FOR records larger then 40 that don't get displayed on data table

Returned JSON is seemingly mixed up when using jQuery Ajax

I've a php script that has the following line:
echo json_encode(array('success'=>'true','userid'=>$userid, 'data' => $array));
It returns the following:
{
"success": "true",
"userid": "1",
"data": [
{
"id": "1",
"name": "Trigger",
"image": "",
"subtitle": "",
"description": "",
"range1": null,
"range2": null,
"range3": null
},
{
"id": "2",
"name": "DWS",
"image": "",
"subtitle": "",
"description": "",
"range1": null,
"range2": null,
"range3": null
}
]
}
But when I call a jQuery ajax as below:
$.ajax({
type: 'POST',
url: 'url',
crossDomain: true,
data: {name: name},
success: function(success, userid, data) {
if (success = true) {
document.write(userid);
document.write(success);
}
}
});
The userid is 'success'. The actual success one works, its true.
Is this malformed data being returned? Or is it simply my code?
Thanks in advance,
Niall
The arguments the success callback takes are defined in the documentation:
success(data, textStatus, jqXHR)
The response is not split up before being passed as arguments to it. You have to extract the values from the first argument.
You also need to add header('Content-Type: application/json') to your PHP so that jQuery will parse the response as JSON instead of as HTML when populating the first argument.
You can then test data.success and access data.userid (as well as data.data which will be the array assigned to the data property in the returned data… you might want to rename it to avoid confusion).
Note that when you test it you need to use === (or ==), not the * assignment* operator you are using at present. Also note that your JSON response is returning the string "true" and not the boolean true.
You can't add your own arguments in Success. Change your code like this,
success: function(response) {
if (response.success == true) {
document.write(response.userid);
document.write(response.success);
}
}
According to jQuery Docs for success(),
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn.
http://api.jquery.com/jQuery.ajax/

Categories