简体   繁体   中英

using AJAX query to pass javascript array to php

After reading through quite a few posts here, (and even just straight copying code,) I still cannot figure out why this is not working.

On my main page, I have a textbox that a user pastes data into. Upon paste, this script runs (this and the ajax query below are in the same script function):

var lines = $('textarea').val().split('\n');  //create array from pasted data

I now have a JavaScript array with the pasted data. I'm trying to send this over to a separate PHP file that I will load into a div on this main page by doing the following:

$.ajax({
      type: 'POST',
      url: 'return.php',
      data: {lines:lines},        
        success:function(data){
          $("#info").load("return.php");
        }
  });

  for (i=0; i < lines.length; i++) {            // log the output
    if (lines[i]){
    console.log("line ",  i , lines[i]);
    }  
  }

In my return.php file, I have this:

$lines = $_REQUEST['lines'];

echo '<pre>';
echo($lines);
echo '</pre>';

My console.log is outputting the array perfectly, but for some reason it is not making its way over to return.php, as my echo is blank.

What am I doing wrong?

The response I get from return.php is:

 <pre>testArrayArray
(
    [0] => DL4004-13-F
    [1] => S1G-13-F
    [2] => ZXMP3A13FTA
    [3] => B260A-13-F
    [4] => S1J-13-F
    [5] => S3B-13-F
    [6] => SSN1N45BTA
    [7] => GBJ1010-F
    [8] => BPW20RF
    [9] => T3035H-6I
    [10] => ZXMP7A17KTC
    [11] => 
)
</pre>

The success handler on your ajax request is calling return.php with nothing and loading it into #info.

Change success to instead do:

$("#info").html(data)

The $lines variable in your PHP code is an array, not a string. If you have the errors turned on, PHP should warn you that you're doing an "Array to string conversion" (at least it does for me using your code).

You can't echo an array like that, you have to iterate through the results somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM