how to call a php function through ajax?

Asked

Viewed 1,895 times

0

how can I call my function PHP for ajax when a click occurs on mine span? I’m not able to call the function properly someone could help me?

code HTML

<span  id="link" class="dropdown-toggle icone">
    <i class="icon-logout"></i>
</span>

code PHP

function logout($sessao){
        if($sessao == $_SESSION['logado']){
            unset($sessao);
            session_destroy();

        }else if($sessao == $_SESSION['logadoCliente']){
            unset($sessao);
            session_destroy();

        }
    }

code Ajax

$("#link").click(function(){
                $.ajax("functions/logout.php",{

                }).done(function(){

                }).fail(function(){

                });
            }); 
  • This url "functions/logout.php" is correct ?

  • yes this correct

  • So what’s the problem? Have you tried putting one alert in .done or .fail to see if the request was able to access the file.

  • Put the whole PHP code. Or this is the whole code. Why if it is, this is the problem.

  • this and the whole code. that’s a function I want to call the function logout that this in functions/logout.php when I click on the span with the id click

  • First of all you are not calling the function anywhere in the PHP code. Nothing differs a PHP code that runs when it is invoked via browser from a code invoked via AJAX. Therefore, setting a function and never calling it will make it never run. Second, the function is requesting a parameter $sessao, which is not being provided by the request and not defined in the code.

  • and hence my question comes where I will call this function with the ajax so I asked the question

  • Let’s go by parts. What is $Session? is the user id? you have it in Javascript?

  • Where will this $Session parameter come from? It looks like a logout, will need an ajax to make a simple logout?

Show 4 more comments

3 answers

2


how to call a php function through ajax?

Answer: The ajax does not call the function itself, it just makes the request for the script logout.php. The script PHP is that it should instantiate the function itself and return a response:

logout.php:

if(isset($_GET['session'])){$sessao = $_GET['session'];} else{$sessao = '';}

function logout($sessao){
  if($sessao == $_SESSION['logado']){
   unset($sessao);
   session_destroy();
  }
  else if($sessao == $_SESSION['logadoCliente']){
   unset($sessao);
   session_destroy();
  }
}
//The cat's leap: Chame a função aqui mesmo:
logout($sessao);

Obs: I’m guessing the value of this $session must be sent by the request ajax, then:

$(function () {
    $("#link").click(function(){
        $.ajax({
            url:"assets/teste.php",
            type:'get',
            data: {
                'session':'Valor da session'
            }
        }).done(function(resp){
            $( "#link" ).append( resp );
        }).fail(function(){
            $( "#link" ).append( 'Requisição falhou!' );
        });
    });
});

0

You click on span and nothing happens? That’s it?

If that’s the case, try it this way:

$('body').on('click', '#link', function () {

   $.ajax("functions/logout.php",{

            }).done(function(){

            }).fail(function(){

            });

});

Your code PHP may be so (I did not understand right the existence of the function...)

if(isset($_SESSION['logado'])){

            unset($_SESSION['logado']);
            session_destroy();

        } else if (isset($_SESSION['logadoCliente'])){

            unset($_SESSION['logadoCliente']);
            session_destroy();

        }

This if you want to logout with ajax.

0

If you’re like me, I mean, don’t like jQuery and don’t even use it if I pay you, here’s another way:

<script type="text/javascript" charset="utf-8">
function ajaxObj(meth, url) {
var x;
try {x=new XMLHttpRequest();}
catch(e) {var XmlHttpVersions=new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");for (var i=0; i<XmlHttpVersions.length && !x; i++){try { x=new ActiveXObject(XmlHttpVersions[i]);} catch (e){}}
};
if (!x){displayError("Erro ao criar o objeto XMLHttpRequest.");} else {x.open(meth, url, true);x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); x.setRequestHeader("Cache-Control", "no-cache");x.setRequestHeader("Pragma", "no-cache");x.setRequestHeader("X-Requested-With", "XMLHttpRequest");return x;}};
function ajaxReturn(x){if(x.readyState==4 && x.status==200){return true;}
}
</script>
<script type="text/javascript" charset="utf-8">
function _(x){ return document.getElementById(x);}
</script>

<script type="text/javascript" charset="utf-8">
function pc(oquepost,pagesc){
if(typeof(oquepost) !== 'undefined'){
var name = oquepost;
}else{
var div1 = document.getElementById('artigo');
var name = div1.getAttribute("data-postid");
};
if(typeof(pagesc) !== 'undefined'){var pagec = pagesc;} else {var pagec = null;};

var vars = 'procuraralgo='+name+'&pagina='+pagec;
var url = "arquivo_procurador.php";
var ajax = ajaxObj("POST",url,true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var return_data = ajax.responseText;
_("artigo").innerHTML = return_data;}
};
ajax.send(vars);
_("artigo").innerHTML = "A processar os dados...";
}
</script>

I hope it helps!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.