new to dojo and javascript in general. I'm working with a piece of code that requires a button to be different depending on what a php database query returns. The php script is already written, and the code I have currently is:
var store = new SimpleSaveWriteStore( {url: "info_get.php"} );
info_get.php returns the data as a JSON object, but what is the syntax to access the data members inside store? I've searched for this but there isn't a whole lot of documentation I've found on SimpleSaveWriteStore.
TL;DR - how would I access a specific piece of data retrieved in the above code? Thanks!
SimpleSaveWriteStore isn't a part of Dojo, so I am going to assume that this is this where you got the code from:
http://kennethfranqueiro.com/2010/06/custom-save-logic-itemfilewritestore/
This code extends the dojo.data.ItemFileWriteStore, and you can query against the store.
http://dojotoolkit.org/reference-guide/1.7/dojo/data/ItemFileReadStore.html#query-syntax
A couple things to note. Dojo is moving toward dojo.store api instead of the dojo.data api (which is the the ItemFileRead and ItemFileWrite store). The dojo store api documentation can be found at:
http://dojotoolkit.org/reference-guide/1.7/dojo/store.html
Also, if the data that you are getting back from the php script, is very simple, a store might not even be needed. You could use dojo.xhr to make the request and get json data. Then just use the json data to get the value that you need. The data and the store api use dojo.xhr to get the data. The documentation for dojo.xhrGet can be found at
http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html
Related
It took me a while to understand this, being that it was a little obvious. I will answer myself, so other can benefit of the answer and ofcourse to see if there's a better way to do this. The problem was based on Axios/Yii2 but I guess this will apply equally to other frontend libraries/frameworks sending data to Yii2.
I needed to post data from a small form made on Vuejs, sending the request Axios to a Action/Controller on Yii2, so data is sent on a simple POST request and the post is getting to the controller, but I was not able to receive the data on the action, $_POST | $post arrives empty (checked using xdebug).
As much as I remember, this had something to do with security. But I already tried by disabling public $enableCsrfValidation, so that was not the problem.
public $enableCsrfValidation = false;
But no matter what, data was not being added to the request/post data inside Yii2.
The following Image, explains the problem you will find there:
The Axisos method that sends the post with test data.
The Yii2 Action stpoed at the place, I should be able to see data.
The capture of the xdebug variables and data for the request.
The capture of Chrome where you can check the payload is sent.
The answer is as I said "kind of obvious", but I could not see that, and I am sure some other devs will probably fall on this.
After searching like crazy and asking everyone, I tried sending the request by using Postman app, yup the best thing I know to test apis.
Dont forgue to add the xdebug cookie to be able to debug your PHP Endpoint.
There I found the first clue «the obvious part», I was not sending data as a form-data, Axios and other libraries, send the data as a raw (application/json) payload.
This means that Yii2 will no be able to find the data inside the post request, yes its there but Yii2 magic will not work, neither you will find this data inside $GLOBALS or in $_POST.
So reading the Yii2 documentation I found that inside request I can use a function that will help me recovering the Raw data, so to do this use the following line:
$raw_data = Yii::$app->request->getRawBody();
Now, that data gets to you as a simple, raw json string, so use the power of PHP to parse it to an object.
$object= json_decode($raw_data );
And finally use the data inside by calling the properties you look for, sent on the pay load:
Json Payload:
{
"msg":"This is my payload",
"id":"11"
}
To use it:
echo $object->{'msg'}; // prints: This is my payload
So that's the way to handle that, now I would like some other points of view to see if there's a better way or cleaner way to do this. Hope it helps.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
With minimal "real" programming experience, I am working on a project that integrates a FileMaker Pro solution, which I have already built, with a native iOS application using FileMaker Server's PHP API. The iOS application is for iPhone and is written in Swift.
We are trying to understand the most efficient ways to approach some scenarios, particularly in writing data back to the server. Let's use the simple example of an address book. When a user navigates to a contact record, he/she can select a field, edit then save it's contents.
While we have already implemented a number of functions that write data to the server, they have all been relatively simple (like scanning a barcode, sending a php request that triggers a script in FM Server and then presenting the result to the client). It seems like, in the case of a contact record with many fields, that sending the value of each field as a variable, some of which may be paragraphs or photos, through a standard PHP URL inefficient and bulky.
For those unfamiliar with the FileMaker PHP API, below is some sample code to demonstrate the process of updating a specific contact record. The sample code does the following:
Sets parameters passed from the client as variables.
Defines the layout on which the code should be executed (FM PHP API works on layouts, not tables like SQL)
Finds a record and updates the fields.
Sample Code:
<?php
require_once 'Filemaker.php';
//connect to db
$fm = new FileMaker();
$fm->setProperty('database', 'fmDbName');
$fm->setProperty('hostspec', '123.45.67.89');
$fm->setProperty('username', 'user');
$fm->setProperty('password', 'password');
//define layout on which to process
$layout = 'php_contacts';
//define variables passed from client
$contactId = $_GET['contactId'];
$first = $_GET['firstName'];
$last = $_GET['lastName'];
$mobile = $_GET['mobile'];
$office = $_GET['office'];
$note = $_GET['note'];
//Find the contact which is being updated
$find = $fm->newFindCommand($layout);
$find->addFindCriterion('contactId', $contactId);
//execute the find
$results = $find->execute();
//check for error
if (FileMaker::isError($result)) {
echo " Error: ".$results." ";
exit;
}
//declare the record being updated
$record = $results->getFirstRecord();
//update the fields
$record->setField('firstName', $first);
$record->setField('lastName', $last);
$record->setField('mobile', $mobile);
$record->setField('office', $office);
$record->setField('note', $note);
?>
The challenge we are facing is not how to implement a particular approach, rather, the challenge is understanding what the options are in the first place and any best practices that go along with them.
For example, is sending the variables from the client to PHP as an array or dictionary a better practice than sending them as independent variables in the URL? What are some other options for neatly pushing data from multiple fields in a native application to the PHP server?
Thanks!
I'm pretty sure PHP basically works with HTTP requests, that is basically POST and GET.
The structures you send should be defined by what you need, there is no perfect solution.
You should check how HTTP requests work:
http://www.w3schools.com/tags/ref_httpmethods.asp
$_GET is much slower than $_POST from my understanding. You should send POST requests to the server from your application which will transfer strings. Sending raw images over the Internet can easily lead to distortion and missing data. In order to send images as strings you would use Base-64 encoding. That means you'll convert the image binary to an encoding scheme which returns a string. You can send this string to the server or the application for decoding. (Note: You can use Base-64 encoded images as URLs, which may come in handy.)
I don't believe there's a better way to send data between a server and client aside from using either a POST message or raw JSON if you can do that. Swift and Objective-C have a class named NSJSONSerialization which you can use to convert JSON returned from a PHP script for use later in your application.
From your server you can simply create an empty array in a variable at the beginning of the script for later use then append information to that array as it becomes available (If you have an image on your server you'll want to Base-64 encode it then append the string to the array only after the Base-64 encoding completes). At the end of the script -- when you have all of the data you want to send to the application appended to that array -- you can write echo json_encode($thatArray) to send the array back to the application as JSON. Of course, that means you'll want this to be an associative array from the beginning, because you'll have key and value pairs.
I'd rely on that method to fetch information from the server and flip it around (create a Dictionary in the Swift application then use NSJSONSerialization.JSONObjectWithData(data: NSData, options: NSJSONReadingOptions, error: NSErrorPointer) to convert the Dictionary to JSON. Then create a request which will send that JSON to the server via a POST request. Of course, your PHP script would use json_decode($_POST['thatJSONFromTheApplication'])) for the application to send JSON to the server.
That's what I've done to allow my application and server to work together. If you read this and you have a better idea, do share!
So there are a couple of things you could or should do.
Should do:
Move credentials out of the document
Move your database connection information out of your php code and into a configuration file stored outside of the server document root, i.e. if your doc root is at:
/var/www/myapp/public/
You could store your configuration file at:
/var/www/myapp/config/
That way if php somehow fails and returns as text vs php code, your credentials are not exposed. You could do this in many ways, but the easiest I've seen is to define them as constants. e.g.:
// File config.php
define('FM_DATABASE', 'fmdbname');
define('FM_HOSTSPEC', '123.45.67.89');
define('FM_USERNAME', 'user');
define('FM_PASSWORD', 'password);
and require the config file in your code and use the constants in your connection object:
$fm = new FileMaker(FM_DATABASE, FM_HOSTSPEC, FM_USERNAME, FM_PASSWORD);
Never dump the entire result if it's an error
You're not doing this in your code, but it's a good thing to know if you're dealing with the FileMaker PHP API. The Error Result object that is returned if your runs into a snag will contain your connection credentials. I have no idea why this is so, but it is. Never dump the entire object to the client because you'll be exposing those credentials as part of the dump.
FileMaker's Error object extends the Pear Error Object, so if you end up wanting to pass back information on an error that was encountered you can use any of the pear error methods.
Use the connection object to test for errors
The FileMaker API code is pretty out of date when it comes to php. the static method FileMaker::isError is actually not defined as static in the API code. This means unless you supress the deprecated messages on your web server you'll have the web server barking at you about it. The thing is, you've already created an instance of the FileMaker object so you can use it to check if your result is an error:
if($fm->isError($result)){ // this won't produce the deprecated warning.
...
That said, you'll probably see a bunch of other errors because of other deprecated code in the api :P
Could do:
Cache the record id in your client app
Right now you're performing a find for a record, updating it's fields, and committing it. This emulates the FileMaker experience, but because you're editing the data via the php interface you may be able to short cut it a bit.
If your client application (the swift app) knows the record id for the record that it's updating already then you could use the newEditCommand to update the record instead. The edit command uses the FileMaker internal record id (i.e. the id that FileMaker gives the record, not the id from your user-added primary key) to determine which record to update. Here's an example of how you'd use it:
$editQuery = $fm->newEditCommand('my_layout', $recordId);
$editQuery->setField('Status', $newStatus);
$editResult = $editQuery->execute();
The advantage of doing this is less processing time for FileMaker Server. You're not asking the server to find the record so you can edit it, you're telling it what record to edit.
Depending on how the business logic flows through your apps this may not be an option, but if you could store the record id on the client side it may help make the communication a bit snappier.
Handle the updates in batches
It looks like you're already doing this, but be sure to send the data in a batch vs one field at a time. I would agree with Arcrammer's comments about using POST instead of GET as POST is the intended method for sending data to the server.
Those are my suggestions on your code. I would also suggest digging around in the API code. I find that looking over the objects and there methods answered a lot of questions for me that the documentation and tutorials that FileMaker provides for the API did not.
Good luck!
I've got an iOS and Android app which downloads data from a database using JSON and PHP. Basically its a lot of mysql queries which returns data from my MySQL database. When I started this project is just created an array in php which holds all queries. Then I would send an index in my url to access that query and optionally some variables.
http://url.nl/script.php?index=1&var1=foo&var2bar
This worked fine and for a small project it wasn't bad but I knew this isn't good programming nor a good model.
So basically it's something like this:
APP with Model-View-Controller-Store model
When app needs data, Store classes request data through url and also send an index in that url
PHP script reads index, executes saved query in array, encodes data to JSON, returns data
App's store classes read and decode data
App's View classes present the data in any way wanted.
So I'm not really doing much with php other than accessing my database, encoding and returning data.
Since my app is getting very large and using more and more queries I wanted to do things right in my new version. What would be a good model for PHP to use in this scenario?
I'm no web developer so I was trying to keep all PHP processes to a minimum but realized this isn't a good way of programming.
Instead of just storing your queries in an array, you should instead use some kind of RESTful API on your server.
You then would send GET requests to your server, which executes them and returns the desired data. This could then be read and decoded. (You can also send and update data to the server).
There are a bunch of REST Framworks for PHP, but i used "Slim Framework" because its really easy to understand (even for people not familiar with php).
This Example from their Website:
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
makes it possible to call www.yourside.com/hello/Mark, which then returns "Hello Mark". With 5 lines of code. Its awesome.
You can write any php code there. To encode your data from a MySQL Database just follow this Tutorial: http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ Just ignore the JQuery part.
In your App you then request the Data from the provided URL. I use AFNetworking for this. (Google it, on their page find "HTTP Request Operation Manager" and look at GET)
I have a php file, and I'm using an API where if I have an id, I can obtain data through the API. However, I'm currently learning how to create a cache system. The API data is retrieved through JSON data. So I was wondering, if its possible to constantly add JSON data to the existing cache file that already has JSON data in it, so when I have an id, next time I'll search the cache file that matches the id instead of searching the API (which has a limit like any API does).
Maybe create multiple arrays and search for the id key?
I hope someone can understand this? I'm still looking around to help me with a caching script, if anyone have any ideas where I can look, that'll be very helpfuul as well.
Thanks!
No need to do that. Cache is often based on time that passed from last request. And in your case, since you are requesting data via API, i think it would be the best to cache the result pafe for few minutes or to not cache it at all.
I am trying to implement paging in PHP, using Json. I need the data to be preloaded, before the user click next results. Please Give me some suggestions or some references.
First off, JSON is for data communication not for data presentation. You need to store the JSON data in a persistent place, either a session variable or in Javascript variables. If you use the PHP session you'd use the PHP code to step through the data, if Javascript I'd go with JQuery. Just store the current starting point in the data in a persistent variable as well and use that as the place to start reading the data each time you display a new page.
jquery has a plugin you can use for pagination, the results have to be preloaded for this as far as i know. We are using this in an app currently, but it wasn't implemented by me...
http://plugins.jquery.com/project/pagination