JQuery - auto-mate/CheatSheetWiki GitHub Wiki

JQuery

Ajax Send Arrays
Ajax Send File
Elements (Get)
$.post
$.post No Async

$.post

A function to Get Data [e.g an HTML table] from a php file that requires POST inputs f0 f1 etc...
The data is posted to "dataSourceFile.php" with $.post().

function updateFromLookup(inputIDs,outputID,dataSourceFile) {

 //where  inputIDs 		as an array e.g ['a','b','c'] or z where z=[1,2,3] etc 
 //       outputID 		as ID of Output Tag as Str,
 //       dataSourceFile 	as the filename of the php file to return data from
 // NB	 
 // Field Names for $_POST[''] are $_POST['f0'],$_POST['f1']..... 

     //Build Post Data in the correct format  
     //=====================================  	 	
     $postData={};		
     for (i=0;i<inputIDs.length;i++)	{  
       $postData["f"+i]=  $("#" + inputIDs[i]).val();  
     }	 	 	  
 
     $postFile=dataSourceFile;  

     // returned data [e.g. HTML Table] is returned to the Tag with the "outputID" and its HTML replaced with the returned "Data"  
     // =========================================================================================================================  
     $.post($postFile,$postData,  
        function(data, status){  
          $("#" + outputID).html(data);  
        });  

}  

$.post No Async

$.ajax({type: 'POST',  
         url: 'address\file.php',   
        data: {PostName2:PostVariable1, PostName2:PostVariable2},   
    dataType: 'text',    
  beforeSend: function() {$('#spinner').show();},  
     success: function(data) {  
                  $('#someDiv').innerHTML=data;  
                  $('#spinner').hide();  
              }  
       async: false  
});  

Ajax Send Arrays

// ## create arrays
p = new Array();  // year period
f = new Array();  // field name
v = new Array();  // value

// ## Add data to arrays
// Loop Rows and Columns For Diffs in cell innerText and Title to find values to update
for ( r = 1; r < rowCount; r++ ) {
  for ( c = 1; c < colCount; c++ ) {
    if  ( tbl.rows[r].cells[c].innerText != tbl.rows[r].cells[c].title )  {
      
    p.push(tbl.rows[r].cells[0].innerText); // period in cell/col 0
    f.push(tbl.rows[0].cells[c].innerText); // field name in row 0
    v.push(tbl.rows[r].cells[c].innerText); // new value in innerText of current cell 
    
    }
  }
}

// ## create object to name and contain the arrays
dataIn = {'per':p,'fld':f,'val':v};

// ## add this object as the "data" parameter and send
$.ajax({
  type: 'POST',
  url: 'https://......php',
  data: dataIn ,
  dataType: 'text',
  success: function(data, status){  
        $("#someID")[0].innerText = " " + data; // output the text returned from the success  
        updateTitleFrminTxt();                  // run some code to align title and innerText now they are updated
      },
  error:function(data, status){  
        $("#someID")[0].innerText =' Failed To update!';  
      }          
  });

}

/*

## To Recieve in PHP

  if ( isset($_POST['per']) && isset($_POST['fld']) && isset($_POST['val']) ) {
    
    $p = $_POST["per"];
    $f = $_POST["fld"];
    $v = $_POST["val"];

    $sql = "";

    for ( $n = 0; $n < sizeof( $p ); $n++ ) {    
      $sql .= "UPDATE [SomeTable] SET [" . $f[$n] .  "] = " . $v[$n] . " WHERE [Period] = '" . $p[$n] . "'\n";      
    }

    // add code to process $sql string

    */

Elements Get

By tag                 $("div")[0] 
By id                  $("#some-id")[0]
By class               $(".class-name")[0]
By atrribute           $("[data-toggle=wy-nav-shift]")[0]
By tag and atrribute   $("div [data-toggle=wy-nav-shift]")[0]

Ajax Send File

Use an input element with type = file

 /*
 In Html
 <input type="file" style="width:80%;" id="fileSelector">
 */

    // Create a form data object
    // -------------------------
    fd = new FormData();
    // Add the file from our element
    // -----------------------------
    fd.append( "file", document.getElementById("fileSelector").files[0] );
    // Add additional data if required (2 more items added here)
    // ----------------------------------------------------------
    fd.append( "someOtherData1", document.getElementById("someOtherData1").value.trim() );
    fd.append( "someOtherData2", document.getElementById("someOtherData2").value.trim() );
    // Post the data to TBC.php
    // -------------------------
    $.ajax({ 
        url:"TBC.php", 
        type: 'post', 
        contentType: false, 
        processData: false, 
        data:fd });

/*
//Example of Handling in php
// -------------------------
<?php

$fileName= $_POST['someOtherData1'] . $_POST['someOtherData1'];

$dir  = __DIR__ ;
$to   = $dir . "\\OurDownloadDirectory\\" . $fileName ;
$from = $_FILES['file']['tmp_name'];

move_uploaded_file( $from, $to );

?>

*/