How to Write PHP in AJAX

2019-06-14 12:21发布

问题:

I am trying to get my session in ajax.. for that i had written my code like this

BTLJ.ajax({
           type: "POST",
           url: btlOpt.BT_AJAX,
           data: datasubmit,
           success: function(html){
                //if html contain "Registration failed" is register fail
              BTLJ("#btl-register-in-process").hide();  
              if(html.indexOf('$error$')!= -1){
                  ...
                  ...
                  }
               }else{                  
                   BTLJ(".btl-formregistration").children("div").hide();
                   BTLJ("#btl-success").html(html); 
                   BTLJ("#btl-success").show(); 
                   alert(<?php session_start(); print_r($_SESSION); ?>);
                   setTimeout(function() { ); BTLJ(".kcregbox").show();},7000);
                  // BTLJ("#btl-success").hide();
               }
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ': Ajax request failed');
           }
        });

but ajax is not working if i write like that.. please help me in getting my session in ajax. thanks in advance.

回答1:

Your AJAX query in Joomla should be formatted as below.

           jQuery.post('index.php',{
                'option'        : 'com_componentname',
                'controller'    : 'controllername',
                'task'          : 'task_name',
                'format'        : 'raw',            
                'data'          :  data
            }).success(function(result) { 
                //if the request is success
            }).error(function() { 
                //if the request is fails
            });


回答2:

I'm using this format for ajax in joomla

$.ajax({
        type: 'GET',
        url: 'index.php', 
        data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
    dataType: 'json',
        async: true, // can be false also
        error: function(xhr, status, error) {
                console.log("AJAX ERROR in taskToggleSuceess: ")
                var err = eval("(" + xhr.responseText + ")");
                console.log(err.Message);
                },
        success: function(response){

                // on success do something
                // use response.valuname for server's data
                        }
                ,
        complete: function() {
            // stop waiting if necessary 
                 }                     
          });

In your component/controllers you should have a file yourcontroller.json.php which will process your call and return encoded json array will all the data you need in the client