Friday, 4 April 2014

How to pass a Javascript Array to PHP file using AJAX and JSON?

How to pass a Javascript Array to PHP file using AJAX and JSON?

I have an array in javascript and I need to pass this array to a PHP by using AJAX call to that PHP file. I will get this array in PHP file and assign this javascript array to PHP array. Then I will find out the count of that PHP array elements and return it back to the javascript. I will convert JS array in JSON format by JSON.stringify. This is a very simple example on how to pass javascript array to PHP asynchronously. You can perform a lot of operations on this array which you have passed to PHP file but for simplicity I am just returning its count. Let's have a look at the following code snippet.

Javascript Array

var myJSArray = new Array("Saab","Volvo","BMW");

ProcessAJAXRequest() function wil pass JS array to PHP file using AJAX request and will show count of array elements returned by PHP file.

function ProcessAJAXRequest()
{
    $.ajax
    ({
        type: "POST",
        url: "myphpfile.php",
        data: {"myJSArray" : JSON.stringify(myJSArray)},
        success: function (data) 
        {
            alert(data); //count of array elements
        }
    });
}

myphpfile.php

<?php 
    $myPHPArray = json_decode($_POST["myJSArray"]);
    echo count($myPHPArray);
 ?>

11 comments:

  1. Play the Best Free Games! We've picked out the racing games, cooking games, candy crush, games shooting, fashion games, ...
    Thanks for sharing !
    Kizi 200
    Friv 1
    Y88
    Y9

    ReplyDelete
  2. I Discovered Many new things from your article. Thank you for this!
    Friv4
    Friv

    ReplyDelete
  3. Please visit our website and play exciting games,thank you verry much
    Friv 2|
    Friv 1000|
    HappyWheels

    ReplyDelete
  4. You'd have time to look these kids active. Please visit our website and let us play the games interesting.
    Thanks you for sharing !
    Friv 100
    Friv 8
    Friv 2

    ReplyDelete
  5. You want to relax after a stressful working hours. Refer to our website. Hope you get the most comfort.
    Thanks for sharing !
    GirlsGoGames
    Kizi 100
    Frvi

    ReplyDelete
  6. Free gaming, the best free online games for you
    Friv 2/
    Friv 4

    ReplyDelete
  7. I’m glad you enjoyed it. Those are great habits! Thank you for sharing.
    Y8Y8Y8

    ReplyDelete
  8. Thanks for the sharing of such information we will pass it on to our readers.
    Friv 2
    Friv 4
    Friv 3

    ReplyDelete
  9. you'd have time to look these kids active. Please visit our website and let us play the game interesting.
    A10 Friv
    Friv 10
    Y6

    ReplyDelete
  10. Our website has many interesting games. Please share this with your friends and have fun.
    Friv 2/
    Kizi 1000

    ReplyDelete