jqGrid with JSON data renders table as empty - php

I'm trying to create a jqgrid, but the table is empty. The table renders, but the data doesn't show.
The data I'm getting back from the php call is:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}
The javascript configuration looks like so:
$("#"+tableId).jqGrid ({
url:'getAwards.php?id='+classId,
dataType : 'json',
mtype:'POST',
colNames:['Id','Badge','Name','Description',''],
colModel : [
{name:'awardId', width:30, sortable:true, align:'center'},
{name:'badge', width:40, sortable:false, align:'center'},
{name:'name', width:180, sortable:true, align:'left'},
{name:'description', width:380, sortable:true, align:'left'},
{name:'selected', width:0, sortable:false, align:'center'}
],
sortname: "awardId",
sortorder: "asc",
pager: $('#'+tableId+'_pager'),
rowNum:15,
rowList:[15,30,50],
caption: 'Awards',
viewrecords:true,
imgpath: 'scripts/jqGrid/themes/green/images',
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id",
userdata: "userdata",
subgrid: {root:"rows", repeatitems: true, cell:"cell" }
},
width: 700,
height: 200
});
The HTML looks like:
<table class="awardsList" id="awardsList2" class="scroll" name="awardsList" />
<div id="awardsList2_pager" class="scroll"></div>
I'm not sure that I needed to define jsonReader, since I've tried to keep to the default. If the php code will help, I can post it too.

I got it to work!
The dataType field should be datatype. It's case sensitive.

The problem also occures when you include script jquery.jqGrid.min.js before then grid.locale-en.js. Check this if there are any problems with controller's method call.

I experienced the same problem when migrating from jqGrid 3.6 to jqGrid 3.7.2. The problem was my JSON was not properly double-quoted (as required by JSON spec). jqGrid 3.6 tolerated my invalid JSON but jqGrid 3.7 is stricter.
Refer here: http://simonwillison.net/2006/Oct/11/json/
Invalid:
{
page:"1",
total:1,
records:"10",
rows:[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}
Valid:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}

I also got it to work: datatype is the correct spelling -- it's shown that way in the example but it is inconsistent with everything else in the library so it was easy to get wrong
I'm getting very tired chasing this sparse documentation around and I really feel like JSON, which is right and proper to be using in JavaScript, has really been given short coverage in favor of XML. Python and JavaScript together, through JSON, is a really strong combination, but it's a constant struggle with this particular library.
Anyone with an alternative that:
1> Properly supports jQuery UI themes (including rounded corners!) (http://datatables.net has much nicer support for themes)
2> Allows resizing of columns (http://datatables.net doesn't support this out of the box)
3> Allows sub-grids (http://datatables.net lets you do whatever you want here, through an event)
please let me know. I'm spending more time on this one part of my interface than on the whole rest of it combined and it's all the time spent searching for working examples and "trying things" which is just getting annoying.
S

This might be a older post but I will post my success just to help others.
Your JSON needs to be in this format:
{
"rows": [
{
"id": 1,
"cell": [
1,
"lname",
"fname",
"mi",
phone,
"cell1",
"cell2",
"address",
"email"
]
},
{
"id": 2,
"cell": [
2,
"lname",
"fname",
"mi",
phone,
"cell1",
"cell2",
"address",
"email"
]
}
]
}
and I wrote this model in Zend so you can use it if you feel like it. Manipulate it how you want.
public function fetchall ($sid, $sord)
{
$select = $this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->join('Subdiv', 'Subdiv.SID = Contacts.SID', array("RepLastName" => "LastName",
"Subdivision" => "Subdivision",
"RepFirstName" => "FirstName"))
->order($sid . " ". $sord);
$resultset = $this->getDbTable()->fetchAll($select);
$i=0;
foreach ($resultset as $row) {
$entry = new Application_Model_Contacts();
$entry->setId($row->id);
$entry->setLastName($row->LastName);
$entry->setFirstName1($row->FirstName1);
$entry->setFirstName2($row->FirstName2);
$entry->setHomePhone($row->HomePhone);
$entry->setCell1($row->Cell1);
$entry->setCell2($row->Cell2);
$entry->setAddress($row->Address);
$entry->setSubdivision($row->Subdivision);
$entry->setRepName($row->RepFirstName . " " . $row->RepLastName);
$entry->setEmail1($row->Email1);
$entry->setEmail2($row->Email2);
$response['rows'][$i]['id'] = $entry->getId(); //id
$response['rows'][$i]['cell'] = array (
$entry->getId(),
$entry->getLastName(),
$entry->getFirstName1(),
$entry->getFirstName2(),
$entry->getHomePhone(),
$entry->getCell1(),
$entry->getCell2(),
$entry->getAddress(),
$entry->getSubdivision(),
$entry->getRepName(),
$entry->getEmail1(),
$entry->getEmail2()
);
$i++;
}
return $response;
}

Guys just want to help you in this. I got following worked:
JSON
var mydata1 = { "page": "1", "total": 1, "records": "4","rows": [{ "id": 1, "cell": ["1", "cell11", "values1" ] },
{ "id": 2, "cell": ["2", "cell21", "values1"] },
{ "id": 3, "cell": ["3", "cell21", "values1"] },
{ "id": 4, "cell": ["4", "cell21", "values1"] }
]};
//Mark below important line. datatype "jsonstring" worked for me instead of "json".
datatype: "jsonstring",
contentType: "application/json; charset=utf-8",
datastr: mydata1,
colNames: ['Id1', 'Name1', 'Values1'],
colModel: [
{ name: 'id1', index: 'id1', width: 55 },
{ name: 'name1', index: 'name1', width: 80, align: 'right', sorttype: 'string' },
{ name: 'values1', index: 'values1', width: 80, align: 'right', sorttype: 'string'}],
Regards,

In my case, the problem was caused by the following line of PHP code (which was taken from jqGrid demo):
$responce->page = $page;
What is wrong here is that: I am accessing property page of object $responce without creating it first. This caused Apache to display the following error message:
Strict Standards: Creating default object from empty value in /home/mariusz/public_html/rezerwacja/apps/frontend/modules/service/actions/actions.class.php on line 35
And finally the error message used to be send to json reader within the script.
I fixed the problem by creating empty object:
$responce = new stdClass();

I don't think your ID is the correct type, I think it should be an int.
For the given json you really don't need the jsonreader settings. What you have listed is the defaults anyway, plus you don't have a subgrid in your json.
Try this:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":1 ,"cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":2,"cell":["2","image","Link Badge","When you are invested as a Scout, you maybe eligible to receive a Link Badge. (See page 45)","0"]},
{"id":3,"cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":4,"cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":5,"cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":6,"cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":7,"cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":8,"cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":9,"cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":10,"cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}

I was working with WAMP 2.4, I was being crazy with this problem, I tried lot of things, like install previous versions of PHP and like 5.2, een I tried in Windows XP, and lots of jqGrid options.
Well thank to Oleg finally and Mariusz I find the only line:
$responce = new stdClass();
Before the use of $responce could solve all, and now my grid is works Great!!!
Thanks my friends.

Related

Google Books API Limit Results

Is there any way to limit the results returned by the Google Books API?
For example the following URL:
https://www.googleapis.com/books/v1/volumes?q=isbn:0751538310
Returns the following:
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "ofTsHAAACAAJ",
"etag": "K6a+5IuCMD0",
"selfLink": "https://www.googleapis.com/books/v1/volumes/ofTsHAAACAAJ",
"volumeInfo": {
"title": "Panic",
"authors": [
"Jeff Abbott"
],
"publisher": "Grand Central Publishing",
"publishedDate": "2006",
"description": "Things are going well for young film-maker Evan Casher - until he receives an urgent phonecall from his mother, summoning him home. He arrives to find her brutally murdered body on the kitchen floor and a hitman lying in wait for him. It is then he realises his whole life has been a lie. His parents are not who he thought they were, his girlfriend is not who he thought she was, his entire existence an ingeniously constructed sham. And now that he knows it, he is in terrible danger. So he is catapulted into a violent world of mercenaries, spies and terrorists. Pursued by a ruthless band of killers who will stop at nothing to keep old secrets buried, Evan's only hope for survival is to discover the truth behind his past. An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0751538310"
},
{
"type": "ISBN_13",
"identifier": "9780751538311"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 408,
"printType": "BOOK",
"categories": [
"Austin (Tex.)"
],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=ofTsHAAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=ofTsHAAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.uk/books?id=ofTsHAAACAAJ&dq=isbn:0751538310&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.uk/books?id=ofTsHAAACAAJ&dq=isbn:0751538310&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/Panic.html?hl=&id=ofTsHAAACAAJ"
},
"saleInfo": {
"country": "GB",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "GB",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://books.google.co.uk/books/reader?id=ofTsHAAACAAJ&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years."
}
}
]
Is there any way I can return only the title and description? I think it may improve performance of my web application.
I have looked at the partial response but it doesn't seem to work.
I am including my API key in the URL query parameter.
Thanks
I added the params according to the partial response documentation.
See the params in following link:
https://www.googleapis.com/books/v1/volumes?q=isbn:0751538310&fields=items(volumeInfo/description,volumeInfo/title)
It will return:
{
"items": [
{
"volumeInfo": {
"title": "Panic",
"description": "Things are going well for young film-maker Evan Casher - until he receives an urgent phonecall from his mother, summoning him home. He arrives to find her brutally murdered body on the kitchen floor and a hitman lying in wait for him. It is then he realises his whole life has been a lie. His parents are not who he thought they were, his girlfriend is not who he thought she was, his entire existence an ingeniously constructed sham. And now that he knows it, he is in terrible danger. So he is catapulted into a violent world of mercenaries, spies and terrorists. Pursued by a ruthless band of killers who will stop at nothing to keep old secrets buried, Evan's only hope for survival is to discover the truth behind his past. An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years."
}
}
]
}
maxResults
include this in your query. 5 is just an integer.
&maxResults=5
Google will help you create your API with this website API called try it.
https://developers.google.com/books/docs/v1/reference/volumes/list?apix=true#try-it
Maybe its too late to respond but you need to activate the API before accessing it. When you try to access it says to activate it from console with some project id. Just copy that url and it takes you straight to your dashboard where you can find your activation button post which you can access the partial response with desired attributes.

How to parse json array and append it to the datatables

I am unable to append the values to data tables, PHP file giving the JSON response but I am unable to append the data to the data table. I have used the following code for JSON response
GetKeyWordBids.php
array_push($ret, array("keyword"=>$keyword, "svol"=>$search_volume));
}
//print_r($ret);
echo json_encode($ret);
And Json Response:
[{
"keyword": "interventional cardiology",
"svol": 6600
},{
"keyword": "pediatric cardiology",
"svol": 5400
},{
"keyword": "cardiology jobs",
"svol": 1300
},{
"keyword": "cardiology associates",
"svol": 6600
},{
"keyword": "interventional cardiology jobs",
"svol": 880
},{
"keyword": "european society of cardiology",
"svol": 5400
},{
"keyword": "nuclear cardiology",
"svol": 1600
}],
And My Jquery Code is :
$('#specialty').change(function(){
$("#example1").dataTable().fnDestroy();
var oTable = $('#example1').dataTable({
"aaSorting": []
});
var spevalue = $("#specialty option:selected").text();
var dataString='specialty='+ spevalue;
$.ajax({
type: "POST",
url: "GetKeyWordBids.php",
data: dataString,
success: function(s){
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i]['keyword'][0],
s[i]['svol'][0]
]);
}
});
});
But I am getting the error shown below. Please let me know the changes that are required.
DataTables warning (table id = 'example1'): Requested unknown parameter '0' from the data source for row 0
The JSON parser is very strict about JSON. And then your actual recall of the data is badly formatted. So:
As per splash58's comment, make sure your dataType is JSON. In your browser's developer tools (or Firebug), look at the XHR. The tool should provide a tab for viewing the response as formatted JSON. If it doesn't, or if you saw an error on the request, it might be requested with bad headers, or returned with the wrong type.
The trailing comma might be ignored by a JavaScript interpreter in general, but the JSON parser is strict and won't like it. A quick way of double-checking your JSON formatting is to fire it into JSONLint.com to see if it validates. The one you supply above does not until you remove the comma at the end.
I assume you want the full "keyword" and "svol". The extra [0] is digging into the string and returning the first character. You're going too deep into the data! What you want is s[i]['keyword'] (or s[i].keyword) and s[i]['svol'] (or s[i].svol) per this fiddle: http://jsfiddle.net/v07tvuq8/
I'm not really sure that the combination of fnClearTable and fnAddData are what you are looking for. The DataTables API allows you to specify what each column should do at initialization time, and thereafter you should just need to call draw() on it. There shouldn't be a need for iterating over your data set.

Save the contenteditable changes in json file using php ajax

I was trying to make a page content editable using html 5 and save the data in json file for later use.
I would also like if the page loads using AJAX just the part which is edited and a php file which modifies the json file.
Any inputs on this would be really helpful.
So far I have gone through the AJAX PHP JSON from head first AJAX, and have a pretty good knowledge abut it, but what I need to know is how do that from a JSON file which has a format like this -
{
"itemGuitar": {
"id": "itemGuitar",
"description": "Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.",
"price": 5695.99,
"urls": [
"thewho",
"Pete_Townshend"
]
},
"itemShades": {
"id": "itemShades",
"description": "Yoko Ono's sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.",
"price": 258.99,
"urls": [
"beatles",
"johnlennon",
"yoko-ono"
]
},
"itemCowbell": {
"id": "itemCowbell",
"description": "Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.",
"price": 299.99,
"urls": [
"Saturday_Night_Live",
"More_cowbell"
]
},
"itemHat": {
"id": "itemHat",
"description": "Michael Jackson's hat as worn in the \"Bille Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.",
"price": 1699.99,
"urls": [
"abc",
"def"
]
}
}
I need help in getting the data which was edited using ajax, modifying it in the json using php and load the data again into the web page using ajax.
and this json is kept in a file.
Thanks in advance!!
Gaurav Nagar
The HTML so far is --
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test HTML to save content editable on the go!!</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function sendData () {
var val = document.getElementById('editMe').innerHTML;
var cuenta = new Object();
cuenta.editMe = val;
$.ajax({
type: 'post'
, url: '/processDataFilePHP.php'
, dataType: 'json'
, data: { cuenta: editMe }
});
}
</script>
</head>
<body>
<h1 id="editMe" contenteditable="true">Hurray!!!</h1>
<button id="save" type="submit" onclick="sendData()">Save</button>
</body>
</html>
I also want to know how I can swap the new test which is saved in json and is returned by php.
Ok, there are two different problems: Send Json data from PHP, and get Json data in PHP from client side.
Send Json Data From PHP
To get your json data, you should write in a way PHP can understand it, and be sent. So, the rewritting to the json data will be:
PHP jsonConfig.php
$var = array(
'itemGuitar' => array(
"id" => "itemGuitar",
"description"=> "Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.",
"price" => 5695.99,
"urls" => array(
"thewho",
"Pete_Townshend"
)
),
"itemCowbell" => array(
"id" => "itemCowbell",
"description"=> "Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.",
"price"=> 299.99,
"urls"=> array(
"Saturday_Night_Live",
"More_cowbell"
)
),
"itemHat"=> array(
"id"=> "itemHat",
"description"=> "Michael Jackson's hat as worn in the \"Bille Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.",
"price"=> 1699.99,
"urls"=> array(
"abc",
"def"
)
)
);
echo json_encode($var);
In this way, when you'll call jsonConfig.phpp you'll get the json. If you can get your data in a PHP file in this way, would be perfect, if not, you'll have to parse from this way to a PHP way (with 'array()' instead of '{}' for grouping data and '=>' instead of ':' to write indexes.
Update to Output Json file
if you don't want to transform the file (because you really only have a json formated file), you may also output the data with Nowdoc (PHP 5.3) or Heredoc strings (lower PHP versions), to avoid problems with double and simple quotes (See more info at http://www.php.net/manual/en/language.types.string.php):
$str = <<<'EOD'
{
"itemGuitar": {
"id": "itemGuitar",
"description": "Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.",
"price": 5695.99,
"urls": [
"thewho",
"Pete_Townshend"
]
},
"itemShades": {
"id": "itemShades",
"description": "Yoko Ono's sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.",
"price": 258.99,
"urls": [
"beatles",
"johnlennon",
"yoko-ono"
]
},
"itemCowbell": {
"id": "itemCowbell",
"description": "Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.",
"price": 299.99,
"urls": [
"Saturday_Night_Live",
"More_cowbell"
]
},
"itemHat": {
"id": "itemHat",
"description": "Michael Jackson's hat as worn in the \"Bille Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.",
"price": 1699.99,
"urls": [
"abc",
"def"
]
}
}
EOD;
Getting data from Client Side
About getting the data from client side, if you send data with, let's say jquery, in a json way, you only have to catch them with json_decode function. I mean:
fileToEdit.php
<script>
//Data to be sent
var cuenta = new Object();
cuenta.red = 'Facebook';
cuenta.tipo = 'UserAccount';
cuenta.cuenta = '11002032030100202120';
$.ajax({
type: 'post'
, url: '/processDataFilePHP.php'
, dataType: 'json'
, data: { cuenta: cuenta }
});
</script>
processDataFilePHP.php
$postear = (array) json_decode($_POST['cuenta']);
// For seeing the received data:
print_r($postear);
This way you'll get the data from the application, and with $.ajax function you can change your way editing and getting data.
I think this may be useful, if you have more restrictions, tell me what and we'll try to workaround, ;)

Json into mysql

The aim is to save user entered JSON into a database. Now, before someone jumps at me, I know json, I know mysql and I know all the links inbetween.
The issue is: I need to safely store the ENTIRE JSON feed in a single cell in the table.
The background: this function will be a temp fix for a tool, that is needed asap but will require a lot of time. The temp fix will allow the system to go live with minimal code.
Users will create a GOOGLE maps style here ( http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html)
and have the JSON made for them
[
{
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "water",
"stylers": [
{ "visibility": "on" }
]
},{
"featureType": "transit.line",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "on" },
{ "hue": "#ff3300" },
{ "color": "#ff0000" },
{ "weight": 0.7 }
]
},{
"featureType": "transit.station.rail",
"stylers": [
{ "visibility": "on" },
{ "color": "#0000ff" },
{ "weight": 4.6 }
]
},{
}
]
The site will then just call the JSON and apply it using jQuery later on. What would my ''best practice'' method be at doing this.
To answer your specific question, I would agree with the poster 'tom' that you should use a TEXT column.
However, I think for ease of use, you should also use prepared statements. If you create a prepared insert statement, you can then pass in the JSON directly. This will be the best representation in your database of the exact JSON (no annoying slashes) - AND be the safest. Please don't forget to do this step - its very important!
Since MySQL doesn't have a dedicated JSON column type, I would just store the JSON in an unbounded TEXT column. Just make sure you always check for valid JSON on write.

passing string in "textfield" to another part in code

I have one question about passing strings from one Ext.formPanel textfield to another part of the code. The thing is that I have two "textfield" in the formPanel and I want the words I enter there as part of the "url" I have in the code. Probably you may ask, why does this guy want that?? this is because the "url" I'm using has a PHP script that generates features stored in a postgis db table as GeoJSON.
This the code:
[CODE]
// define the data source
var protocol = new OpenLayers.Protocol.HTTP({
url: "http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom&parameters=" + "column" + ilike '%"string"%',
format: new OpenLayers.Format.GeoJSON({
ignoreExtraDims: true,
'internalProjection': new OpenLayers.Projection("EPSG:900913"),
'externalProjection': new OpenLayers.Projection("EPSG:4326")
})
});
formPanel = new GeoExt.form.FormPanel({
title: "Place Name Search",
height: 150,
region: "north",
protocol: protocol,
items: [{
xtype: "textfield",
id: "column",
emptyText: "Choose table column",
fieldLabel: "Choose table column",
width: 200,
allowBlank: false
}, {
xtype: "textfield",
id: "string",
emptyText: "Search inside table",
fieldLabel: "Enter a word to search",
width: 200,
allowBlank: false
}],
listeners: {
actioncomplete: function(form, action) {
features = action.response.features;
store.loadData(features);
vm=map.getLayersByName("Results");
if(vm.length===0){
vecLayer = new OpenLayers.Layer.Vector("Results");
map.addLayer(vecLayer);
store.bind(vecLayer);
select.bind(vecLayer);
}
}
},
buttons: [{text: 'search',
handler: function(){
formPanel.search();
}
}],
keys: [{ key: [Ext.EventObject.ENTER],
handler: function() {
formPanel.search();
}
}]
});
[/CODE]
These are the cases I already tested:
url: http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom: this generates the whole table "boreholes_point_wgs84" as GeoJSON.
url: http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom&parameters=station ilike '%llena%': this generates only one feature, the feature that has "llena" in the "station" column. So, in this way I can find the feature through the search form.
What I was thinking is if I can pass these two strings I enter in "textfield" and modify the "url" in the way that it can catch these two words and form, for example, the second case I put above. I was playing with this:
url: http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom&parameters=" + "column" + ilike '%"string"%', so using the "id" I specified below each xtype, but it doesn't work.
I appreciate any support on this, thanks in advance,
Best regards,
Gery
The correct way to this is a simple form submission. The text input values will be sent to the server in a form post. Server side should parse the submitted values and do what's necessary. This isn't any different from the use of plain HTML and any server side frameworks.
Alternatively you can force your form to submit using HTTP GET method instead of POST and then your input values will be part of your URL. In ExtJS you use 'method' config. See API docs: http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.Basic-cfg-method
EDIT: if you are not at all interested in actually 'submitting' the form you can get your field values like this: form.findField('myField').value
I'm pretty sure that this solution will help to understand how to solve this problem, I solved myself.

Categories