简体   繁体   中英

Send JSON from Javascript to PHP with AJAX using Jquery

Why AJAX is not sending the Json object to the php file?

Full code (JS):

<script>
 //Json-Ajax: Getr JSON via Ajax
var xmlhttp = new XMLHttpRequest();
var url = "creador_json.php";

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
var arreglo = JSON.parse(response);
salida = "";

for(var i = 0; i < arreglo.length; i++) {
salida += '<li id="'+ arreglo[i].Identif +'" class="ui-state-default">' +   arreglo[i].Nombre + "</li>";
}
$("#sortable1").append(salida);

//Jquery UI Sortable y límite de selección
$(function() {
$( "#sortable2" ).sortable({
  connectWith: ".connectedSortable",
  //receive: This event is triggered when a
  //connected sortable list has received an item from another list.
  receive: function(event, ui) {
    if ($(this).children().length > 3) {
        //ui.sender: will cancel the change.
        //Useful in the 'receive' callback.
        $(ui.sender).sortable('cancel');
          alert('No se pueden ingresar más de 3 elementos');
        }
    }
 }).disableSelection();
});

$(function() {
$( "#sortable1" ).sortable({
  connectWith: ".connectedSortable",
}).disableSelection();
});

//button event
$( "#button" ).click(function(){
  var myArray = [];
    $("#sortable2 li").each(function() {
      var id_li = $(this).attr('id');
      var contenido_li = $(this).text();
      //myArray.push( id_li, contenido_li);
      //myArray[myArray.length]=( id_li, contenido_li);

      myArray[myArray.length]={
        id: id_li, 
        nombre: contenido_li
      };
    });
    var objJson = JSON.stringify(myArray);

    //send Json object Ajax to PHP file 


    console.log(objJson);

$.ajax({
       type: "POST",
        url: 'guardar_enbd.php',
        data: {'myJson': objJson},
       success: function(response) {
          alert('sending Json');
          console.log(objJson);             
       }
    });  

});
}//Cierre de MyFunction

</script>

As you see in the following code, I have my Json Object in a Variable called "objJson", So, after use AJAX to send it to my php (guardar_enbd.php), I get this error "Notice: Undefined index: myJson in C:\\xampp\\htdocs\\guardar_enbd.php on line 4"

//button event
$( "#button" ).click(function(){
  var myArray = [];
    $("#sortable2 li").each(function() {
      var id_li = $(this).attr('id');
      var contenido_li = $(this).text();
      //myArray.push( id_li, contenido_li);
      //myArray[myArray.length]=( id_li, contenido_li);

      myArray[myArray.length]={
        id: id_li, 
        nombre: contenido_li
      };
    });
    var objJson = JSON.stringify(myArray);

    //send Json object Ajax to PHP file 


    console.log(objJson);

$.ajax({
       type: "POST",
        url: 'guardar_enbd.php',
        data: {'myJson': objJson},
       success: function(response) {
          alert('sending Json');
          console.log(objJson);             
       }
    });  

});

PHP file code:

<?php

$myval = $_POST['myJson'];
echo $myval;


?>

Taking the code from your example into a single file it is working for me.

Can you tell me what is the output you are getting for console.log(objJson);?

//ajax.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $myval = $_POST['myJson'];
    echo $myval;
    exit();
}

?>

<html>
<head>
    <script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>

    <script type="application/javascript">

        $(document).ready(function(){

            $( "#button" ).click(function(){

                var myArray = [];

                $("#sortable2 li").each(function() {
                    var id_li = $(this).attr('id');
                    var contenido_li = $(this).text();
                    //myArray.push( id_li, contenido_li);
                    //myArray[myArray.length]=( id_li, contenido_li);

                    myArray[myArray.length]={
                        id: id_li,
                        nombre: contenido_li
                    };
                });

                var objJson = JSON.stringify(myArray);

                $.ajax({
                    type: "POST",
                    url: '',
                    data: {'myJson': objJson},
                    success: function(response) {
                        console.log(objJson); //[{"id":"one","nombre":"1"},{"id":"two","nombre":"2"},{"id":"three","nombre":"3"}]
                        console.log(response); //[{"id":"one","nombre":"1"},{"id":"two","nombre":"2"},{"id":"three","nombre":"3"}]
                    }
                });
            });

        });

    </script>

</head>
<body>
<a id="button">click me</a>
<ul id="sortable2">
    <li id="one">1</li>
    <li id="two">2</li>
    <li id="three">3</li>
</ul>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM