Save the contenteditable changes in json file using php ajax - php
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, ;)
Related
Laravel return simplified JSON from query
So I'm performing a query and getting data back like this: [ { "part_number": "MAC0009", "description": "Accessory Stand Foot" }, { "part_number": "MAC0010", "description": "Accessory Stand Collar Tapped M5" }, { "part_number": "MAC0011", "description": "Accessory Stand Top Collar" }, { "part_number": "MAC0012", "description": "25mm Round Knob With 2 Rail Holes" } ] However for the AJAX script I'm trying to implement I need the data in this format: [ { "MAC0009" : "Accessory Stand Foot" }, { "MAC00010" : "Accessory Stand Collar Tapped M5" }, { "MAC00012" : "Accessory Stand Top Collar" } ] So basically I need plain data back without the table names. All I have so far is the query. $result = DB::table('macs')->select('part_number', 'description')->get(); Which is obviously fine but I don't know how to manipulate the data into that format :/ Any help appreciated.
You can use lists method: DB::table('macs')->select('part_number', 'description')->lists('description', 'part_number');
Jit.js, Jquery Json & PHP json_encode odd issues
I chose to use JIT.js rgraph for a project I am working on. What I've done was taken the examples and began slowly merging the js into the projects core files. Simple! The hang up I've run into has me literally stumped. example.js has (assumed to be hand written at some point) json like so. var json = { id: "190_0", name: "Pearl Jam", children: [{ id: "306208_1", name: "Pearl Jam & Cypress Hill", data: { relation: "<h4>Pearl Jam & Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam <div>(relation: collaboration)</div></li><li>Cypress Hill <div>(relation: collaboration)</div></li></ul>" }, children: [{ id: "84_2", name: "Cypress Hill", data: { relation: "<h4>Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam & Cypress Hill <div>(relation: collaboration)</div></li></ul>" }, children: [] }] },... I need the json file dynamically generated in a sense and the most productive way for me to use the json is to create a static file if/when relative parts of the project are updated instead of generating json every time the page loads. Makes sense right? json.php looks like this $project = array( "id" => "1", "name" => "Testing Project", "children" => array ( "id" => "2", "name" => "Sub 1", "data" => array( "relation" => "<h4>Testing Project</h4><b>Structure:</b><ul><li>Sub1</li><li>Section 1</li></ul>" ), "children" => array( "id" => "3", "name" => "Section 1", "data" => array( "relation" => "<h4>Section 1</h4><b>Structure:</b><ul><li>Testing Project</li><li>Sub 1</li></ul>" ), "children" => '' ) ) ); // header('Content-type: application/json'); /* DOES NOTHING */ echo json_encode($project); my Arrays are hand written at the moment to make sure the process works as intended before programmatically generating the arrays from the database. There are other pieces to the puzzle I do not believe are at all involved at this time but the next piece we need to look at is the ajax call to fetch json.php which is in my custom.js file. function init() { var json = (function () { var json = null; $.ajax({ 'async': false, 'global': true, 'url': 'js/json.php', 'dataType': "json", 'success': function (data) { json = data; console.log(data); } }); return json; })(); ... continue with JIT.js functions I added console.log(data) to see if the json was coming back formatted and this is what that looks like console.log screenshot using custom.js ajax call So then I reused the example.js file and console.log(data) give us console.log screenshot using example.js The only obvisou difference is that the example.js json is be represented as an array, not an object. Even stranger still is that when I run the example using the custom.js file with the ajax call "Testing Project" does appear on the graph but no children elements. In the screenshot for custom.js console.log shows all the children elements as children: object, not children:Array[] like example.js My first thought was to see if I can ensure that all json_encoding forced the associative arrays into "arrays". And yea... lots of time wasted looking at the obvious. So my next thought was it must be in the formatting. example.js used [{ for each child element but json_encode does not. I cannot locate any information to confirm if that really is the problem or not, but, none the less I cant rule that out. I also checked into sequential indexes. example.js certainly does not have sequential indexes. I even went ahead and sorted the arrays before encoding json_encode(array_values($project)); to see what happens and while it outputs to a browser with indexes it of course shows nothing in the graph. I feel like im spinning in circles ( not in the good eagle circling prey kinda way ) but getting to far off focus to figure this out. I need some fresh perspective and ideas what might be going wrong. **Edit I've also tried to convert the strings manually with PHP. still not working. Any ideas?
WOW, Just over 24 hours and I end up doing something like this. It works by making each child with content an array of arrays. $test = array( 'id' => "1", 'name' => "testing sample", 'children' => array( array( ... ),array( ... 'children' =>array(), ), ) ); echo json_encode($test);
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.
How to turn JSON to object literal using PHP and jquery
Is there a concise neat way to turn an XML feed into an JavaScript object literal? I have this XML feed <jobs> <industry> <name>Technology</name> <area>Refrigiration</area> <area>Information Technology</area> <area>Electronics</area> <area>Avionics</area> </industry> <industry> <name>Agriculture</name> <area>Agri-Tourism</area> <area>Animal Husbandry</area> <area>Harvesting</area> <area>Poultry</area> </industry> </jobs> and wish to turn it to: var jobs = [ { "name" : "Technology", "areas" : [ "Refrigiration" , "Information Technology", "Electronics", "Avionics" ] }, { "name" : "Agriculture", "areas" : [ "Agri-Tourism" , "Animal Husbandry", "Harvesting", "Poultry" ] }, { "name" : "Media", "areas" : [ "Journalism" , "Camera person", "Reality tv person", "Commentator" ] } ]; I succeeded in encoding the JSON object using php. What I am missing is the rest.
echo json_encode(simplexml_load_string("<jobs> <industry> <name>Technology</name> <area>Refrigiration</area> <area>Information Technology</area> <area>Electronics</area> <area>Avionics</area> </industry> <industry> <name>Agriculture</name> <area>Agri-Tourism</area> <area>Animal Husbandry</area> <area>Harvesting</area> <area>Poultry</area> </industry> </jobs>")); This gives you: { "industry": [ { "name": "Technology", "area": [ "Refrigiration", "Information Technology", "Electronics", "Avionics" ] }, { "name": "Agriculture", "area": [ "Agri-Tourism", "Animal Husbandry", "Harvesting", "Poultry" ] } ] }
You need to convert your XML to an array, https://stackoverflow.com/questions/4844476/xml-to-php-array Then you'll need to convert the array to json using php json_encode()
If you are receiving a JSON encoded string in your javascript callback, you probably need to run $.parseJSON() to make jQuery treat it as a JSON object instead of a string
Two solutions: PURE JQUERY Using jQuery's parseXML , combined with jQuery get you can have the object you need: $.get("http://www.example.com/path/to/file.xml", function(data){ var xml = $.parseXML(data); console.log(xml); }); PHP+JQUERY if you've already parsed the object into a json, just print it into an html file and get that file using jquery's getJSON $.getJSON("http://www.example.com/json/feed",function(data){ console.log(data); });
jqGrid with JSON data renders table as empty
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.