Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  153] [ 3]  / answers: 1 / hits: 26630  / 12 Years ago, mon, november 12, 2012, 12:00:00

I have a javascript file and I want to call a function on the php server side and return the result back to the client side using ajax, but I am not sure how to make the request to the specific php function.



Here are my files:



The javascript file basically retrieves the username from the html form, and I want to send that username to php and check against the database for availability.



In something.js:



function check_availability()
{
var username = $.trim(document.getElementById('usernameField').value);
var xmlhttp= new XMLHttpRequest();

// not sure how to make the request here to check_availability() under php
}


The PHP file will just check the username thats being passed from the js file against the database, if its available return true, else false.



In something.php:



    class Something_Model {
private $data;
private $table;

public function __construct() {
$this->data = new udata(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
}

# check for username availability
public function check_availability()
{
// make the check here, but needs to retrieve username from js file
echo here;
}
}


So, inside the Something_Model class, I want to make the check_availability() call from javascript, can someone give me an example to make this ajax call? Also, how do I return the result back to the javascript? Do I need to encode it as a JSON obj?



Thanks a lot.


More From » php

 Answers
8

You can't call a function in PHP directly - but you can call a PHP page that in turn can call the PHP function. For example...



service.php



include_once('something.php');
$model = new Something_Model();
$model->check_availability();


something.js



function check_availability() {

var request = new XMLHttpRequest();
request.open('GET', 'http://yoursite/service.php', false);
request.send();

if (request.status === 200) {
alert(request.responseText);
}
}


I have used a really simple example of an XMLHttpRequest - this example actually blocks while the request is made. In reality you may want to use a callback and allow it to run asynchronously but I wanted to keep the answer as short as possible.


[#82036] Saturday, November 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesse

Total Points: 513
Total Questions: 118
Total Answers: 106

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;