jQuery调用php函数

I want to call a function in php using jquery or ajax.

Actually. i got it with ajax, but i need to use 2 buttons. (submit and button)

I need to upload a text file, and then call a php function. check it out.

index.php

JS:

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
 <SCRIPT type="text/javascript">
       $(function (){
          $('#filecsv').submit(function (){

        $('#contenidos').load('server.php');
           });
        });
       </SCRIPT>

FORM:

    <form action="index.php" id="filecsv"  method="post" enctype="multipart/form-data">
                      <input type="file" multiple="multiple" id="file" name="up_csv[]"/>
                      <input type="submit" id="crearcsv" value="Cargar" /><br />
                      </form>
                      <?php
                      global $archivocsv;
                         //tipos de archivos permitidos
                $extensionxml = array('csv','txt');
                //destino
                $rutaupcsv = './csv/';
                //multicargador de archivos
                $vt=0;
                for($i=0;$i<count($_FILES['up_csv']['size']);$i++){
                    for ($j=-1; $j<count($extensionxml); $j++) {
                        if (strripos($_FILES['up_csv']['name'][$i], $extensionxml[$j])!== false) {
                        $filename = $_FILES['up_csv']['name'][$i];
                        $destino = $rutaupcsv.$filename;
                        $archivocsv = basename($_FILES['up_csv']['name'][$i]);
                        if (file_exists($destino)){
                               $existe = $filename.' Ya Existe!';
                               $vt=1;
                        }
                         else
                         {
                          move_uploaded_file($_FILES['up_csv']['tmp_name'][$i],$destino);
                          $carga = $filename.' Carga correcta!';
                          $vt=1;
                         }  
                        break; 
                        }
                        $noexis = ' Archivo Incorrecto';
                        }
                        }
                        session_start(); # read up on session.auto_start
                        $_SESSION["var"] = $archivocsv;
                      ?>
                     <button id="csv">Crear</button><br />
                     <div id="contenidos">
                         <?php
                         if ($vt != 1){
                         echo $noexis;   
                         }
                         echo $carga;
                         echo $existe;
                         ?>
                     </div>

PHP-> server.php

    include_once($_SERVER["DOCUMENT_ROOT"].'/include/include.inc.php');

   require_once ('common.php');

   function check_session(){
     global $db;
     $objResponse = new xajaxResponse();
     if (!isset($_SESSION)){
       $objResponse->addRedirect("/logout.php");
      }else{
       $interval = TIMEOUT * 60 * 1000 + 1000;

    $objResponse->addScript("setTimeout('xajax_check_session()',$interval);");
         }
          return $objResponse->getXML();
        }
     $xajax->processRequests();

     ##### PHP FUNCTION. Parser CSV to XML
       session_start();

      $filename = $_SESSION["var"];
      $filepath = './csv/'.$filename;

    function csv_in_array($csv) {

   $doc = new DOMDocument();

   $row = 1;
   $handle = fopen($csv, "r");
   # Rows Counter
  $csvxrow = file($csv);
  $csvxrow[0] = chop($csvxrow[0]);
    $anzdata = count($csvxrow);    
         $xml2 = $xml;
         $xmlruta = './Templates/';
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   $num = count($data);
   $row++;
         $xml = $xmlruta.$data[1].'.xml';
         $doc->load($xml);  
         $xp = new DOMXPath($doc);
         $xmlcount = 0;
         if (file_exists($filename)) {
     for ($c=0; $c < $num; $c++) {

           foreach($xp->query('/ROOT/HEADER/@KEY[. != ""]') as $attrib)
           {
            $attrib->nodeValue = $data[0];
           }
           foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/@AUFNR[. != ""]') as $attrib)
           {
            $attrib->nodeValue = $data[0];
           }
           foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/@MATNR[. != ""]') as $attrib)
           {
            $attrib->nodeValue = $data[1];
           }
           foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/@GAMNG[. != ""]') as $attrib)
           {
            $attrib->nodeValue = $data[2];
           }
           foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1AFFLL/E1FVOL/@MGVRG[. != ""]') as $attrib)
           {
             $attrib->nodeValue = $data[2];
           }
           foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/@GSTRS[. != ""]') as $attrib)
           {
            $attrib->nodeValue = $data[3];
           }
           foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/@GLTRS[. != ""]') as $attrib)
           {
             $fecha = new DateTime($data[3]);
              $fecha->add(new DateInterval('P1M'));
             $attrib->nodeValue = $fecha->format('Y-m-d');
           }
        }
           $name = $data[0] .'-'. $data[1];
           $doc->formatOutput = true;
      echo $doc->saveXML();
           $ruta = './XML/';
           $doc->save($ruta.$name.'.xml');
           $xmlcount++;
         }else{
             $restantes = $anzdata - $xmlcount;
             echo $xmlcount.' XML Creados'.' de '.$anzdata.'<br />';
             echo 'El Template '.$data[1].'.xml'.' No existe' .'<br />';
             echo $restantes . 'Restantes';
             return 0;
         }

     }

       fclose($handle);

       echo $anzdata . " XML Creados" . "<br />";  
      return $doc->saveXML();
     }
    $csvdata = csv_in_array($filepath);

 ?>

I just want to keep submit buton. Is it possible, to keep to do both things ? upload file then call function ?

use $.ajax and then have the done for the file submission and then after it comes back saying ok you can continue.

or is there something else that the button needed to do.

anything you have want to activate you can do it by tagging the ID via jquery $('#unique_id'). or class $('.unique_class).

and doing the button/submit depending on which is pressed.

If you want to submit and then go fetch data.

$('#filecsv').on('click', function (){
 $.ajax({
   type: 'POST',
   data: {//serialize your form variable}
   url: "server.php",//

   // ...
 }).done(function( msg ) {
      //load your div here from submitted data
  });;
});

I can add to this answer later, but quickly.

You can make a jquery click trigger a ajax call to pass the data that you need to the php function, then take the result of the function and make it into json. Then send it back. This would keep your javascript/jquery and php separate.

JAVASCRIPT

ex:

    var operator_information = {INFO TO PASS - ex: username:text1}
// the php will take the _POST['username'] as the javascript variable value of text1
            $.ajax({
                    type: "POST",
                    url: 'phppage.php',
                    cache: true,
                    data: operator_information,
                    dataType: "json",
                    success: function(data) {
                                var result = data;
                                console.log(result.test);
                            },
                    error: function() {alert('Error');},
                    complete: function(){
                    }
                });

phppage.php

<?php

$username = $_POST['text1']; $data = array();

function hello($username){
   ...
    $data[test] = $username; }

$data_push = json_encode($data);

echo $data_push;

?>

This would console.log the value of the function - you can do whatever you want at that point by using javascript or jquery.