Link to home
Start Free TrialLog in
Avatar of DMTrump
DMTrumpFlag for United States of America

asked on

Best way to pass javascript array to a PHP page

Now that the need to pass just the first three chars of my list items has been solved, I need to pass the resulting array to a PHP page for processing on the server side.  And in the PHP I need to know how to properly receive the data into a well-formed PHP array.  So I need to replace the alert line below with the proper Ajax, I guess - but all my attempts have backfired!


 function submit(){
     var udxNewOrder = [];
     $("ul#sortable1 li").each(function() {
        var str = $(this).text().substring(0, 3);
        udxNewOrder.push(str);    
    });
    alert(udxNewOrder.join('\n'));
}
Avatar of Gary
Gary
Flag of Ireland image

  $.ajax({url:"yoursite.com/yourpage.php?yourvar="+udxNewOrder.join('\n')});

Open in new window

javascript:
$.ajax(
{
	type: 'post',
	url: 'script.php',
	data: {newOrder: udxNewOrder.join('\n')}
		})

Open in new window


In php:
$array = $_POST['newOrder'];
...

Open in new window

Avatar of DMTrump

ASKER

I have to write some more code in my php file to verify this but it looks like it will work.  I had tried <almost> that code but hadn't enclosed the data assignment in curly-brackets and the result kept killing my sortable list.
Avatar of DMTrump

ASKER

I realized I need to pass a second php variable to the php file - will this do it?  (It doesn't, at least blow up the sortable)

    var category = json_encode($peraccess);
    $.ajax(
    {
      type: 'post',
      url: 'neworder.php',
      data: {newOrder: udxNewOrder.join('\n'), cat: category }
    })

then in the php file:

$udxarray = $_POST['newOrder'];
$peraccess = $_POST['cat'];
Yes, it'll do it
Avatar of DMTrump

ASKER

There seems to be a problem with actually executing the php at the url
In the following, I'm calling a test php file that when called from the command line makes a modification to database table.  

function submit(){
     var udxNewOrder = [];
     $("ul#sortable1 li").each(function() {
        var str = $(this).text().substring(0, 3);
        udxNewOrder.push(str);    
    });
    var category = json_encode($peraccess);
    $.ajax(
    {
      type: 'post',
      url: 'noworder.php',
      data: {newOrder: udxNewOrder.join('\n'), cat: category }
    })

}      

But when called via this javascript, nothing happens which to me means that the call to noworder.php is not successful (much less passing any data)  Do you have any idea why this might be happening (not happening)
Maybe it's a stupid question: the script name has to be 'noworder.php' or 'neworder.php'?
Avatar of DMTrump

ASKER

The real php I need to call to process the array is neworder.php  but for test puroses I created noworder.php
that consists of the following:

<?php
$con = mysqli_connect("localhost","myuser","mypassword","mydatabase");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
 
$order = rand(100, 500);
$sql="UPDATE test SET rank = '".$order."' WHERE udx = 'v11'  ";
mysqli_query($con,$sql);
mysqli_close($con);

?>

So if this file is executed it just makes a random change to a table.
Avatar of DMTrump

ASKER

Here are my

jquery invocations in the page with the javascript
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>      
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Try the code below. I added some code to be sure if the call succeed or fails

function submit(){
     var udxNewOrder = [];
     $("ul#sortable1 li").each(function() {
        var str = $(this).text().substring(0, 3);
        udxNewOrder.push(str);    
    });
    var category = json_encode($peraccess);
    $.ajax(
    {
      type: 'post',
      url: 'noworder.php',
      data: {newOrder: udxNewOrder.join('\n'), cat: category }
    })
    .done(function(result) 
    {
	alert('Done');
    })
    .fail(function(result)
    {
        alert('failed');
    });
}     

Open in new window

It's not a good idea to call jquery twice, even if the version is the same: I suggest you suppress this:

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

Open in new window


or this

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>      
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> 

Open in new window

In addition this doesn't make sense

//code.jquery.com/

double slash doesn't mean nothing to me
//code.jquery.com/

Is protocol agnostic - will use http or https depending on the current url
Oh, thanks Gary, I didn't know it.
Avatar of DMTrump

ASKER

I wondered about the weird calls.  But that in itslef did not fix the problem.
Avatar of DMTrump

ASKER

Marco, neither alert displays - something is short-circuiting.
var category = json_encode($peraccess);

json_encode is PHP what you want is
JSON.stringify

Edit
And I've just noticed - $peraccess is a PHP variable, if you want to pass into the javascript and assuming this js code is in the php page and after where you set this value that line should be like this

var category = JSON.stringify(<?php echo $peraccess?>);
Avatar of DMTrump

ASKER

When I replace the ajax with the original alert     alert(udxNewOrder.join('\n'));
 that shows the array.
If I put the ajax section back in, either before or after the alert, it doesn't show.  Something is killing the submit function when the ajax is in there.
Actually I'm not sure what $peraccess is supposed to be and where it is coming from and if it needs to be encoded
The code is a bit confusing
Avatar of DMTrump

ASKER

Yikes! Gary, that was the cause of the failure! - and ironically on further investigation I didn't need that cat variable after all.  So I removed that and now Marco's alerts return "done".  

Too many long years in PHP and in spite of 35 years of coding (embedded systems, Windows apps, lots of PHP etc - I'm a total newby at JS - especially jquery and ajax.

So I walked into a cafe in Paris and ordered in German and got a blank stare and directions to the Louvre!
LOL
Avatar of DMTrump

ASKER

$peraccess is a PHP variable used elsewhere in my web-app and needed in the processing of the array in the target PHP - but I realized I can grab it's current value in another way (from the global variables provided by Vibralogix SiteLok that I use to identify the current user).

So now I can go back to finishing the code in newOrder.php

(nowOrder.php is making its random update when called from the ajax, so I know that the target PHP is getting executed.)
Avatar of DMTrump

ASKER

Okay - I know the php is being executed.  Here is the ajax

function submit(){
     var udxNewOrder = [];
     $("ul#sortable1 li").each(function() {
        var str = $(this).text().substring(0, 3);
        udxNewOrder.push(str);    
    });

    $.ajax(
    {
      type: 'post',
      url: 'neworder.php',
      data: {newOrder: udxNewOrder.join('\n') }
    })
    .done(function(result)
    {
      alert('Done');
    })
    .fail(function(result)
    {
        alert('failed');
    });
}    

And in my php here's how I'm accepting the array

$udxarray = $_POST['newOrder'];

But it's not working........
however if  instead I create a fake array like so:
$udxarray = array("uvq","v17","v18","v16","v1b","v1a","v19");
Then my code works and the database is updated.  So obviously I'm not getting the array from the Post

I thought maybe I had to json_decode it:  $udxarray = json_decode($_POST['newOrder'], TRUE); but that doesn't work either.  Obviously there's something I'm still doing wrong - but what?
SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DMTrump

ASKER

Still no joy in mudville!

Here is my js function:
function submit(){
     var udxNewOrder = [];
     $("ul#sortable1 li").each(function() {
        var str = $(this).text().substring(0, 3);
        udxNewOrder.push(str);    
    });
    $.ajax(
    {
      type: 'post',
      url: 'neworder.php',
      data: {newOrder: JSON.stringify(udxNewOrder) }
    })
}

and here is my PHP

$udxarray = json_decode($_POST['newOrder']);

I should add that I also tried casting the json_decode to an array:
$udxarray = (array) json_decode($_POST['newOrder']);
The code works perfectly

Are you getting the alert failed/done?

What is your php code that grabs the posted value and does whatever to it?
Avatar of DMTrump

ASKER

Yes, it alerts done
and as I posted above here is my PHP code:

$udxarray = json_decode($_POST['newOrder']);

I should add that I also tried casting the json_decode to an array:
$udxarray = (array) json_decode($_POST['newOrder']);

And once again, if I insert a PHP array in place of the Post version of $udxarray, the PHP does it's job
Amend like this

// echo the post value and make sure it is correct
var_dump($_POST['newOrder']);

echo "<br><br>";

$udxarray = json_decode($_POST['newOrder']);

// dump the array 
var_dump($udxarray);

Open in new window

Avatar of DMTrump

ASKER

And here is the entire php  And I have tried it without lines 2 and 3 and a hard-coded value for $peraccess
<?php
$groupswithaccess="PUBLIC,CLIENT";
require_once("slpw/sitelokpw.php");
$peraccess = $slcustom3;

$udxarray = json_decode($_POST['newOrder']);

//$udxarray = array("uvq","v17","v18","v16","v1b","v1a","v19");

$con = mysqli_connect("localhost","go_sys","aTGXXXXXXXXXXXX]X&","go_datax");  // disguised!
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$order = 1;
foreach ($udxarray as $value)
{
  $sql="UPDATE percats SET rank = '".$order."' WHERE udx = '".$value."' AND category = '".$peraccess."' ";
  mysqli_query($con,$sql);
  $order=$order+1;
}
mysqli_close($con);
?>
Whats the result of my comment above?
Avatar of DMTrump

ASKER

If I include your dump code, how do I view it?  (Pardon my ignorance (which has already been fully proven)
Do you have FF? Install Firebug.

When installed click the bug in the top right, this will open up the Firebug console
Make sure the console tab is selected
Run your page and you should see a new entry appear for your ajax call, click the expand icon (the + sign) can click on response and post here the contents.
Avatar of DMTrump

ASKER

Here's what is output in the console:

string(89) "[\"v0w\",\"v0v\",\"v0y\",\"v0x\",\"v0z\",\"v10\",\"v11\",\"v12\",\"v13\",\"v14\",\"v15\"]"
<br><br>NULL


So the string version of the array is coming through but the json_decode is returning NULL?
Change
$udxarray = json_decode($_POST['newOrder']);

to
$udxarray = json_decode($_POST['newOrder'],true);
Avatar of DMTrump

ASKER

It still returns NULL (I had already tried that before having the dump)
Avatar of DMTrump

ASKER

$udxarray = json_decode(str_replace('\\', '', $_POST['newOrder']));

produces:

string(89) "[\"v0w\",\"v0v\",\"v0y\",\"v0x\",\"v0z\",\"v10\",\"v11\",\"v12\",\"v13\",\"v14\",\"v15\"]"
<br><br>array(11) {
  [0]=>
  string(3) "v0w"
  [1]=>
  string(3) "v0v"
  [2]=>
  string(3) "v0y"
  [3]=>
  string(3) "v0x"
  [4]=>
  string(3) "v0z"
  [5]=>
  string(3) "v10"
  [6]=>
  string(3) "v11"
  [7]=>
  string(3) "v12"
  [8]=>
  string(3) "v13"
  [9]=>
  string(3) "v14"
  [10]=>
  string(3) "v15"
}
I have to go, maybe Marco can continue, else I will get back to it tomorrow.
Is there any reason why you need to do this as an array, why not just build a comma separated list of your categories, post this and then put in an array in your php page.
What version of PHP are you on?
Avatar of DMTrump

ASKER

I don't know the full version but I know it's 5.x.x - probably the latest stable.  I'm running on a VPS from WiredTree

And I have to go too.  I'm getting really hungry!!!!

Thanks for your help - I may be able to take it from here but you've certainly earned your points - I'll wait to close the question until I can post full code that works so this can help someone else in the future.  But you'll surely get the points!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DMTrump

ASKER

Wow!  Nice stuff while I was asleep.  It will be a little bit before I can test things out but it looks good.
Avatar of DMTrump

ASKER

I'm going to have to suspend this question for today.  I have a contract customer waiting for some other work and it will probably take me most of the day.  Thanks so far, and watch for a further post after 10 hours or so.  I dabbled a little in the suggestions but didn't succeed so far but I've got to step aside for a while and get the other work done.

Thanks a lot!
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DMTrump

ASKER

Marco and Gary both helped me find the final answer to my problem - so I've awarded them both half the points  I marked my own comment as the best solution because it summarizes best for someone who might happen upon this.  I don't claim the credit -