0

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 ?

2
  • You seem to have forgotten to ask a question Commented Mar 13, 2014 at 21:57
  • I want use only a button, (input submit). to do both things... upload file and call function. Commented Mar 13, 2014 at 22:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to use your example... I'm starting using jquery-Ajax, though. It's seems like I want, I just want to call the php function and show the result in a -<div>- Thank you.
0

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
  });;
});

5 Comments

I'd like to do the first option... Submit the file and then call function ans show the result in <div></div>.
@ezos yup - successs or done will enable him to reload to the div
Sry for my (stupids) questions... I'm starting in jquery. Should i need set something in data: {} ?
yes data: { } is for the variables that will end up as $_POST[''] on the other side. so data: {var1 : $('#some_id').val()} will end up in the php as $_POST['var1']. When i said serialize basically there is a short way to get all the variables inside a form in one shot - look it up with some examples it should give you an idea.
Ok. i'll check examples. but actually i just need to send the name of the file uploaded. ('text.csv'), so... Do i need to use... data:{varcsv: $('#file').val()}, and in server.php $_POST['varcsv']; right ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.