skip to Main Content

The code request an associative array from a php file.
There is an example of the code that I’m using:

function cOffices() {
    return $.post('../../init.php', {
        getOffice: ''
    }, (data) => {
    }, 'json');
}
cOffices()
        .done((data) => {
            console.log(data);
        });

That piece of code doesn’t show any data on the console.
But if I change the code and don’t use the ‘json’ datatype, it shows all the arrays in a string

function cOffices() {
    return $.post('../../init.php', {
        getOffice: ''
    }, (data) => {
    }, 'json');
}

Here is my php file

if (isset($_REQUEST['getOffice'])) {
            $oficModel = new User();

            $getO = $oficModel -> getOfficeData($config['dirLogin'], $config['dirPass']);

            echo json_encode($getO);
        }

By the way, these are my scripts:

<script src="../js/jquery-3.6.0.min.js"></script>
<script type="module" src="../js/users.js"></script>

UPDATE:
I want to use the request after I request data in another request.
Here is an example:

$.post('../../init.php', {
        getCreate: ''
    }, (data) => {
        let lOptions = '';

        data.forEach((d) => {
            lOptions += `<option value="${d.id_grupo}">${d.nom_grupo}</option>`;
        });

        let formCreate = `<div class="formCreate">
            <form action="../../init.php" method="POST" id="formCreate" autocomplete="off">
                <button type="button" class="closeForm"><i class="fas fa-times"></i></button>
                <h2>Create User</h2>
                <input required type="email" name="cMail" placeholder="Insert E-Mail"
                maxlength="35" id="cMail">
                <input required type="password" name="cPass" placeholder="Insert Password"
                maxlength="24" id="cPass">
                <input required type="text" name="cName" placeholder="Insert Name"
                maxlength="40" id="cName">
                <div class="selectOffice">
                    <select name="cOffice" id="cOffice" required>
                        <option value="" disabled selected>Select an Office</option>
                        ${lOptions}
                    </select>
                </div>
                <div class="selectCreate">
                    <select name="cGroup" id="cGroup" required>
                        <option value="" disabled selected>Select a Group</option>
                        ${lOffices}
                    </select>
                </div>
                <button type="submit" name="saveUser">Save</button>
            </form>
        </div>`;

        $('.container1').prepend(formCreate);
        $('.formCreate').fadeTo(400, 1);
    },'json');
}

ANOTHER UPDATE [SOLVED]
I found the error, in my php I had 2 processes with the same name, so when I did an ajax call, the data was 2 json encoded strings, and ajax couldn’t decode that. Sorry for the inconvenience

2

Answers


  1. Try using

    cOffices.error(function(jqXHR, textStatus, errorThrown) {
            console.log("error " + textStatus);
            console.log("incoming Text " + jqXHR.responseText);
        })
    

    to define the reason of the error.
    It might be you have corrupted JSON in the response.

    Also check your request in the network tab of the dev console

    Login or Signup to reply.
  2. Consider the following example.

    $(function() {
      function cOffices() {
        $.ajax({
          url: "../../init.php",
          type: "POST",
          data: {
            getOffice: true
          },
          dataType: "json",
          success: function(results) {
            return results;
          },
          error: function(x, status, error) {
            console.log("Error:", status, error);
          }
        });
      }
    
      $("button").click(function() {
        console.log(cOffices());
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    Using $.post() is very similar. It should also identify JSON data, but this is just a bit more specific.

    Update

    Now seeing your PHP, I would advise entering a value into getOffice variable. Yes, "" should work and isset() should detect that it’s a variable with an Empty String set, and it might be better to pass a variable just in case. I updated mine with getOffice: true for example.

    Update 2

    I created the following example Fiddle: https://jsfiddle.net/Twisty/7oh29dyj/

    JavaScript (jQuery 3.6.0)

    $(function() {
      var testData = JSON.stringify([{
        "id_lugar": "1",
        "desc_lugar": "Oficina Nu00famero 1",
        "dir_lugar": "Calle Random 1",
        "depart_lugar": "Montevideo",
        "ciudad_lugar": "Montevideo",
        "tel_lugar": "94132471",
        "fk_dep": "0"
      }]);
    
      var myData = [];
    
      function cOffices() {
        var myPost = $.ajax({
          url: "/echo/json/",
          type: "POST",
          data: {
            json: testData
          },
          dataType: "json",
          success: function(results) {
            myData = results;
            $(".results").html(JSON.stringify(results));
          }
        });
      }
    
      $("button").click(function() {
        cOffices();
      });
    });
    

    This is working in the Fiddle. Remember that the scope of results or data only exists in that callback. It is usually best to do what you want with the data in that same callback.

    My example puts the data in a more globally scoped variable, so you can get to it from other functions if needed. If you want to manage the data, you have to wait until the AJAX completes. Due to the async nature of JS, you may need to wait until the ready state completes to ensure the variable is populated.

    Update 3

    Try the following.

    $.post('../../init.php', {
      getCreate: ''
    }, (data) => {
      var formCreate = "<div class='formCreate'><form action='../../init.php' method='POST' id='formCreate' autocomplete='off'><button type='button' class='closeForm'><i class='fas fa-times'></i></button><h2>Create User</h2><input required type='email' name='cMail' placeholder='Insert E-Mail' maxlength='35' id='cMail'><input required type='password' name='cPass' placeholder='Insert Password' maxlength='24' id='cPass'><input required type='text' name='cName' placeholder='Insert Name' maxlength='40' id='cName'><div class='selectOffice'><select name='cOffice' id='cOffice' required><option value='' disabled selected>Select an Office</option></option></select></div><div class='selectCreate'><select name='cGroup' id='cGroup' required><option value='' disabled selected>Select a Group</option></select></div><button type='submit' name='saveUser'>Save</button></form></div>";
    
      $.each(data, function(k, v) {
        $("<option>", {
          value: v.id_grupo
        }).html(v.nom_grupo).appendTo($("#cOffice", formCreate));
        $("<option>", {
          value: v.id_grupo
        }).html(v.nom_grupo).appendTo($("#cGroup", formCreate));
      });
    
      $('.container1').prepend(formCreate);
      $('.formCreate').fadeTo(400, 1);
    }, "json");
    

    This created all the relevant HTML first, then appends the dynamic elements from the data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search