skip to Main Content

I have a json file like this.

{
    "name" : [
        "Alsa", "Alice", "Alas", "Alpha", "Beta", "Bervis", "Bankai", "Celcia", "Celsa", "Ceasar", 
        "Domino", "Dorito", "David", "Eurius", "Easter", "Ethium", "Fourin", "Flora", "Fifa", "Genius"
    ]
}

I would perform a jQuery AJAX call like this.

            function method1(){
                $.ajax({
                url: "name_suggestion.json",
                type: "GET",
                dataType : "JSON",
                success : function(data){
                    for(i in data.name){
                        name_array.push(data.name[i]);
                    }
                }
            });
            }
            function method2(){
                $.post('search_name.php', {
                      names: JSON.stringify(name_array)
                    }, function(data, status){
                        console.log(data);
                    }
                );
            }
            $.when(method1()).then(method2);

In PHP file,

<?php
$nameData = json_decode($_POST['names']);
print_r($nameData[1]);
?>

When the function is called, it shows an error saying array key is not defined.

If I pass a normal array written in JavaScript, it won’t show the error but that’s not how I want to do:)
I am just into AJAX so if there is any mistake, I would love to know!

EDIT:
Here is the final code which works(Thanks for the answer)

          var name_array = [];
            function method1() {
                $.ajax({
                    url: "name_suggestion.json",
                    type: "GET",
                    dataType: "JSON",
                    success: function(data) {
                        name_array = data.name;
                        method2(name_array); 
                    }
                });
            }

            function method2(name_array) {
                $.get('search_name.php', {
                    names: JSON.stringify(name_array)
                }, function(data, status) {
                    console.log(data);
                });
            }
            method1();

2

Answers


  1. var name_array = [];
    
    function method1() {
        var name_array = [];
    
        $.ajax({
            url: "name_suggestion.json",
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                for (var i in data.name) {
                    name_array.push(data.name[i]);
                }
    
                method2(name_array); 
            }
        });
    }
    
    function method2(name_array) {
        $.post('search_name.php', {
            names: JSON.stringify(name_array)
        }, function(data, status) {
            console.log(data);
        });
    }
    
    method1();
    

    In your PHP code, you are trying to access the second element of $nameData using print_r($nameData[1]). However, json_decode with the default second parameter set to false returns an object, not an array. To access the elements, you should use the arrow (->) operator instead of square brackets.

    <?php
    $jsonData = file_get_contents('php://input');
    $nameData = json_decode($jsonData);
    
    print_r($nameData->name[1]);
    ?>
    

    Hope it works mate!

    Login or Signup to reply.
  2. Picking up on the suggestion above by @Brad – the Fetch api offers an easy to use, powerful and reliable means of sending ajax requests. An "All-in-One" example solution using Fetch

    <?php
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['names'] ) ){
    
            # In the Fetch call we set a FormData parameter called "names" which we access here.
            $data=json_decode( $_POST['names'] );
            # The data we want is within the property "name"
            $names=$data->name;
            
            # do something with the data
            foreach( $names as $index => $name )echo $name;
            
            exit();
        }
    ?>
    <!DOCTYPE html>
    <html lang='en'>
        <head>
            <title></title>
        </head>
        <body>
            <script>
            
                const getresponse=(r)=>r.text();
                const callback=(res)=>console.log(res)
                
                const json={
                    "name" : [
                        "Alsa", "Alice", "Alas", "Alpha", "Beta", "Bervis", "Bankai", "Celcia", "Celsa", "Ceasar", 
                        "Domino", "Dorito", "David", "Eurius", "Easter", "Ethium", "Fourin", "Flora", "Fifa", "Genius"
                    ]
                };
                
                let fd=new FormData();
                    fd.set( 'names', JSON.stringify( json ) );// set the property we will access in PHP
                    
                fetch( location.href, { method:'post', body:fd })
                    .then( getresponse )
                    .then( callback )
                    .catch( alert ) 
            </script>
        </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search