0

this is my code:

<script>
 jQuery(function() {
    jQuery.getJSON('lessons.json', function(data) {             
    var lessonID = data.t["sfwd-lessons"];
       $.each(lessonID, function(i, val) {
       lessonID = val;
       console.log(lessonID);
       })
    }); 
 }); 
             
</script>

I get a list of IDs that I can use for different curl api call. So, what's the best way to pass these jquery variables to PHP for an api call?

It should be something like this:

curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://website.com/wp-json/ldlms/v2/sfwd-lessons/'.lessonID,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer '.$token.'',
            'Cookie: cookie'
        ),
    ));

Thank you all.

hhh
  • 394
  • 2
  • 15
  • 3
    PHP runs _before_ there's any output sent to the browser. So the moment Javascript (jQuery) does its job, PHP is already finished. The only way to do this would be to submit the data towards a new PHP script and let it handle it. This can be a form or Ajax. Most likely Ajax will be what you're looking for. – icecub Feb 26 '21 at 15:22
  • 3
    The "best way" depends on how you want your code to work. Do you want to do it in the "background" (without the browser reloads?), then you can use Ajax. Do you want to send the user to another page? Then you can use a form or pass them in the URL. Either way, you need to make a request to PHP where you pass the values. Without more info, that's about as specific we can get. – M. Eriksson Feb 26 '21 at 15:22
  • The idea is to pass data without any browser reload. How can I pass data with ajax? Any example? thank you. – hhh Feb 26 '21 at 15:26
  • There are plenty of examples on the official documentation website: https://api.jquery.com/jquery.ajax/ Most likely you want to look at the examples given at the bottom of the page there. – icecub Feb 26 '21 at 15:30

1 Answers1

2

There are three steps: (1) Retrieving DOM data: inputs, textarea, etc, (2) Sending via AJAX, (3) Retrieving it in PHP:

1 - DOM Data with jQuery: build a single object (easier to send)

let myData = {
    name: $('#name').val(),
    description: $('#description').val(),
    ...
}

2 - Send it via Ajax:

jQuery.ajax({
     data:  myData,
     url:   PHPurl,
     type:  "post",
     method: "POST",
     success:  function (response) {
         // whatever
     },
     error: function (e) {
         // whatever
     }
});

3 - Retrieve it in PHP

$name = isset($_POST['name']) ? $_POST['name'] : '';
$description = isset($_POST['description']) ? $_POST['description'] : 'default description';
... more data

Now if you need to make a cURL call using that data, you have two options:

  • Pass an array and use header Content-Type 'multipart/form-data':
$data = array(
   'name' => $name,
   'description' => $description,
   ...
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  • Or encode the same array as json, and use header Content-Type 'application/json':
$data = array(...);
$data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

---- EDIT (Relative to your question below) I see you read a 'lessons.json'. So you get a list of lessons from there. In that case you need to keep the relation between each lesson object, and the DOM elements. For example:

for(let lesson of lessons) {
   // Create your HTML inputs to edit the lesson
   let container = $("<div class='lesson-editor'></div>");

   container.append(...);
   container.append(...);

   // Now add a reference to the ID of the lesson
   container.attr("lessonId", lesson.ID);
}

Now you have an editor for each lesson, and each "container" has the ID of the lesson it's editing.

Later in Javascript, when you want to build your list of lessons and send it with AJAX:

let lessons = [];
let containers = $(".lesson-editor");
containers.each(function() {
    
   let ID = $(this).attr("lessonId");
   
   let lesson = {
       ID: ID,
       name: $(this).find("#nameInput"),
       description: $(this).find("#descInput"),
       ....
   }

   lessons.push(lesson);

});

// -> ajax, data: { lessons: lessons }

Then remember that in PHP you have $_POST['lessons'] that is an array of objects (associative arrays).


Oscar Sales DEV
  • 436
  • 3
  • 5
  • Very detailed answer. Thank you. I'm trying to get IDs with ajax. This is my code: jQuery.ajax({ data: {lessonContent : lessonContent}, url: "/learndash-api/webinar-bst-past-ids.php", type: "post", method: "POST", success: function (response) { console.log(lessonContent) }, error: function (e) { console.log('error'); } }); `code` – hhh Feb 26 '21 at 16:35
  • The console log returns a succes answer but only shows the last ID. How can I got all the IDs? – hhh Feb 26 '21 at 16:36
  • I've edited my answer, check. – Oscar Sales DEV Feb 26 '21 at 17:14
  • _Side note:_ You don't need to set both `type` and `method` in the ajax call since `type` is an alias for `method`. Just using one or the other is sufficient. – M. Eriksson Mar 01 '21 at 08:41
  • Yes I know, I've added both because once I had problems with ajax precisely due to this. One didn't work and the other did. Since then I've always used both to avoid trouble. – Oscar Sales DEV Mar 01 '21 at 11:39