Link to home
Start Free TrialLog in
Avatar of sia ram
sia ram

asked on

how to pass dynamically data from java script to php using ajax

<script type="text/javascript">
 
var httpBuildQuery = function(params) {

    if (typeof params === 'undefined' || typeof params !== 'object') {
        params = {};
        return params;
    }

    var query = '?';
    //var index = '';
    var index = <?php echo json_encode($array3); ?>;

    
      for (var i in index) {
        //index++;
        //var param = index[i];
        var value = params[i];
        if (index == 1) {
            query += value + '=' +  value +'.value';
        } 
        else {

            query += '&' + value + '=' +  value +'.value';
        }

    }
    return query;
};


var build = document.getElementById('submit');
var output = document.getElementById('output');

build.onclick = function() {
 
 var parameters = <?php echo json_encode($array2); ?>;
    
  var $query = httpBuildQuery(parameters);
    //output.firstChild.nodeValue = $query;
    alert($query);
   var $z=document.getElementById("output").innerHTML = $query;
 
   
   //var $my_variable = "something";
$("#build").click(function() {
   
$.ajax({
     url: 'insert_value.php',
     data: {x: $query},
     type: 'POST'

});
});

};
</script>

Open in new window



here I'm uploaded my code here i'm generating controls dynamically and trying to insert those controls values into some table so I have to pass the values from javascript to php

in javascript i'm creating query string but it is like ?gender=gender.value&name=name.value so instead of printing like it should take directly values like ?gender=Male&name=sai like this

so plaease anyone help me to solve my problem



here is my design code
while ($row = $res->fetch_object())
{
    //$html =$html.' 
  echo'
<tr>
  <td>
    <div class="row-fluid">

      <div class="span3 bgcolor">
     <label>'.$row->Alias_name.'</label>


        <select  id='.$row->source_table.' name='.$row->source_table.' data-live-search="true" class="selectpicker form-control">';

  /*foreach ( $Data->{$row->source_table} as $key =>$item) {
    echo "<option value=".$key.">".$item."</option>" ;
  }*/
   foreach ( $Data->{$row->source_table} as $key =>$item)  {
    echo "<option value=".$key.">".$item."</option>";
  }
echo '         
          </select> 
                                          </div>
      </div>
  </td>
</tr>';
}
}
else
{
   
   //$html =$html.' 
  echo '
<tr>
  <td>
   <div class="row-fluid">
               
            <div class="span3 bgcolor">
            <label>'.$row.'</label>
                 <input id='.$row.' type="text" placeholder=" Enter Value " name='.$row.' style="width:100%" class="form-control" />
                              
                </select> 
</div>
</div>
  </td>
</tr>';

}

}
echo'<input  id="submit" type="submit" value="SUBMIT" class="btn btn-success"  name="submit" onclick="myFunction()"/> </form>';

Open in new window

Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Can you post a sample of the data array that you want to post?Specially the   <?php echo json_encode($array3); ?>   and   <?php echo json_encode($array2); ?>
Avatar of sia ram
sia ram

ASKER

the query string will generate like this  ?gender=gender.value&name=name.value&city=city.value&address=address.value so instead if this it should take actual values what we will give in controls  so the query string should be for eg:?gender=Male&name=sss&city=dwd&address=xxx
ASKER CERTIFIED SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sia ram

ASKER

Here its giving some notice and warnings
Can you post the HTML form that you set inside the values witch you want to send at php page?
Avatar of sia ram

ASKER

<!DOCTYPE html>
<html>
<head>
   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>


<?php 
include("con_gen.php");

error_reporting(E_ALL);

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "idcard";
$db_user = "root";
$db_word = "";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

// RUN A QUERY
$result = mysqli_query($mysqli,"SELECT value FROM combo1");
$num_rows = mysqli_num_rows($result);

//echo "$num_rows Rows\n";
if ($result->num_rows > 0) {
     // output data of each row
  $array = Array();
  $array1 = Array();
     while($row = $result->fetch_assoc()) {
         //echo "<br> value: ". $row['value'].  "<br>";
          $array[] = $row['value'];
        
}
//print_r($array);

$sql = "SELECT static_name FROM static_values";
$result = mysqli_query($mysqli, $sql);
if ($result && mysqli_num_rows($result) > 0) 
 while($row = mysqli_fetch_array($result)){
                //echo "<option>" . $row['static_name'] . "</option>";
                $array1[]=$row['static_name'];
                 
                 //echo $source;
               }
              // print_r($array1);
               foreach ($array as $row)
{
  if(in_array($row, $array1))
  {
$sql = "SELECT source_table,Alias_name FROM static_values where static_name='$row'";
$res = $mysqli->query($sql);

// DID THE QUERY WORK OR FAIL?
if (!$res)
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}

// ARE THERE ANY ROWS IN THE RESULTS SET

if ($res->num_rows == 0)
{
    trigger_error("ERROR: NO DATA FOUND BY $sql", E_USER_ERROR);
}

// RETRIEVE THE ROWS INTO AN ARRAY OF HTML STATEMENTS
//$html = "";
echo '<form method="POST" action="">';

while ($row = $res->fetch_object())
{
    //$html =$html.' 
  echo'
<tr>
  <td>
    <div class="row-fluid">

      <div class="span3 bgcolor">
     <label>'.$row->Alias_name.'</label>


        <select  id='.$row->source_table.' name='.$row->source_table.' data-live-search="true" class="selectpicker form-control">';

  /*foreach ( $Data->{$row->source_table} as $key =>$item) {
    echo "<option value=".$key.">".$item."</option>" ;
  }*/
   foreach ( $Data->{$row->source_table} as $key =>$item)  {
    echo "<option value=".$key.">".$item."</option>";
  }
echo '         
          </select> 
                                          </div>
      </div>
  </td>
</tr>';
}
}
else
{
   
   //$html =$html.' 
  echo '
<tr>
  <td>
   <div class="row-fluid">
               
            <div class="span3 bgcolor">
            <label>'.$row.'</label>
                 <input id='.$row.' type="text" placeholder=" Enter Value " name='.$row.' style="width:100%" class="form-control" />
                              
                </select> 
</div>
</div>
  </td>
</tr>';

}

}
echo'<input  id="submit" type="submit" value="SUBMIT" class="btn btn-success"  name="submit" onclick="myFunction()"/> </form>';
echo '<p id="output">&nbsp;</p>';

}
$sql = "SELECT * FROM combo1";
$res = $mysqli->query($sql);

if ($res && mysqli_num_rows($res) > 0) 
 while($row = mysqli_fetch_array($res)){
                
                $array2[]=$row['value'];
                 $array3[]=$row['column'];
                 
               }
               $c=1;
               
                print_r($array[1]);

               ?>
               </body>
</html>

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
greetings  sia ram , , , I am having real difficulty trying to understand what you are trying to do in your code? ? You have a JAVASCRIPT VALUE STRING rendered from a PHP HTML write as -
         var index = <?php echo json_encode($array3); ?>;

? ? this may not work like you want it to ? ?
You do NOT tell us what the PHP variable  $array3  has in it, , I guess from the name, it is a PHP ARRAY? ?
This array may be just an array of strings with NUMBERS as the KEYS, OR a KEY Value string Array, OR an array of arrays, or an array of objects , or some mix of various things? Which will make a big difference in how the javascript will work.

Next you do some sort of code to get and use the "Values" in  $array3 which in javascript is now variable "index" -

   for (var j in index) {
        var value = params[j];
        if (index == 1) {
            query += value + '=' +  value +'.value';
        } else {
            query += '&' + value + '=' +  value +'.value';
        }
    }

the above code is incorrect in several ways, your ARRAY in javascript as "index" will never equal 1 as you test it -
        if (index == 1) {

also I do not understand what the params Variable is when you use -
        params[j]

I also do not know that the javascript variable you use as "value" comes from? ?
     query += value + '=' +  value +'.value';

Shouldn't a Query string with = and & in it, , ,  be a KEY-VALUE pair combination? ?

you seem to want a javascript object property with the
  .value
BUT you have that in a string with quotes -
    '.value'
which makes it a string, and this can NOT be used as an object property, in this way as a string addition.

 = = = = = = = =
also if you are trying to do an AJAX Form submission this code will not work -

$("#build").click(function() {
   
$.ajax({
     url: 'insert_value.php',
     data: {x: $query},
     type: 'POST'

});
});

because it Does NOT prevent the normal FORM submission to happen.

Can you tell use more about what you are trying to do with the PHP code write of   php echo json_encode($array2);     in this -
         var parameters = <?php echo json_encode($array2); ?>;
         var $query = httpBuildQuery(parameters);
This question has been inactive for more than 14 days and now must be Closed.
Points are split for experts possible solutions.