Search code examples
phpjsonajaxlocalhostmamp

How can I use json on localhost (MAMP)?


index.php

    <button class="button">color</button>
    <div class="blue"></div>
    <div class="red"></div>

script.js

$(".button").click(function(){
  $.ajax({
        url: "update.php",
        type: "POST",
        success: function (data) {
            $(".blue").html(data.blue);
            $(".red").html(data.red);
              alert("success");
        }
    })
});

update.php

$array['blue'] = "blue content";
$array['red'] = "red content";
header('Content-type: application/json');
echo json_encode($array);

I want to work with json on localhost. But it is not working. I am using MAMP.


Solution

  • use DataType : 'json' on the ajax call and set encode to true. I have done a working fiddle for you to see, that is working.

      $(document).on("click", ".send", function (event) {
       $.ajax({
                url: "http://www.personaldev.co.za/json/update.php",
                type: "POST",
                dataType : 'json',
                encode : true,
                success: function (data) {
                    console.log(data);
                    $(".blue").html(data.blue);
                    $(".red").html(data.red);
                }
            })
     });
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
     
    
    <button class="send">Send</button>
    <div class="blue" style="background: blue;color: white"></div>
    <div class="red" style="background: red;color:white"></div>

    update.php

    <?php
        header('Access-Control-Allow-Origin: *');
        $array['blue'] = "blue content";
        $array['red'] = "red content";
    
        echo json_encode($array);
    ?>
    

    Nb: header('Access-Control-Allow-Origin: *'); you don't actually need this I did this so that the fiddle can be able to access the update file from my server, so you can see this in action live.

    result :

    enter image description here