-2

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.

So i have an array in Javascript which I'm trying to pass on to PHP.

I've got a little JS function to first POST it, so:

function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}

Then down the page, I have the PHP:

<?php 
    $myval = $_POST['variable'];
    print_r ($myval);
    ?>

*The prints just there for me to check.

Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?

Thanks.

Phil
  • 157,677
  • 23
  • 242
  • 245
Sae Us
  • 277
  • 1
  • 6
  • 21
  • 1
    what does the print_r output? – Jonathan Kuhn Apr 24 '13 at 00:16
  • You aren't doing anything with the results of the AJAX post so I don't know why you would expect to see anything – Phil Apr 24 '13 at 00:18
  • 1
    Actually I just realized, are you sending the data through ajax to the same page you are on? ajax doesn't work like that. You would usually send the ajax data to another page and add a 3rd argument to $.post, a callback function, that gets called when the ajax call is done and gets passed in the output from the ajax call. Inside that callback is where you would update the screen. – Jonathan Kuhn Apr 24 '13 at 00:19
  • The output gives nothing. So with the AJAX post what needs to be done - I assumed its just handed over? – Sae Us Apr 24 '13 at 00:19
  • Try $.post({url:"index.php", data:{ "variable": toSearchArray }}); – Ramesh Apr 24 '13 at 00:28
  • @Ramesh That doesn't match the [`$.post`](http://api.jquery.com/jQuery.post/) API at all – Phil Apr 24 '13 at 00:33
  • Refer this http://stackoverflow.com/questions/8890524/pass-array-to-ajax-request-in-ajax – Ramesh Apr 24 '13 at 00:36

4 Answers4

3

You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:

index.php

<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //attach to the button a click event
    $('#btn').click(function(){
            //get the value from the textbox
        var txt=$('#txt').val();
            //if txt is blank, alert an error
        if(txt == ''){
            alert("Enter some text");
        } else {
                    //send txt to the server
                    //notice the function at the end. this gets called after the data has been sent
            $.post('catcher.php', {'text':txt}, function(data){
                            //now data is an object, so put the message in the div
                $('#response').text(data.message);
            }, 'json');
        }
    });
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;">&nbsp;</pre>
</body>
</html>

catcher.php:

<?php
//if something was posted
if(!empty($_POST)){
    //start an output var
    $output = array();

    //do any processing here.
    $output['message'] = "Success!";

    //send the output back to the client
    echo json_encode($output);
}

It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
  • Hi - Ok i see this working however as I have 2 files - I how do i get it back to the array value to teh original i.e. index.php - shall i just use sessions? – Sae Us Apr 24 '13 at 10:53
  • it is already an array in index.php. However if you want a response from the server (file 2, catcher.php) to be an array, you can specify a data type in your post, most likely 'json', as the fourth argument. Then anything sent from the second file you can just run through json_encode in php and the callback function will get that. I'll update the example to show this. – Jonathan Kuhn Apr 24 '13 at 14:55
0

This is what happens when you open your page (index.php)

  1. A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
  2. Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.

Hopefully this will illustrate what you can do.

ajax.php

<?php
header("content-type: application/json");
exit(json_encode($_POST));

index.php

<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
  variable: toSearchArray
}).done(data => {
  console.log(data) // here you will see the result of the ajax.php script
})
</script>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Hi - Ok i see this working however as I have 2 files - I how do i get it back to the array value to teh original i.e. index.php - shall i just use sessions? – Sae Us Apr 24 '13 at 11:12
0

Instead of declaring variable toSearchArray as array. consider it an javascript object. var toSearchArray = {}.

-1

Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php Refer to this question Pass Javascript Array -> PHP

Community
  • 1
  • 1
engma
  • 1,849
  • 2
  • 26
  • 55
  • 3
    In jquery, you can pass an object and jquery will serialize it to a valid post payload. http://api.jquery.com/jQuery.post/ – Jonathan Kuhn Apr 24 '13 at 00:22
  • I'm sooo lost. Literally no idea why what I have is not working What do i need to read up? All I want to do is send a javascript array to PHP – Sae Us Apr 24 '13 at 00:29