Jump to content

imgrooot

Members
  • Posts

    383
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by imgrooot

  1. I am using ajax live search to retrieve data from MySQL table. It works fine. However I noticed that it only returns a single result that matches the entire word instead of multiple results that match only the first couple letters.

    For e.g.

    DB Table

    ----------------

    1. Foot

    2. Foot Path

    3. Football

    ----------------

    If I type "foo" in the ajax search field, it won't return any results. But if I type "foot", it'll return "Foot". It won't return the other two results that contain the letters "Foot".

    Here's my query

    $param_term = $_POST["term"] . '%';
    
    $get_data = $db->prepare("SELECT name FROM table WHERE title LIKE :param");
    $get_data->bindParam(':param', $param_term);
    $get_data->execute();

     

    I was wondering how can I improve the above query so that it looks for all potential results based on partial matching of letters?

  2. I found the mistake. All I had to do was to add a "," after the beforeShowday to separate it from the onSelect function. You could've just told me this.

    Also I don't even have to create a variable outside the ajax as you previously told me. It works fine without it. 

    Here's the updated code.

    <script>
    $(document).ready(function() {
    
      function formattedDate(d = new Date) {
        let month = String(d.getMonth() + 1);
        let day = String(d.getDate());
        const year = String(d.getFullYear());
    
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        return `${year}-${month}-${day}`;
      }
      $.ajax({
        type: "POST",
        url: 'snippets/adapter-fetch.php',
        data: {},
        dataType: 'json',
        success: function(highlighted) {
    
          $('#datetimepicker1').datepicker({
            dateFormat: "yy-mm-dd",
            multidate: true,
    
            beforeShowDay: function(date) {
    
              newDate = formattedDate(date);
    
              for(let x=0; x < highlighted.length; x++) {
                console.log(highlighted[x], newDate);
    
                if (highlighted[x] === newDate) {
                  return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
                }
              }
              return [true, '']; // default if not a highlight
            },
    
            onSelect: function () {
                var getDate = $("#datetimepicker1").val();
    
                $.ajax({
                     type: "POST",
                     url: "snippets/adapter-set.php",
                     data: { date: getDate },
                     success: function(data) {
                      // alert(data);
                     },
                     error: function() {
                         alert("Error.");
                     }
                });
            }
    
          });
        }
      });
    
    });
    </script>

     

  3. 1 hour ago, requinix said:

    I'm not going to write the code for you. Instead, I'm going to refer you to my previous post where I said

    Look at your code, read that post again, and decide whether your code is accurately reflected by the statements I made.

    I'm not asking you to redo the whole code. The code I have works. It just needs to be reformatted so both work on the same page. 

    And I understand about being only able to using a single datepicker instance. And like I said before, I have tried many different variations  in the past 24 hours and none of them work. So either I keep going in circles or you can help me out and insert your code snippet in the right place into my code. It helps to see it visually.

     

    Here's the updated code with what you were trying to say. It doesn't show the Calendar anymore and I get this error in the console "Uncaught SyntaxError: Unexpected identifier".

     

    <script>
    $(document).ready(function() {
    
      function formattedDate(d = new Date) {
        let month = String(d.getMonth() + 1);
        let day = String(d.getDate());
        const year = String(d.getFullYear());
    
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        return `${year}-${month}-${day}`;
      }
      //CODE#1
      // THIS CODE FETCHES DATES FROM A MYSQL TABLE AND HIGHLIGHTS THEM ON A DATEPICKER CALENDAR
    
      var highlighted = null;
    
      $.ajax({
        type: "POST",
        url: 'snippets/adapter-fetch.php',
        data: {},
        dataType: 'json',
        success: function(data) {
    
          highlighted = data;
    
          $('#datetimepicker1').datepicker({
            dateFormat: "yy-mm-dd",
            multidate: true,
    
            beforeShowDay: function(date) {
    
              newDate = formattedDate(date);
    
              for(let x=0; x < highlighted.length; x++) {
                console.log(highlighted[x], newDate);
    
                if (highlighted[x] === newDate) {
                  return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
                }
              }
              return [true, '']; // default if not a highlight
            }
    
            onSelect: function () {
                var getDate = $("#datetimepicker1").val();
    
                $.ajax({
                     type: "POST",
                     url: "snippets/adapter-set.php",
                     data: { date: getDate },
                     success: function(data) {
                      // alert(data);
                     },
                     error: function() {
                         alert("Error.");
                     }
                });
            }
    
          });
        }
      });
    
    });
    </script>

     

  4. 23 hours ago, requinix said:
    var highlighted = null;
    $.ajax({
    	...
    	onSuccess: function(data) {
    		highlighted = data;
    	}
    	...
    });

     

    Been trying your method many different ways and it still doesn't work. 

    Could you please add your edits to the entire code below instead of bits and pieces? Here's my code with your supposed update code. It doesn't return any errors, but it doesn't highlight the dates either.

    <script>
    $(document).ready(function() {
    
      function formattedDate(d = new Date) {
        let month = String(d.getMonth() + 1);
        let day = String(d.getDate());
        const year = String(d.getFullYear());
    
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        return `${year}-${month}-${day}`;
      }
      //CODE#1
      // THIS CODE FETCHES DATES FROM A MYSQL TABLE AND HIGHLIGHTS THEM ON A DATEPICKER CALENDAR
    
      var highlighted = null;
    
      $.ajax({
        type: "POST",
        url: 'snippets/adapter-fetch.php',
        data: {},
        dataType: 'json',
        success: function(data) {
    
          highlighted = data;
    
          $('#datetimepicker1').datepicker({
            dateFormat: "yy-mm-dd",
            multidate: true,
    
            beforeShowDay: function(date) {
    
              newDate = formattedDate(date);
    
              for(let x=0; x < highlighted.length; x++) {
                console.log(highlighted[x], newDate);
    
                if (highlighted[x] === newDate) {
                  return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
                }
              }
              return [true, '']; // default if not a highlight
            }
    
          });
        }
      });
    
      // CODE#1
      // THIS CODE INSERTS AND REMOVES THE SELECTED DATES FROM THE MYSQL TABLE.
      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,
        onSelect: function () {
            var getDate = $("#datetimepicker1").val();
    
            $.ajax({
                 type: "POST",
                 url: "snippets/adapter-set.php",
                 data: { date: getDate },
                 success: function(data) {
                  // alert(data);
                 },
                 error: function() {
                     alert("Error.");
                 }
            });
        }
      });
    
    });
    </script>

     

  5. 36 minutes ago, requinix said:

    The date picker only allows one of itself to exist on #datetimepicker1 at a time. Imagine the types of conflicts there could be if it tried to run twice on the same control.

    Your first datepicker code needs "highlighted" to know which dates to highlight. Instead of using the variable that comes from $.ajax, use a separate variable, and have the AJAX set that variable. For a brief moment after the page loads, the date picker will be set up and not highlighting any dates, but the user probably won't be able to hit the date picker fast enough to see that being the case.

    With the datepicker initialization happening outside of the AJAX, you can more easily combine the beforeShowDay and onSelect options into that configuration object datepicker needs.

    I sort of understand what you're trying to say. Can you show me an example of setting up a variable outside the ajax using my code? Seeing it would help a lot.  

  6. On 6/28/2021 at 7:53 PM, requinix said:

    I don't know what you think, but that is not a date. That's a bunch of numbers and hyphens.

    Would you expect this

    
    $.post('snippets/adapter-fetch.php', {},
    function(data) {
      $("#datetimepicker1").datepicker({
        datesEnabled : "2021-06-022021-06-032021-06-01"
      });
    });

    to work?

    Keep thinking in that direction for a few minutes and see what you can come up with.

    I have finally solved this issue. It was a lot more complicated than I originally imagined. Here's code.

    <script>
    $(document).ready(function() {
    
      function formattedDate(d = new Date) {
        let month = String(d.getMonth() + 1);
        let day = String(d.getDate());
        const year = String(d.getFullYear());
    
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        return `${year}-${month}-${day}`;
      }
    
      $.ajax({
        type: "POST",
        url: 'snippets/adapter-fetch.php',
        data: {},
        dataType: 'json',
        success: function(highlighted) {
          $('#datetimepicker1').datepicker({
            dateFormat: "yy-mm-dd",
            multidate: true,
            beforeShowDay: function(date) {
              newDate = formattedDate(date);
              for(let x=0; x < highlighted.length; x++) {
                if (highlighted[x] === newDate) {
                  return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
                }
              }
              return [true, '']; // default if not a highlight
            }
          });
        }
      });
      
    });
    </script>
    // PHP adapter-fetch.php
    
    $global_user_id = 5;
    
    $find_query = $db->prepare("SELECT date_available FROM user_dates WHERE user_id = :user_id");
    $find_query->bindParam(':user_id', $global_user_id);
    $find_query->execute();
    $result_find = $find_query->fetchAll(PDO::FETCH_ASSOC);
    
    $dates = [];
    
    if(count($result_find) > 0) {
      foreach($result_find as $row) $dates[] = $row['date_available'];
    }
    echo json_encode($dates);

     

    So now the above code will highlight all the dates I fetch from the database table. And my original code will insert and delete dates entries when clicking a date on the Calendar. 

    Having said that I have a new issue. Here's the full code combined.

    <script>
    $(document).ready(function() {
    
      function formattedDate(d = new Date) {
        let month = String(d.getMonth() + 1);
        let day = String(d.getDate());
        const year = String(d.getFullYear());
    
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        return `${year}-${month}-${day}`;
      }
      // THIS CODE WILL HIGHLIGHT THE DATES
      $.ajax({
        type: "POST",
        url: 'snippets/adapter-fetch.php',
        data: {},
        dataType: 'json',
        success: function(highlighted) {
          $('#datetimepicker1').datepicker({
            dateFormat: "yy-mm-dd",
            multidate: true,
            beforeShowDay: function(date) {
              newDate = formattedDate(date);
              for(let x=0; x < highlighted.length; x++) {
                if (highlighted[x] === newDate) {
                  return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
                }
              }
              return [true, '']; // default if not a highlight
            }
          });
        }
      });
    
      // THIS CODE WILL INSERT/DELETE THE DATES
      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,
        onSelect: function () {
          var getDate = $("#datetimepicker1").val();
    
          $.ajax({
               type: "POST", //or GET. Whichever floats your boat.
               url: "snippets/adapter-set.php",
               data: { date: getDate },
               success: function(data) {
                // alert(data);
               },
               error: function() {
                   alert("Error.");
               }
          });
        }
      });
    
    });
    </script>

    It seems like the ajax code that highlights the dates won't work if I have both of them together. Can you tell me why I can't use the "$('#datetimepicker1').datepicker" twice in the same script? It doesn't return any errors. It just doesn't highlight the dates.

  7. 6 minutes ago, requinix said:

    Exactly what did the alert show? Or change your alert to a console.log and copy/paste what you get in the console.

    The alert shows the dates that the user already inserted into the database. Same output when using console.log.

    Like this.  Shows three different dates without any spacing between them.

    2021-06-022021-06-032021-06-01

     

  8. 30 minutes ago, requinix said:

    Definitely not the correct syntax.

    You familiar with Javascript much? May be worth spending an hour or two learning about it.

    Alright so I fixed that issue. The alert wouldn't work if I had the "json" in the function. Here's the updated code.

    $.post('snippets/adapter-fetch.php', {},
    function(data) {
      $("#datetimepicker1").datepicker({
        datesEnabled : data.datesEnabled
      });
      alert(data);
    });

    It returns the correct dates(eg. yy-mm-dd) from the adapter-fetch.php. Now I need to know how I can highlight these dates on the datepicker?

  9. 1 hour ago, requinix said:

    Have you looked at what output adapter-fetch.php is returning?

    I used alert to return the output but it's not working. I might be doing it wrong. No popup shows up.

    $.post('snippets/adapter-fetch.php', {}, function(data){
                $("#datetimepicker1").datepicker({
                  datesEnabled : data.datesEnabled
                  alert(data);
                });
            }, 'json');

    It gives me this error.

    Uncaught SyntaxError: Unexpected identifier

     

  10. I am trying to create a simple calendar where a user can add/remove their availability date. This part works so far. Now what I am having trouble with is highlighting the already selected dates that are fetched from a MySQL database.

     

    Here's my code.

    // HTML
    <div id="datetimepicker1"></div>
    // Jquery/Ajax
    
    <script>
    $(document).ready(function () {
    
      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,
        onSelect: function () {
            var getDate = $("#datetimepicker1").val();
    
            $.ajax({
                 type: "POST", //or GET. Whichever floats your boat.
                 url: "snippets/adapter-set.php",
                 data: { date: getDate },
                 success: function(data) {
                  // alert(data);
                 },
                 error: function() {
                     alert("Error.");
                 }
            });
        }
      });
    });
    </script>
    // PHP
    // adapter-set.php
    
    $post_date = $_POST['date'];
    
    $find_query = $db->prepare("SELECT user_id FROM user_dates WHERE date_available = :date_available");
    $find_query->bindParam(':date_available', $post_date);
    $find_query->execute();
    $result_find = $find_query->fetchAll(PDO::FETCH_ASSOC);
    if(count($result_find) > 0) {
      foreach($result_find as $row) {
        $user_id =	$row['user_id'];
      }
      $delete_query = $db->prepare("DELETE FROM user_dates WHERE user_id = :user_id");
      $delete_query->bindParam(':user_id', $user_id);
      $delete_query->execute();
      $result_delete = $delete_query->execute();
      if($result_delete == false) {
       echo 'delete false';
      } else {
       echo 'delete success';
      }
    } else {
      $insert_query = $db->prepare("INSERT INTO user_dates(date_available) VALUES(:date_available)");
      $insert_query->bindParam(':date_available', $post_date);
      $result_insert = $insert_query->execute();
      if($result_insert == false) {
       echo 'insert false';
      } else {
       echo 'insert success';
      }
    
    }

     

    The above code works fine. It inserts and deletes a date row in MySQL database table based on a click.

    Now what I would like to do is to highlight all the "available" dates that are already inserted into the database; so that the user knows which dates he has already selected. This is my code for that. But it doesn't seem to be working. No errors. It's just not highlighting the inserted dates. Can you tell me what I'm doing wrong?

    // JQUERY
    <script>
        $(document).ready(function() {
    
            $.post('snippets/adapter-fetch.php', {}, function(data){
                $("#datetimepicker1").datepicker({
                  datesEnabled : data.datesEnabled
                });
            }, 'json');
    
        });
    </script>
    // PHP
    // adapter-fetch.php
    
    $global_user_id = 5;
    
    $find_query = $db->prepare("SELECT date_available FROM user_dates WHERE user_id = :user_id");
    $find_query->bindParam(':user_id', $global_user_id);
    $find_query->execute();
    $result_find = $find_query->fetchAll(PDO::FETCH_ASSOC);
    if(count($result_find) > 0) {
      foreach($result_find as $row) {
        $date_available =	$row['date_available'];
    
        echo $date_available;
      }
    } else {
      echo 'not dates available';
    }

     

  11. Here's what I'm trying to do.

    1. A user creates a calendar that shows which dates he's available. This calendar could showcase availability for up to a year.

    2. Other users can do a search for a user that's available on a set date. For e.g. July 1st. 

    3. All the users available on July 1st will show up in the search results.

     

    There is no booking for appointments involved. It simply needs to show the users available on set dates. I am wondering what's the best way to create this calendar feature?

  12. On 11/16/2020 at 4:36 PM, kicken said:

    If you're sure they are returned in oldest to newest (rather than that being just by chance) then you could simply reverse the array.

    If you need more control, then see the other replies for details on implementing a sort.

     

    Wow that was a simple solution. It works now.

    Here is the update code. All I had to do was add ".reverse()" to the each data.

    <div id="output"></div>
    <script>
      $(document).ready(function(){
        $.ajax ({
          type: 'GET',
          url: "https://3rdpartywebsite.com/api/getcustomers",
          dataType: 'json',
          success: function(data) {
           $.each(data.reverse(), function(i, v) {
    
             var customerId 		   = v.customerId;
             var firstName 			   = v.firstName;
             var lastName  			   = v.lastName;
             var createdDateTime 	   = v.createdDateTime;
    
              $('#output').append('<ul class="output-ul">' + '<li>' + customerId + '</li>' + '<li>' + firstName + '</li>' + '<li>' + lastName + '</li>' +   '<li>' + createdDateTime + '</li>' + '</ul>');
           });
          }
        });
      });
    </script>

     

  13. 3 minutes ago, requinix said:

     

    I was hoping for a simpler solutions where someone can edit my code to include the sort by. I've been researching and trying to do it myself but no luck so far.

     

    Also I am noticing that the page load time increases every time I submit the record and  I retrieve them from the API. It really shouldn't be taking a min to load 20 records from the API. 

    Do you think if I create a pagination that it'll slow the load time? Or you think it's an issue on the API party's end?

  14. I am retrieving data using AJAX. I would like to sort them from newest to oldest date. Currently they show from oldest to newest.

    How do I do that?

    <div id="output"></div>
    <script>
      $(document).ready(function(){
        $.ajax ({
          type: 'GET',
          url: "https://3rdpartywebsite.com/api/getcustomers",
          dataType: 'json',
          success: function(data) {
           $.each(data, function(i, v) {
    
             var customerId 		   = v.customerId;
             var firstName 			   = v.firstName;
             var lastName  			   = v.lastName;
             var createdDateTime 	   = v.createdDateTime;
    
              $('#output').append('<ul class="output-ul">' + '<li>' + customerId + '</li>' + '<li>' + firstName + '</li>' + '<li>' + lastName + '</li>' +   '<li>' + createdDateTime + '</li>' + '</ul>');
           });
          }
        });
      });
    </script>

     

  15. I have a solution.

    Apparently I was inputting the wrong label name. Instead of it being "FirstName", it's actually with lowercase "firstName".

    Here's the new code.

    <script>
      $.ajax ({
        type: 'GET',
        url: "https://3rdpartywebsite.com/api/GetCustomers",
        dataType: 'json',
        success: function(data) {
          $.each(data, function(i, v) {
             $('.output').append(v.firstName);
             $('.output').append(v.lastName);
          });
        }
      });
    </script>
    
    // To access individual record inside the array.
    console.log(data[0].firstName);

     

  16. I am retrieving data from a third party's API using AJAX method. I would like to do two things.

    1. Display the data records on a page.

    2. Create a pagination on the page to display records more efficiently. I am expecting to retrieve possibly hundreds of records. I can normally do this using PHP but since I am retrieving the records using AJAX, the pagination is gonna be a challenge. 

    First things first is to display the records. Here is my AJAX code.

    It displays the log data fine. But it doesn't display any data in the "output" div. And it gives this error in the console.

    Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at Object.success
    <div class="output"></div>
    
    <script>
      $.ajax ({
        type: 'GET',
        url: "https://3rdpartywebsite.com/api/GetCustomers",
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(data) {
          console.log(data)
    
          $newData = JSON.parse(data);
          $.each($newData, function(i, v) {
             $('.output').append(v.LastName);
             $('.output').append(v.FirstName);
          });
        }
      });
    </script>

     

    What am I doing wrong?

  17. This issue has been resolved. I did not have to do any hack tricks to make it work. The problem was simple.

    1. They provided the incorrect URL.

    2. All form required fields had to be filled out before submitting.

    3. Had to clear my browser's cache before doing a new test.

    Now it submits the form data to their API just fine.

  18. 1 hour ago, kicken said:

    Apparently you need to add the Content-length header yourself, PHP won't add it for you when passing body content.  The code I posted was just to get you on the right path, you'll have to troubleshoot/problem-solve yourself to get to a final working solution.

    Not necessarily.   Since most API's are REST based these days, most places in my experience don't really bother with an SDK.  At best, you get documentation of the end points and some example code.  At worst you get the "common use case" documentation and have to figure everything else out yourself.

    The general idea is that anyone that is going to be trying to implement said API knows how HTTP works and knows how to make HTTP requests.   If you're not well-versed on HTTP then you fall back to a library that can handle that part of it for you, which for PHP a popular choice these days is Guzzle.  It's still up to you to know what request to make and what data to pass however.

    If they have explicitly advertised their API as being AJAX compatible then maybe it is.  Maybe they just forgot to add the necessary CORS stuff.  Since you mention it's a private API, potentially created just for you, then this is a real possibility.

    If it's not advertised as being AJAX compatible though then calling it from javascript probably isn't intended and the missing CORS stuff is likely intentional.

    Yes it is a private API created just for us. Supposedly the only two compatible methods to submit the form are AJAX and CURL. The AJAX code you see is what they provided to submit the form.

    I will get more clarification from them tomorrow.

  19. 51 minutes ago, requinix said:

    "Verify" customers? The API endpoint is "createCustomer"...

    Here's the deal with Javascript: it's public. Everything is visible for someone to read. Anyone can pull up your HTML and Javascript, see the API call, and start to abuse that.
    I don't see a hidden input in the form for some sort of API key, but that means (a) there's supposed to be one and you haven't included it yet, or (b) the endpoint is not authenticated. Either way, it really doesn't sound to me like this is the sort of thing that should be run entirely from Javascript.

    "CreateCustomer" would create the customer and return the result message if it's successful or not. The verification will be done manually on their end and they will update this "Customer". At that point I use "GetCustomers" to retrieve that information and find out if it has been verified or not.

    There is no API key provided. It's strictly submitted through that URL they provided. The form field names are exactly as they wanted. AJAX is one of the methods to submit the form. The other one is CURL but i'm not familiar with that.

    Now that you mentioned it, yeah this method doesn't seem safe.

  20. 34 minutes ago, requinix said:

    Er, I missed this before.

    Whose API are you trying to use?

    Not sure if i'm allowed to say the company but they are giving a private access to their API that's not available to others. It's essentially to verify customers. I send the data to their them via AJAX call.

    Here is the full code.

    <form id="submit-form" method="post" enctype="multipart/form-data">
               <fieldset>
               <label>Last Name *</label>
               <input type="text" name="LastName" maxlength="300" placeholder="Last Name" />
               </fieldset>
               <fieldset>
               <label>First Name *</label>
               <input type="text" name="FirstName" maxlength="300" placeholder="First Name" />
               </fieldset>
               <fieldset>
               <label>Date Of Birth *</label>
               <input type="text" name="DateOfBirth" id="datepicker2" placeholder="Choose a date" />
               </fieldset>
               <fieldset>
               <label>Phone Number *</label>
               <input type="tel" name="PhoneNumber" maxlength="50" placeholder="123-4567-8901" />
               </fieldset>
               <fieldset>
               <label>Email Address *</label>
               <input type="email" name="EmailAddress" maxlength="100" placeholder="Email Address" />
               </fieldset>
               <fieldset>
               <label>Company Position *</label>
               <select class="select-category" name="CompanyPosition" >
                 <option value="">Select</option>
                 <option value="President">President</option>
                 <option value="Director">Director</option>
               </select>
               </fieldset>
               <fieldset>
               <label>Legal Company Name *</label>
               <input type="text" name="LegalCompanyName" maxlength="500" placeholder="Legal Company Name" />
               </fieldset>
               <fieldset>
               <label>Doing Business Name As *</label>
               <input type="text" name="DoingBusinessAsName" maxlength="500" placeholder="Doing Business Name As" />
               </fieldset>
               <fieldset>
               <label>Corporate Registration Jurisdiction *</label>
               <select class="select-category" name="CorporateRegistrationJurisdiction" >
                 <option value="">Select</option>
                 <option value="USA" >USA</option>
                 <option value="Canada" >Canada</option>
               </select>
               </fieldset>
               <fieldset>
               <label>Business Address *</label>
               <input type="text" name="BusinessAddress" maxlength="500" placeholder="Business Address" />
               </fieldset>
               <fieldset>
               <label>Photo ID *</label>
               <input type="file" name="PhotoId" class="input-image">
               </fieldset>
               <fieldset>
               <input type="submit" name="submit" value="Submit" />
               </fieldset>
             </form>
            <script>
               var url = "https://3rdpartywebsite.com/api/CreateCustomer";
    
               $('#submit-form')
                 .submit(function (e) {
    
                   $.ajax ({
                     url: url,
                     type: 'POST',
                     data: new FormData(this),
                     processData: false,
                     contentType: false,
                     success: function(data) {
                       alert(data.message);
                     }
                   });
                   e.preventDefault();
                 });
             </script>

    That is the code example they showed me. It should work without me doing anything else. But I get that "...blocked by CORS policy" error in the inspect console.

  21. 58 minutes ago, requinix said:

    When you put those Proxy commands kicken's gave you into your .htaccess, you said you got an internal server error. What do the server logs have to say about why there was an internal server error?

     

    kicken gave you the "simplest thing" that could work. Evidently their API is not a simple thing.

     

    Says who? The internet isn't some plug-and-play thing. You can't wave a magic wand and suddenly have your site start talking to another site, just like how I can't travel to Finland and suddenly be able to speak Finnish.
    It will take some degree of work to make this happen.

    I just meant that an API integration should be pretty straightforward process instead of having to find certain hacks to try and make it work.

    This is my first time dealing with an API that's not SDK based. I guess the issue is mainly on their end.

  22. 3 hours ago, kicken said:

    It could look like many things, depending on what you need to accomplish.  The simplest thing would just be something like:

    
    <?php
    
    $url = 'https://3rdpartywebsite.com/api';
    $context = stream_context_create([
    	'http' => [
    		'method' => 'POST'
    		, 'content' => file_get_contents('php://input')
    	]
    ]);
    
    echo file_get_contents($url, false, $context);

    Basically you just have PHP make the request to the API via whatever means (native streams, cURL, guzzle, etc) and return the result back.

     

    The above code echos an error.

    Warning: file_get_contents(https://3rdpartywebsite.com/api): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required in

    Though I should mention that I am trying to create a customer. So the full url is like this "https://3rdpartywebsite.com/api/createCustomer"

     

    Still I shouldn't have to go through all this trouble to make a simple AJAX call to a third party API.

  23. 30 minutes ago, requinix said:

    That's not weird. It's only the larger companies that tend to provide SDKs for developers. Most of the time all you have to work with is documentation.

     

    Sounds like you don't have mod_proxy installed. If you control the server then you'll have to install that module first. If you don't, and if your hosting provider doesn't give you a way to enable features like mod_proxy, then you might have to go with a pure PHP solution.

    I see.

    So what would a pure PHP solution look like?

    My hosting provider is telling me that mod_proxy is already installed on the server. So could it be something else?

  24. 3 hours ago, kicken said:

    Instead of requesting the third-party API directly in your script you request a resource on your domain then you have your server forward that request to the third-party.

    So, for example, your XMLHttpRequest would be to the URL http://yourdomain.com/third-party/api

    Then on your server you could either make that point to a PHP script that runs the third-party request and returns the result, or configure your server to proxy the request with something like:

    
    ProxyPass /third-party/api "https://3rdpartywebsite.com/api"
    ProxyPassReverse /third-party/api "https://3rdpartywebsite.com/api"

     

     

    The thing is this is not a typical API integration. The third party does not provide any API files to added to the server. 

    The only way to connect to this particular third party's API is through a host url they provided.

    Here is my original ajax code to submit the form's info to that API.

    <script>
                var url = "https://3rdpartywebsite.com/api";
    
                $('#submit-form')
                  .submit(function (e) {
    
                    $.ajax ({
                      url: url,
                      type: 'POST',
                      data: new FormData(this),
                      processData: false,
                      contentType: false,
                      success: function(data) {
                        alert(data.message);
                      }
                    });
                    e.preventDefault();
                  });
              </script>

     

    In your example, are you prosing that I should change the url to this?

    <script>
                var url = "http://yourdomain.com/third-party/api";
    
                $('#submit-form')
                  .submit(function (e) {
    
                    $.ajax ({
                      url: url,
                      type: 'POST',
                      data: new FormData(this),
                      processData: false,
                      contentType: false,
                      success: function(data) {
                        alert(data.message);
                      }
                    });
                    e.preventDefault();
                  });
              </script>

     

    And where do I add the two "ProxyPass" lines on the page? In .htaccess file? Because if I do that, it gives me an internal server error.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.