call PHP script after form submit - php

I have two separate processes and I am wondering how I can combine them.
I have a PHP email sign-up form which posts the users email address and other data into an SQL DB.
I have a sync PHP script API which once run adds all info from the SQL DB to a 3rd party site (mailchimp)
How can I combine them so once a new user adds their details, and the form is submitted the PHP API script runs. I did this, however it runs the script and the user has to wait until the API call is done:
$appUrl = $_SERVER['HTTP_HOST'];
$path = 'newsletter/mailchimp.php';//your path here
$appUrl = 'http://'.$appUrl.'/'.$path;
if (count($_POST)>0) echo file_get_contents($appUrl);?>

Find an HTML-element which you can bind your function to, like your form, button, checkbox or whatever. There's many different ways like $("form").submit(function(){});, .click, .changed. After that you can use the $.post() function to call the PHP-files.
$(document).ready(function(){
$("#buttonId").click(function(){
$.post('phpfile1.php');
$.post('phpfile2.php');
});
});

If you're getting the content from a remote site, then you can't send it to the client before you've got it.
But in your example you are calling a URL on the local machine - if you include the file instead of calling it in a new HTTP request then you'll get a small improvement in speed.
If you don't need the content from the other URL, then call it from a shutdown function after your script generates the content flushes its buffers and exits.
Calling the second url via javascript is ot a good idea if the transaction spans both codesets - you're putting the user in control of the flow in your application.

Related

Can i call a method on the same php page also a method in another php code simultaneously on form submit using jquery ajax?

help me! I am a php rookie and i am confused with the php request.
Working on MVC structure for view, I created a HTML form, and on form submit i want to do call two different methods sendMail() and validateData() available in two different controllers (php file) - say one in process.php and another in register.php .
On form submit first I want to validate the data and save data to database using validatedata(). Then I want to send a verification mail to the user using sendMail().
To handle the request (click event) I am using jquery ajax. Ajax takes a single URL for posting data to the specified URL. So how can I make two different URL requests in a single Ajax call, or say how can I call both the methods in a single Ajax call?
Please suggest me what i should do to solve this issue?
thanks in advance.
A controller should handle an entire request.
So if the user makes (for example) a request asking to create a new user account then a single controller should:
Validate the data the user has sent to make sure it is what is required before creating an account
Create the account in the database
Send the email
Return a response saying if it worked or if there was an error
So you'll end up with something like
{
$errors = validateData($_POST);
if ($errors) {
echo generateErrorPage($errors);
exit;
}
$result = createUserInDBAndSendEmail($_POST);
showSuccessPage($result);
}
(That's very rough and ready for the sake of example).
Don't divide the steps you need to do to complete the task up between different controllers. Then you only have one URL to worry about.
You can divide the functions up between different files and then include them.
The complete process for creating a user might require additional feedback from the client, e.g.
Client makes a request to the CreateUser controller
Server creates a user in "unconfirmed" state, sends email to the user and returns an HTML page telling them to check their email
User clicks a link in the email to make a request to the ConfirmEmail conroller
Server changes the user to "confirmed" and returns a logged in homepage with a welcome message
… and in that case it would have multiple controllers since you need the user to make two different requests.

Passing variables into a function instead of ahref

Instead of using code like this:
'<td> Cancel
I would like to be able to simply call a function and pass the $memberId and $classId into that instead of having to create a new PHP page to run some code with these values.
So basically the user will click the 'cancel' button and then it will run a function from another class, instead of clicking the button and then having another page deal with the request.
How would I go about doing that?
No! You have to use JavaScript for that. PHP is a server-side language, and PHP process died when you see something in the browser page.
The only way for HTML page loaded in a browser and a PHP program hosted on a web server to interact is through HTTP requests.
You can't call a PHP function from a web page. You can only make an HTTP request (e.g. through a link, a form submission or XMLHttpRequest) which sends some data to a PHP program. That program can then look at the data (e.g. via $_GET) and use that to determine which function to call.

How to keep track of multiple request data from the same user in PHP sessions?

So the question is a little complicated, let me explain. My page code is running like this:
User enters query in the search field and clicks submit.
1.1 jQuery loads a new body to display progress data.
1.2 jQuery calls process.php via AJAX and supplies query as the argument.
1.3 jQuery starts setInterval periodic update to grab progress data, stored inside $_SESSION['prog'], and displays it.
When process.php finishes, jQuery stops periodic update, displays final information and calls AJAX to clear the $_SESSION['prog'] variable.
At the moment progress data is stored inside one variable, which is fine as far as different users are concerned (because of the different sessions), but if the same user were to make multiple requests at the same time, the $_SESSION['prog'] variable would be cross-overwritten.
So far I have thought of two possiblities to distinguish data for each request from the same user (same session)
Have jQuery generate some random string and send it together with query (and hope to avoid colission, although that would be unlikely)
Make 2 AJAX calls, first one requesting new_request_id, the second one sending query and new_request_id as parameters.
Have AJAX return something from PHP before is finishes(completes).
I need to connect each browser window (each request) with each running process, so I cannot send back new request ID after the request has been submitted, because I wont know which data to pick up with jQuery in the browser window. Btw, I will change $_SESSION['prog'] to $_SESSION[request_id] -> request_id is what I'm looking for.
It (request_id) could be last_insert_id(), because im creating new DB entries for each valid query, but I don't know how to get it back to each different user window.
I need advice here. Only just begun to code in PHP, AJAX and jQuery, don't really know much about sessions. How should I solve this problem?
Sorry for the lack of code, I will paste is at request.
You could add a unique ID to each request in addition to the session ID. eg. uniqid() in javascript/jquery?
You need to differentiate them somehow. For example use a unique ID autonumber field. MySQL has last_insert_id() which is very useful and handles concurrent requests correctly.
Avoid using Session variables in Ajax requests. Send them with GET (or POST) instead. Even if calling Session_start(); in the Ajax request and getting $_SESSION['prog'] from there, results can be unexpected.

Terminate connection to jQuery AJAX request, keep processing php on server side?

I have a signup form that calls a PHP script which can interact with our CRM's API, like so:
CRM API <--> PHP script <--> Signup form
The signup form passes some information to the PHP script in one
AJAX call
The PHP script run a dozen API calls to the CRM to create
an account and attach various data
The CRM returns the new account id it just created to the PHP script
The PHP script passes the account id back to the signup form, at which point the AJAX call is complete and the signup form can continue.
The problem is #2, those dozen calls take about 20 seconds to complete, but the data the signup form needs is generated after the first API call so it could in theory return that data much sooner and do the rest of the stuff server side without holding that AJAX call open the whole time.
I tried flush() and ob_flush() which does output account id to the client before processing is complete, but the jQuery AJAX connection remains open so I'm still stuck waiting for the connection to be closed on the signup form side before anything happens.
So what's the easiest route for returning that account id to the form as fast as possible?
Maybe break out using curl and exec?
if(signing up){
stuff
exec(curl myself, notsignup)
}
else {
bunch of api calls
}
You should probably think about creating a seperate process for the rest of the steps that are needed. One way is that you could after the #1 first api calls has been completed. It responds back to the user, and doesn't try to complete the rest of the 20 calls on the user side.
Then create a queue that will finish the rest. You could always create a table in mysql to store the queue.
Next just create a cronjob that will run in the background, knocking the queue out.
Note: You will not want this cronjob to just start and never stop. Maybe have it run every 5 minutes, but before it starts to run, check to see if another cron is still in progress. If it is then it will check in another 5 minutes to see if it is ok to run.
Hope this helps!
If you only need the information from the first API call to return the form, then I would probably try a different workflow:
Form calls PHP Script
PHP Calls first API Call
PHP Returns to Form
Form processes response
Form calls second PHP Script to complete the process
PHP finishes API Calls (the form can abandon at this point since it sounds like you don't care what happens from here on out).
The workflow requires a little more work and co-ordination for the developer, but presents the most responsive interface to the user.

Push update notifications back to PHP while calling a function

I have a PHP script that loads a function which uses Curl to log itself in to another webpage to get some data. This operation takes about 14 seconds altogether and some users might become impatient. I have a little busy loader to indicate activity.
I have seen this on other websites and want to know what technology I need to implement the following:
How can I send little notification messages back to the main site while the PHP function is running so the user knows about the progress.
Messages could be in the following form:
Logging in to website
Extracting data
Sorting data
Closing connection
You can do it using ajax, do the following.
1) Keep your curl code in the seperate php file.
2) While click the button, using js or jquery call that php file using ajax.
3) Before ajax return the reponse, you can display the div with your message, once you
got response, you can hide the div.

Categories