Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Shon Levi
Shon Levi
6,036 Points

Using JavaScript/jQuery with Php?

Hey you all, I'm tring to code some function in Jq/Ajax to check validation of form and if work to add it to the mysql, I got functions and variables in the php files to manage sql, but the ajax check is in jq - how can I use the php functions and variables in the jq code???

4 Answers

Seth Kroger
Seth Kroger
56,413 Points

You wouldn't access your PHP variable and functions in your client-side JavaScript. The codes are running on two different machines. After your JavaScript validates the form on the browser, the AJAX call sends the form to the server. So, instead of calling the code directly, you're sending a message to the server that you have a request that needs to be processed and stored. After the PHP takes care of that request, it sends a message back in response.

Shon Levi
Shon Levi
6,036 Points

This is my code so far:

checkForm - is function in jq to check validation of form

        $("#add_task").submit(function(evt) {
            evt.preventDefault();

            if (checkForm) {
                var url = $(this).attr("action");
                $.ajax(url, {
                    method : "POST",
                    data : $("#add_task").serialize(),
                    success : function(response){
                        // NEED TO RUN FUNCTION IN PHP - HOW
                    }
                });
            }
        });
Seth Kroger
Seth Kroger
56,413 Points

Your "#add_task" URL should resolve to a PHP file that will accept the POST request and process the form. Strictly speaking, the URL should be for a separate "page", not necessary an id anchor on your current one. If you already have the routing set up to take care of that though, great. The PHP will be run when you make the AJAX call. What the success callback is for is to handle the response you'll be sending back.

Shon Levi
Shon Levi
6,036 Points

So for each call of ajax I'll need a seperate file of php code to handle it? There is no other way to manage all ajax call in one file??? how?

Seth Kroger
Seth Kroger
56,413 Points

The PHP code runs on the server and outputs an pure HTML page (or other data formats, but lets stick to HTML). Once that page is fully output and sent to the browser, the PHP code is done. The only way to execute more is to make a new request to the server.