Interactive file processing in using PHP, jQuery and Ajax - php

I'm migrating an old MS-DOS Foxpro program to cakePHP, but in some part of the application process the user will have the possibility to load a text file and process it according to some business logic.
I worked the algorithm, and it's working fine, I programmed it in plain PHP.
But in some parts of the process the user must interact performing some tasks, in plain PHP it's possible to do it.
My question is:
How can I have an interactive file process on a MVC framework, since the controller had processed the data when it`s give the control to the view.?
jQuery-ajax could help?
What do you think?
Regards
Update
As Borislav Sabev pointed, I do this:
Create a file upload using using: jQuery Form Plugin
A PHP file parsing according the data structure on the uploaded file that returns to the client the parsed contents of the file in JSON.
Then the JSON data is sent for processing via ajax POST
$.each(data, function (i, fb) {
callAJAX(fb);
});
callAJAX just send the POST request
function callAJAX(fb){
$.ajax({
type: 'POST',
url: "proc.php",
dataType:"json",
complete: function(r,st){
},
success: function(r,st){
processError(r);
})
},
async: false
});
}
If there is a translation error, the PHP returns to the client an error message via JSON.
function proccessError(r)
{
$.each(r,function(i,d){
if (d['error'] == 1){
$.alert('Material not found in translation table','Error');
}
})
}
Now the big question:
When I open the $.alert dialog I want the user select the correct material via an autocomplete, but the code is no waiting for the user selection and pops another $.alert window. How can I tell jquery to wait to the user input an then continue with the processing?
BTW: this is the $.alert extension that I use:
$.extend({ alert: function (message, title) {
$("<div></div>").dialog( {
buttons: { "Ok": function () { $(this).dialog("close"); } },
close: function (event, ui) { $(this).remove(); },
resizable: false,
title: title,
modal: true
}).text(message)
.parents(".ui-dialog:eq(0)").wrap('<div class="error-w"></div>');
}
});

What #AD7six told you is completely right however your question is very vague.
What you seem to need is to provide an interactive (realtime?) way for a user to edit data after a files has been uploaded and processed?. If it is 'data arranged in rows' I can suggest some DataGrid - imagine this as a Web representation of your file's structure.
What you're trying to say with 'the view shows the result of a method or action on the controller' is that this case is in the normal HTTP (with MVC) flow:
Browser (user) initiates a request => Request is processed my Controller => Model is called (gets, saves or manipulates data) => Data is returned to Controller => Controller handles the data over to the View layer => The view layer renders, Controller returns the Response (the rendered view)
In order to do this thing interactively you will have to use AJAX (I propose AJAJ).
The overall paradigm in this case is that the above flow is iterated on every AJAX request. You can achieve this in many ways:
Use plain JavaScript and XMLHttpRequest
Use jQuery's XMLHttpRequest wrapper functions ($.ajax(), $.post(), $.get(), $.load(), etc.)
Some other JS lib's AJAX capabilities (MooTools for example)
Use an real-time JS app framework
This also heavily depends on the browsers (and versions) you need to support.
You will need to provide 'access' for the client-side via a controller or a full API. The best solution for an API would be REST. If this is an enterprise app I suggest you adhere to the Richardson Maturity Model.
If you don't need a fully-realtime app I'd go with jQuery AJAX or some other JS lib's AJAX.
The thing is that what you request as an answer is an overall explanation and that is why I am not going to provide code examples.
Cake has JSON views that you can use to return data.
The other option is an empty layout and a view that returns JSON encoded data like:
<?php echo json_encode($data);?>
Hope this helps. If anything ask.

Related

Is it possible to 'echo' a sequence of responses from an ajax call

I'm learning and experimenting with jquery/ajax as I develop a website. I have a page that updates a database. I would like a 'sequence' of responses to display on the screen when the user submits their data (I've seen this done on many other sites).
For instance... user submits form and the page displays:
Received Input
Checking Database - recond number xy
Updating Database
Retrieving Information
etc etc
This is just an example but you get the idea.
I have an ajax call that is initiated on 'click' of the submit button (getFormData just serialises all the form data for me and works fine):
var toSend = getFormData($upgrade_db_form);
var formMessageBox = $("#displayResults");
$.ajax({
url: ajaxurl,
data: {
action: "database_action",
formData : toSend
},
type: 'POST',
dataType: 'TEXT',
beforeSend: function() {
//$form.fadeOut('slow');
formMessageBox.html("starting it up");
},
success: function (data) {
formMessageBox.empty();
formMessageBox.html(data);
error: function (xhr) {
// formMessageBox.html("Oops error!");
}
});
I have a function which gets called by ajax:
function upgrade_database_function() {
echo "testing ";
for($i = 0; $i < 99; $i++) {
echo "percent complete ".$i."%";
}
echo "done ";
die(); // this is required to return a proper result
}
I'm using Wordpress and all the ajax side of things works fine, it passes the form data correctly etc, it's just that I get one long output as though it's cache'ing all the echo's up instead of outputting them in sequence.
I've gone through the jquery ajax documentation and couldn't find how to make it behave the way I want it to. I can live with it the way it is but I think it would look a lot better if I could get it working the way I would like.
Can this be done this way or do I need lots of sequential ajax calls to make it work?
I don't know PHP, but i'm guessing that the echo is just writing to the response buffer... so when all the echos are done the whole response will be returned and you would get the effect that you are seeing... You would need to go with a polling system or something along those lines to get the latest status' from the server and display them I would think... Maybe there is some system in PHP that allows this, but as I said, I don't know PHP.
An Example of Long Polling can be found in this article.
http://www.abrandao.com/2013/05/11/php-http-long-poll-server-push/
WARNING: You may have to do some manual managing of locking of the session in PHP so that your long running call doesn't lock your polling ajax calls: See here:
http://konrness.com/php5/how-to-prevent-blocking-php-requests/
Note that you would likely be wanting to:
create one ajax call that starts the execution of some coded that will take a while... you could put messages that have been generated into a session variable for example in a list of some sort. You would need to lock/unlock the session as mentioned to prevent suspension of AJAX polling calls.
you would create a polling method like in the article that might check the session every 500ms or something to see whether there are any more messages, lock the session, remove those messages and return those messages to the client side and display them.
WARNING: Again, I'm not a PHP person, I may have done this once in my life in PHP (can't remember exactly) but I may be wrong and this may not work, from what I've seen though it looks like it is achievable. Hope this gets you on your way!

How can i change multiple portions of a webpage with ajax onclick?

In my website I will have a "browse catalogue" button, which, onclick will change several elements of the page to display the catalogue element. I dont want a full page reload because several elements such as the nav bars and news feed will stay the same.
My question is how can i change several different divs with ajax onclick?
Essentially im not sure how to do place several different components in different divs across a page.
And i know there's a limit on simultaneous ajax calls, so im sure the proper way to do it wouldnt be to make a unique ajax call for each of my divs.
A little guidance would be great.
Using jQuery, you can get an json array of elements for each block that needs to be updated:
In your html page:
$.get("page.php?id=42",
function(result){
$('#title').text(result['title']);
$('#description').text(result['description']);
$('#price').text(result['price']);
}, "json");
In page.php:
$result = array('title' => 'foo', 'description' => 'bar', 'price' => 3);
echo json_encode($result);
header('Content-Type: application/json');
die();
I'm not sure if the right decision will be to send several ajax requests. Just create a request with unique attribute value, in so shape that server will know which blocks you need. On server side all required blocks concatenate in json object, and return it to client. After just parse object on blocks that should be. For example
$.ajax({
url : 'http://your.server.doment',
data : 'block[]=1&block[]=7&block[]=15',
type : 'post',
dataType : 'json',
success : function (object){
for( el in object) { $('#block_'+el).html(object[el]); }
}
});
you can use json
example
php request ajax
$div1="<table><tr><td>x</td></tr></table>";
$div2="<table><tr><td>x</td></tr></table>";
$div3="<table><tr><td>x</td></tr></table>";
$json = '{"div1":"'.$div1.'","div2":"'.$div2.'","div3":"'.$div3.'"}';
return $json;
uses jquery
$.ajax({url: 'ajax/test.php',
success: function(data) {
var obj = JSON.parse(data);
$("mydiv1").html(obj.div1);
$("mydiv2").html(obj.div2);
$("mydiv3").html(obj.div3);
}});
if you have a error in the parce function
replace spaces
example
$arr =array("\n","\t");
$div1= str_replace($arr,"",$div1);
Practically, ten or more elements updated in parallel on the page (each by a separate ajax) will not make such a big difference (unless you can test it with your website deployed into productive environment and prove I am wrong).
Nonetheless, if you wish to compact all the data exchange to one single request/response ajax call - it is very well possible but does require certain flexibility on the server side (see http://php.net/manual/en/function.json-encode.php).
I.e. one of the possible solutions is to produce json response on the server side, that generates a key-value pairs (JSON - javascript {} object) with keys being id of your elements and values being (new) html.
There are tons of ajax JS frameworks as jQuery, prototype, dojo, etc. (I will pick jQuery for this one).
Ajax request
$.ajax({
...
})
See http://api.jquery.com/jQuery.ajax/
Server response
// Assume we got
// var data = {key1:'html1',key2: 'html2'};
// Ajax handle can look like
success(data) {
$.each(data, function(key, val){
//console.log(key, val);
// Do some checks here.. But key should indicate #id of html elements
$(key).empty().append(html);
});
}
This is a basic outline but should keep you going into the right direction.

PHP / AJAX Application structure

I'm working on a PHP / AJAX application and it's quickly becoming unmanageable!
The application is designed to work much like a a desktop application so almost every user action results in an AJAX call.
For every one of these actions I have some jQuery that posts the data to my PHP script and runs a corresponding PHP function that handles the server side actions.
That means in my jQuery file i'll have something like this:
$('.delete-project').on('click', function(){
// Ajax request to http://myapp.co.uk/ajax/delete_project
});
$('.delete-user').on('click', function(){
// Ajax request to http://myapp.co.uk/ajax/delete_user
});
$('.delete-keyword').on('click', function(){
// Ajax request to http://myapp.co.uk/ajax/delete_keyword
});
I'm sure there is a better way of doing things, but how is it generally done to avoid lots of similar code? The above actions could possible rolled into one 'delete' ajax request which posts the item type and a database ID but a lot of my functions post different data and require different parameters so wouldn't fit so neatly under one jQuery handler.
I've tried finding some resources on how an AJAX application should be put together but all I can find is beginner tutorials on making AJAX requests etc, not how to write a scalable AJAX application.
Just to be clear I know how AJAX works, I'm just trying to find the best way of implementing it in terms of reducing the jQuery and PHP needed where possible.
Are there any good resources that deal with this sort of thing?
You can roll all those into one delete function by using attributes in HTML, for example:
$('.delete').on('click', function(){
var delete = $(this).attr('data-delete');
// Ajax request to http://myapp.co.uk/ajax/delete_{delete}
});
Then your HTML would be something like:
Delete
More information on data-attributes
Not sure if this would help but you could create some functions to reduce your code as it grows. For starters you could prevent duplicating of the ajax call by putting the jQuery .ajax function in a custom wrapper function of your own. For example:
function ajaxGet(myUrl, queryString, successCallback, errorCallback) {
if(queryString) myUrl+= "?" + queryString;
$.ajax({
url: myUrl,
type: "GET",
data: null,
success: function (res) {
if(!successCallback) return;
else successCallback(res);
},
failure: function (res) {
if(!errorCallback) return;
else errorCallback(res);
}
},
By creating a wrapper function, you can pass in the needed data without duplicating the $.ajax call code over and over in each of the click functions. You can also create a similar function for an ajax call using post. You could then dynamically build the click functions to further reduce your code:
function buildClicks() {
setupClick([url], [data], [success], [error], [$(elem)]);
setupClick([url], [data], [success], [error], [$(elem)]);
setupClick([url], [data], [success], [error], [$(elem)]);
}
//Setup clicks for each button or link
function setupClick(url, data, success, error, elem) {
elem.click(function () {
ajaxGet(url, data, success, error);
});
}
In this example I'm assuming your using a "GET" and adding a query string. You could easily adapt this to pass, a JSON formatted object for example, using a custom "POST" function. In that case [data] would be an object not a query string.
Sorry this code isn't the clearest. Let me explain it a little more. The buildClicks function would allow you to setup multiple click events on different elements by passing in the required data. I'm not sure if you are passing any data, but the above functions would allow for it. By dynamically creating the clicks you can avoid duplicating the .click code over and over. Just call the buildClicks function on document ready as such.
$(document).ready(function () { buildClicks(); });
NOTE: The success and error callbacks are functions that will be executed when your call either completes successfully or errors out. If you do not wish to use these they can be ommitted or null can be passed in. Make sure if you do pass in functions that you leave off the "()" on the end of the function name. Otherwise the functions will be executed prior to the success or failure of the ajax call. For example:
ajaxGet("http://testurl.com", null, ajaxSuccess, ajaxFailure);
ajaxSuccess() {
}
ajaxFailure() {
}
You could set an ID attributes to that buttons and a class like submit-button.
Then hang a handler on that $('.submit-button') while using an ID attribute value to define the URL to call, like that:
$('.submit-button').on('click', function(){
$action = $(this).attr('id'); //lets say the ID's value is 'delete_project'
$url = 'http://myapp.co.uk/ajax/' + $action;
// Ajax request to http://myapp.co.uk/ajax/delete_project is done
});
Anyway any web application that tends to be like a desktop one is only a bunch of JS and few HTML with some PHP behind... That is always badly maintanable...
I used [extJs][1] once for this, which led to using only jQuery and their modules while no (or just a minimum of) HTML was needed to write...
Not a copy-and-paste-solution, but maybe you find some more ideas how to build a scalable client-server application when looking for how REST APIs are built. I find REST a very good structure to keep a clear server-side API when building such apps, and i'm sure there are tutorials around how to do the corresponding client-part cleanly too.
In my application I do quite a lot of ajax calls too. I found that the easiest way to do things was to create myself a wrapper for all ajax calls such as:
var MySite = function()
{
AjaxWrapper : function(type,url,data,callback,noloading)
{
$.ajax({
type: type,
url: url,
data: data,
success:function(json)
{
if(json.status === true)
{
if(typeof callback === 'function')
{
callback(json);
} else {
// A generic success handler
}
} else {
// An error handler
}
}
});
};
}();
then you'd call it like:
MySite.AjaxWrapper("GET", "somehref", {}, function(json)
{
// json has the result of your json callback
// you could also make this a separate function
// or not have it
});
this let's you call your ajax on just about anything you want. You could then use something like data attributes, or just the standard href for anything that requires ajax and add an event to all links that pass through this function. Or, if you wanted some to do certain things just make the callback function different for those.
I'm finding this hard to explain, but this is what I've used for a couple of ajax-rich projects and it makes things so much easier!
For an example for your case you could then use something like:
$('a[class|="delete"]').on("click", function()
{
MySite.AjaxWrapper("POST", $(this).attr("href"), {param:number1}, DeleteHandler);
});
The way I would do this would be to have a single function for all actions:
$('.actions').on('click', function (e) {
e.preventDefault();
var action = $(this).data('action'),
id = $(this).data('id');
$.get('/local/handler.php', {
'action': action,
'id': id
}, function () {
// Callback stuff here
});
});
And HTML:
Delete Project
Delete User
Delete Keywork
And the PHP file should have if statements based on the action parameter that performs the requested action.
EDIT:
This way your not limited to just delete actions, so you can scale your app in the future.
Also, If the different actions become a large list (e.g. deletes of many kinds, updates, adding), I would create a separate PHP file for each action and include them in one master file. This will allow for easy scaling.

triggering a portion of a php script through a user action without going into a new form?

I just started learning PHP and was wondering if there is a way to trigger a portion (a function really) of a php script when a user clicks on a link/button without redirecting the user to a new php script page?.
Basically, is there a way to invoke php functions through client side user actions like you have in javascript?.
PHP is not client side. It simply generates a page and sends it to the user's browser.
You would need to incorporate javascript into the page you are returning for client side actions. The most common approach is having javascript make AJAX calls to php scripts on the backend.
Here's how you can do it with JQuery using $.ajax() [Docs]
$('#my-button').click(function(){
$.ajax({
url: 'my_php_page.php?route=my_preferred_function',
data: 'foo=bar',
type: 'post',
dataType: 'json',
success: function(data){
alert('Response = ' + data);
}
});
});
Most MVC frameworks - one example being CodeIgniter allow you to execute specific functions in the controller via the URL: http://domain.com/mycontroller/myfunc. If your function takes two arguments, for example:
public function foobar($foo,$bar){
// do something
}
You can access it via http://domain.com/mycontroller/foobar/abc/123 making your ajax calls super easy.

Safe JavasScript that calls PHP script that calls external web service

I have a PHP page that needs to make a call to a external web service. This Web service call takes a bunch of sensitive data from a html form on the PHP page, e.g. SSN, and returns info related to that person.
The problem is that the web service call should be made as soon as the customer fills in the SSN field and the field loses focus, so the page cannot be reloaded in any way. I was thinking about using jQuery to make a call to the web service, but AJAX unfortunately requires that you are on the same domain as the requested resource. So I'm thinking about creating an local PHP page that makes the call to the web service and then use JQuery to call this new page.
Questions:
How do I use JQuery to call the local PHP script that makes the call to the web service?
Because the JQuery code will take sensitive data from a html form and send it to the PHP script, how can I encrypt the data?
To call your PHP file:
var url = "http://localhost/data.php";
var params = {
"SSN" : theSSN
};
$.get(url, params, function (){
// Do whatever you need here, once the data arrives.
});
To call the external webservice from PHP, I'd suggest using cURL.
To encrypt, I'd suggest using the HTTPS protocol instead of encrypting manually from JavaScript.
1) $.get("myscript.php", function(response) { alert(response) });
2) I wouldn't encrypt using jQuery, it would be slow and easy to decrypt. Enabling SSL on the server would be a better solution.
1: Ajax request example:
$.ajax(
{
type: "GET",
url: "http://yourdomain.com/yourpage.php",
success: function (msg) { //does something }
});
More details here
2: php XOR is a pretty good encryption algorithm, I use it myself for a project with sensitive data. you can find the function here.
Enjoy! :)
This probably won't help you in particular, but some webservices support something called JSONP, which adds a callback name to a normal JSON request.
However, chances are you will need to make some sort of local proxy, as not many JSONP services exist yet.
The way to go is enabling SSL on your domain, and doing the xmlHTTPRequest to the https of the remote service

Categories