I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
Here's how I do it
Jquery Request
PHP Page Just takes the 2 input
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
1) This doesn't look nice
This is nice
2) Use $_POST
You just have to call the function inside your file.
The data is send in the
$_POST
global variable. You can access it when calling the check_user function:If you do this however remember to check the field value, whether no mallicious content has been sent inside it.