1

Please read the description before marking it as duplicate.

As far as I know, the way to pass data from JavaScript to PHP is through Ajax Call.

My scenario is like this:

  1. Using PHP,I echo an HTML page which has JavaScript.

    <?php        
    $out .= '    
    <h3>Upload New Primary Studies</h3>    
    <div>    
    <p> Please select the primary studies which you want to upload:</p>    
    <table>    
    <form id="file-form" action="" method="POST">
    <Tr><input type="file" id="file-select" name="userFile" multiple/>                 
    <button type="submit" id="upload-button"">Upload</button>                 
    </Tr>               
    </form>      
    </table>        
    </div>
    
    <h3>View / Edit Primary Studies</h3>
    <div id="grid1"></div>
    <script>
    
    var form = document.getElementById("file-form");
    var fileSelect = document.getElementById("file-select");
    var uploadButton = document.getElementById("upload-button");
    var today = new Date();
    var idValue = 1;      
    var jsonData = {
    
        header: []
    
    };
    
    var data1;
    
    form.onsubmit = function(event) {
      event.preventDefault();
    
    // Update button text.
    uploadButton.innerHTML = "Uploading...";
    
    
    // Get the selected files from the input.
    var files = fileSelect.files;
    var file1 = files[0];
    
    var i = 1;
    var reader = new FileReader();
    reader.readAsText(file1);
    reader.onload = function(event){
        var csv = event.target.result;
        var data = $.csv.toArrays(csv);
        for(var row in data) {
            if ( row == 0)
                continue;
            else
            {
                jsonData.header.push({
    
                    "ID" : idValue,
                    "RefID" : 1,
                    "RefType" : data[row][0],
                    "recordDate" : new Date().toJSON().slice(0,10),
                    "PrimaryAuthors" : data[row][1],
                    "PrimaryTitle" : data[row][2],
                    "FullPeriodical" : data[row][3],
                    "PeriodicalAbbrev" : data[row][4],
                    "PubYear" : data[row][5],
                    "PubDate" : data[row][6],
                    "Volume" : data[row][7],
                    "Issue" : data[row][8],
                    "StartPage" : data[row][9],
                    "OtherPage" : data[row][10],
                    "Keywords" : data[row][11],
                    "Abstract" : data[row][12],
                    "Notes" : data[row][13],
                    "PersonalNotes" : data[row][14],
                    "SecondaryAuthors" : data[row][15],
                    "SecondaryTitle" : data[row][16],
                    "Edition" : data[row][17],
                    "Publisher" : data[row][18],
                    "PlacePub" : data[row][19],
                    "TertiaryAuthors" : data[row][20],
                    "QuaternaryAuthors" : data[row][21],
                    "QuinaryAuthors" : data[row][22],
                    "TertiaryTitle" : data[row][23],
                    "ISSN" : data[row][24],
                    "Availability" : data[row][25],
                    "Address" : data[row][26],
                    "AccNumber" : data[row][27],
                    "Language" : data[row][28],
                    "Classification" : data[row][29],
                    "SubFile" : data[row][30],
                    "OrgForiegnTitle" : data[row][31],
                    "url" : data[row][32],
                    "DOI" : data[row][33],
                    "CallNumber" : data[row][34],
                    "Database" : data[row][35],
                    "DataSource" : data[row][36],
                    "IdentPhrase" : data[row][37],
                    "RetDate" : data[row][38]
                });
                idValue++;
            }
        }
            data1 = jsonData;
            //alert(JSON.stringify(data1));
            $("#grid1").igGrid("dataSourceObject", data1);
            $("#grid1").igGrid("dataBind");
    
        }
    
    
        uploadButton.innerHTML = "Upload Complete";
    }
    
    // Call the grid with JSON Data
    $( document ).ready(grid1());
    var request;
    function createDBRows()
    {
        var r = confirm("Do you want to create records in the database");
    
        var url = "/_application/model/dataAccess/insertStudies.php?json=";
        if (r == true) {
    
            alert("You pressed OK!");
            // Get the database of the Grid
            var dbSource = $("#grid1").igGrid().data().igGrid.dataSourceObject();
    
    
    
        } else {
           alert("You pressed Cancel!");
        }
    }
    </script>
    <br>
    <br>
    
    <div>
    
    <button type="submit" id="upload-button"" onclick="createDBRows()">Create  Database Rows</button>
    
    <button type="clear" id="clear-button"">Clear</button>    
    <button type="cancel" id="cancel-button"">Cancel</button>
    </div>
    ';
    
  2. Steps for this application are:

    1. Upload a CSV file.
    2. Data from CSV file is displayed in an iggrid.
    3. user modifies the data & saves it on the grid.
    4. Once user is done with modification, user clicks on create DB rows button
    5. on Click of above button, the data source should pass to another PHP page: insertStudies.php

My Problem:

I am stuck at point 2.e as I am not able to create an ajax call and send the data to the php page. Can anyone point to a source or give an example which can explain a way to pass data using javascript with an PHP page to another PHP page.

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
CalmWinds
  • 157
  • 1
  • 3
  • 13

2 Answers2

1

Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)

<script type="text/javascript">
    function sendJSValsToPHP(){
        var xmlhttp;

        //These are the variables i am going to post to illustrate the example, what you want
        var var_1toPost = 1;
        var var_2toPost = 2;
        var var_3toPost = 3;

        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                //You can get the response text from abc.php file and process it in any of the tags you want by javascript code
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;              
            }
        }
        xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
        xmlhttp.send();
    }
</script>

The echo'ed data in abc.php will come in the div="myDiv" //as a response.

<body>
    <div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
        the things echo'ed in abc.php will come in this div
    </div>
    <button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>

and then in abc.php //file

<?php
    $recieved_1 = $_GET['recieve_1'];
    $recieved_2 = $_GET['recieve_2'];
    $recieved_3 = $_GET['recieve_3'];

    //Do your processing here and insert it in the database
        //Insert Query OR Update Query (whatever)
    // after you have inserted you can get the response in
    // the <div> having id="myDiv" Or whatever you want
    // Suppose you have successfully inserted data then 
    $insertedDataBoolean = true;
    if($insertedDataBoolean){
        echo "Data: " . $recieved_1 . ", " . $recieved_2 . 
        " and " . $recieved_3 . " inserted successfully.";
    }
    else{
        echo "Data-insertion error.";
    }
?>
Asif Mehmood
  • 964
  • 2
  • 14
  • 35
0

What you are asking for is an Ajax Post method.

You can either send your data to the php page via json array or form serialize.

The function returns the data "echoed" from the php page into the tag with a class of result

$.post("path/yourPhpPage.php",{key: 'value'}, function( data ) {
  $( ".result" ).html( data );
});
Demodave
  • 6,242
  • 6
  • 43
  • 58
  • thank your response. I had tried the above method before but it does not work. When I try to use a similar line of code in my program, it does not accept $.post as valid because I am already using PHP and echoing out html + javascript code. – CalmWinds Mar 31 '15 at 17:46
  • Using php has no interference with javascript since php is server-side and javascript is client side. The only issue you may face is getting the single/double quotes wrong. – Demodave Apr 01 '15 at 13:57
  • Also the $post method has to sit inside the ready https://api.jquery.com/ready/ – Demodave Apr 01 '15 at 14:06