Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current Entry from Array in Javascript

I'm a newbie so be kind :) In Javascript, how do I add to a variable the current entry from an array? See my code below.

    <?php
        $array = mysql_query(SELECT column1 FROM table1 WHERE column2='$entry'); 
                                           //this returns several entries

        <script>
            var array=<?=json_encode($array)?>;   // the      
            var data={mouse:mickey, rabbit:roger};
                $.each(array, function(){
                        $.post('dostuff.php',data+','+{array[this]}); // <-- not sure
                        });
        </script>
    ?>

My question is about the data sent in the "post" jquery command. how do I add the current database entry and send it as part of the data sent in the ajax request. I wrote it roughly, but I'm confident it isn't right the way I wrote it here.

Thanks!

like image 894
Lucy Weatherford Avatar asked Mar 17 '26 14:03

Lucy Weatherford


1 Answers

How do I fetch the data from MySQL?

mysql_query returns a handle to be used to actually fetch the result (kind of like a file handle when reading files).

You should use mysql_fetch_array which will give you a row from the result set, or false when you have reached the end.

Remember that the returned array from mysql_fetch_array will contain values with a number as key, as well as the field name as a key, you are probably only interested in the latter; then you should use mysql_fetch_assoc:

// please remember to sanitize $entry before using it in a SQL query.
$result = mysql_query ("SELECT column1 FROM table1 WHERE column2='$entry'");

$query_data = array ();

while (($row = mysql_fetch_assoc ($result)) !== false) {
  $query_data[] = $row;
}

...

<script>
  var array = <?=json_encode ($query_data);?>;

...

I read your post again, if you are only interested in the value of a single row and a single column then you should use mysql_fetch_field (pass it your $result from mysql_query).

That function will return the value in the first column (in your case field1).

Wrap this value in an array and use json_encode before giving it to your javascript.


Documentation

  • PHP: mysql_query - Manual
  • PHP: mysql_fetch_assoc - Manual
  • PHP: mysql_fetch_field - Manual

How do I iterate over the array in javascript?

The callback sent to jQuery.each can optionally take two parameters.

  1. the index of the current entry
  2. the value of the current entry

With this knowledge you could write your function as:

$.each(array, function(idx, value){
  $.post('dostuff.php',[data, value]); 
});

// or.. (depending on what you wanna do)

var post_data = $.extend ({}, data, {array_data: array});

$.post ('dostuff.php', post_data);
like image 72
Filip Roséen - refp Avatar answered Mar 19 '26 03:03

Filip Roséen - refp