Buonasera,
premetto che sono alle prime armi con javascript e st� cercando di creare una funzione per l'invio di alcune informazioni in background derivanti dalla compilazione di un forms. il problema � che lo script lavora correttamente ma al termine mi apre la pagina sendlike.php invice di rimanere sull'attuale pagina. i forms sono generati con il seguente php:
Codice PHP:
while ($riga = mysql_fetch_array($qry, MYSQL_ASSOC)) {
echo '<form method="POST" name="like'.$riga['id_photo'].'"action ="sendlike.php" onsubmit="InviaDati(); return false;">';
echo '<input type="input" name="id_user" value="'.$id_user.'">';
echo '<input type="input" name="id_photo" value="'.$riga['id_photo'].'">';
echo '<input id="'.$riga['id_photo'].'" class="like" type="submit" name="add_like" value="'.$qry_likes.'">';
echo '</form>';
}
La funzione che si occupa di inviare il dato in background � la seguente.
codice:
<script>
function dati() {
$(document).ready(function() {
$('.like').click(function(){
var recupero_id = "like" + $(this).attr("id");
return recupero_id;
});
});
}
function PreparaDati(){
stringa = "";
var form = document.forms[recupero_id];
var numeroElementi = form.elements.length;
for(var i = 0; i < numeroElementi; i++){
if(i < numeroElementi-1){
stringa += form.elements[i].name+"="+encodeURIComponent(form.elements[i].value)+"&";
}else{
stringa += form.elements[i].name+"="+encodeURIComponent(form.elements[i].value);
}
}
}
function AJAXReq(method,url,bool){
if(window.XMLHttpRequest){
myReq = new XMLHttpRequest();
} else
if(window.ActiveXObject){
myReq = new ActiveXObject("Microsoft.XMLHTTP");
if(!myReq){
myReq = new ActiveXObject("Msxml2.XMLHTTP");
}
}
if(myReq){
execfunc(method,url,bool);
}else{
alert("Impossibilitati ad usare AJAX");
}
}
function execfunc(method,url,bool){
myReq.onreadystatechange = handleResponse;
myReq.open(method,url,bool);
myReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
myReq.send(stringa);
}
function InviaDati(){
PreparaDati();
AJAXReq("POST","sendlike.php",true);
}
function handleResponse(){
if(myReq.readyState == 4){
if(myReq.status == 200){
alert(myReq.responseText);
}else{
alert("Niente da fare, AJAX non funziona :(");
}
}
}
</script>
Ringrazio anticipatamente.
ciao