0

I want to manipulate a PHParray in javascript. This is the code i'm using.

Array.php

<?php

$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler"; 


?>

fx_funciones.js

 /*Pre-sentences*/
 var js_array=new Array();

$.ajax({        
       type: "POST",
       url: "array.php",
       success: function(response) {
           js_array=response      
       }
    }); 

This is what I want to do but it's not working.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
Leo
  • 1,051
  • 2
  • 13
  • 33
  • Well, you're not doing anything with the array after you create it. Try adding `echo json_encode($sentido)` – DiMono Mar 05 '13 at 15:26
  • possible duplicate of [Get data from php array - AJAX - jQuery](http://stackoverflow.com/questions/6395720/get-data-from-php-array-ajax-jquery) – Anthony Grist Mar 05 '13 at 15:32

4 Answers4

0

Try this:

<?php

$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler"; 

echo json_encode($sentido);

And:

$.getJSON('array.php', function(sentido) {
    console.log(sentido);
});
sroes
  • 14,663
  • 1
  • 53
  • 72
0

You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:

var js_array=new Array();

$.ajax({        
   type: "POST",
   url: "array.php",
   success: function(response) {
       js_array=response      
   },
   dataType: 'json'
});
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

I think , the answer for above question is already addressed in below link. please check them out. Get data from php array - AJAX - jQuery

I hope it will help you

Community
  • 1
  • 1
Jeyakumar
  • 31
  • 5
  • If you think an existing question and its answers provide the answer for this question then you should flag the question as a duplicate. – Anthony Grist Mar 05 '13 at 15:29
0

Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.

On the server:

echo json_encode($sentido);

For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php

On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:

$.getJSON('address/to/your/php/file.php', function(sentidos) {

    alert(sentidos[0]);  // It will alert "ver"
    alert(sentidos[1]);  // It will alert "tocar"

});

It uses GET but this most probably what you need.

For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/

bgusach
  • 14,527
  • 14
  • 51
  • 68