Question

I'm using Easyphp 5.3.5.0 on my pc to bulid some Ajax simple dynamic operations.

I would to refresh a list on click to "add item" button, so the button have an event on click.

The first javascript page do this in the click event:

$.post("operation/insert.php", { type : "cliente", name : nome, surname : cognome ,  description : descrizione, day : giornoNascita, month : meseNascita, year : annoNascita }, function(data){  
alert("HELLO!");
},'json');

In the Php page, "operation/insert.php", after preliminar checks on the variables I run this code:

$q_add_client = mysql_query($query);

    $return = array(
        id => mysql_insert_id(),
        response => 0
    );

    echo json_encode($return);

I'm sure that the query is executed, because I can see the new item in my database. But, at the end, i don't see my alert("HELLO!"), so i think that there's a problem with json_encode function and his parameters. It don't execute my callback function in Javascript module, at row $.post(...).

Can anyone help me please? Thanks

Was it helpful?

Solution

If you're telling $.post to expect 'json' from the server, and whenever you send json to the output, you should set correct content-type first:

$q_add_client = mysql_query($query);

$return = array(
    'id' => mysql_insert_id(),
    'response' => 0
);

header("content-type: application/json");

echo json_encode($return);

OTHER TIPS

Try this syntax using jQuery.ajax method

$.ajax({
                url:'operation/insert.php',
                type:'POST',
                data:{
                 type : "cliente", name : nome, surname : cognome ,  description : descrizione, day : giornoNascita, month : meseNascita, year : annoNascita
                },
                success:function(data){
                    alert('HELLO');
                }
      }) 

and if you got an error like as your comment below

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

write this code in your page

if (!event.preventDefault) {
    event.preventDefault = function() {
        event.returnValue = false; //ie
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top