1

I'm using this ajax to pass an array of strings to another page.

This is the array on nomes.php

[ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio',]

This is the code, the alert doesn't work - can anyone help?

$.ajax({
 type: 'post',
 url: 'nomes.php',
 beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType("application/j-son;charset=UTF-8");
  }
 },
 dataType: "json",
 success: function(data){
    v=data;
    alert(v);
 }
});
mvw
  • 5,075
  • 1
  • 28
  • 34
Ana Brandão
  • 21
  • 1
  • 4
  • 2
    you aren't even passing any data into the ajax request. Where is your array of strings? Maybe i'm misunderstanding what you're trying to do. Are you trying to *retrieve* an array of strings rather than *pass* an array of strings? – Kevin B Sep 03 '13 at 15:36
  • Why are you doing `overrideMimeType`? – gen_Eric Sep 03 '13 at 15:39
  • The array you show isn't valid JSON. – gen_Eric Sep 03 '13 at 18:52

3 Answers3

1

You need to encode the PHP-array to a JSON-array.

<?php
    echo (json_encode($myPhpArray));
?>
Oskar Persson
  • 6,605
  • 15
  • 63
  • 124
0

You can serialize the array into JSON using stringify to pass them through. Add this to your Ajax call:

data: JSON.stringify(arr);

Replace arr with your JavaScript array. This needs a plugin though. Have a look at this answer for more info.

Alternatively, if your array is in PHP, not in JavaScript you can echo it out directly like this:

data: <?php echo json_encode($arr) ?>,
Community
  • 1
  • 1
Styphon
  • 10,304
  • 9
  • 52
  • 86
0

If you're trying to pass the json to the server, you can do it like :

var strArray = ['str1', 'str2', 'str3'];
$.ajax({
 type: 'post',
 url: 'nomes.php',
 data: {strarray: strArray},
 dataType: "json",
 success: function(data){
    v=data;
    alert(v);
 }
});

If you're trying to receive it, you need to set the header on php side :

header('content-type: application/json');
echo json_encode(array('str1', 'str2', 'str3'));
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • If you're not actually sending JSON, then you don't need `application/j-son` (which should actually be `application/json`) in the AJAX *request*. – gen_Eric Sep 03 '13 at 15:41
  • I copied his code, didn't even see that part, the coffee didn't kick in yet. – OneOfOne Sep 03 '13 at 15:45