-3
function aggiungifav(){
    document.getElementById("addfav").style.display = "none";
    document.getElementById("delfav").style.display = "block";
    <?php 
        mysql_connect("localhost", "", "");
        $utente = $_COOKIE['id_utente'];
        $id_locale = $_GET['id'];
        mysql_select_db("my_db");
        mysql_query("INSERT INTO preferito (utente,locale) VALUES ('$utente', '$id_locale')");    
    ?>  
}

Clearly it's wrong, but I post it to let you understand what I'd like to do. According to a lot of answers here on stackoverflow, Ajax is needed. But I never used it, so could someone help me? I have other functions but if you show me this one, I'll understand how it works and then I'll do the other ones by myself. Thanks

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Alessandro
  • 23
  • 4

1 Answers1

0

AJAX isn't a way to mix client-side and server-side code, as your attempt suggests. It's simply a way to make HTTP requests from client-side code without refreshing the page.

For example, let's say you have a PHP page like this:

<?php
    require('some_functions.php');
    some_function();
?>

All this does is import a script which has some functions and call one of those functions. So in order to "call that function" from the client-side code, you'd just need to request that page. Just as if you typed the address for this page into the browser and loaded it. (Though it has no output, of course.)

Since you tagged the question with jQuery, I'll assume its use. So your client-side code might look like this:

$.ajax({
    url: 'your_page.php'
}).done(function() {
    alert('success');
}).fail(function() {
    alert('error');
})

Note the addition of done and fail callback functions in particular. It's important to not assume success and to check the response of the AJAX call in some way.

Naturally, this can get considerably more complex. The server-side page can have output (possibly in HTML, though often JSON data is preferred since the page's HTML should really already be in the browser and it just needs data from the server), additional success/error information can be sent, data can be posted to the server, etc. Check the documentation for all of the options available to the jQuery $.ajax() function.


Regardless of the details of what you need this code to do, the main point to take away from this is that your client-side code doesn't call a function in server-side code. It requests a page of some sort. That page has server-side code like any other PHP page, and responds to the request by emitting output like any other.

It's all just HTTP requests and responses.

David
  • 208,112
  • 36
  • 198
  • 279