0

When I request different data than pressing select, it does not perform a single operation, and when they are combined, only one operation is performed,

It does a process called getStatesByCountryId but it doesn't call get_shipping_price, and because I'm requesting information from two different tables I can't merge them,

And when we merge them, the information is not sent to the span text, so I preferred to separate them,

I using a php codeigniter framework

javascript code:

$("select[name='country']").change(function () {
  var countryId = $(this).val();
  $.ajax({
    url: "/Ajax/getStatesByCountryId",
    method: "post",
    data: { countryId },
    success: function (data) {

        var rJson = $.parseJSON(data);
        if (rJson.status === true) {
          $("select[name='state']").html("");
          
          $.each(rJson.data, function (e, v) {
            $("select[name='state']").append(
              "<option value='" + v.id + "'>" + v.name + "</option>"
            );
          });
        } else {
          $("select[name='state']").html("");
        }
    }
  });
});




$("select[name='country']").change(function () {
    var countryname = $(this).val();
    $.ajax({
        url: "/Ajax/get_shipping_price",
        method: "post",
        data: { 'countryname': countryname },
        success: function (data2) {
        if (data2) {
        $("span[name='shipping_price']").text(data2.shipping_price);
        } else {
        $("span[name='shipping_price']").text("");
        }
        }
    });
});

Ajax Code:

public function get_shipping_price()
{
  $countryName = $this->request->getPost("countryname");
  $result = $this->con->query("SELECT shipping_price FROM table2 WHERE country = '{$countryName}'")->getResult();

  if ($result) {
    $data2 = array('shipping_price' => $result[0]->shipping_price);
  } else {
    $data2 = array('shipping_price' => 0);
  }

  echo json_encode($data2);
}




  public function getStatesByCountryId()
{
    $countryId = $this->request->getPost("countryId");
    $states = $this->con->query("select * from table where ID = {$countryId}")->getResult();
    if ($states) {
        $data = [
            "status" => true,
            "data" => $states
        ];
    } else {
        $data = [
            "status" => false
        ];
    }
    
    echo json_encode($data);
}

and here respon:

enter image description here

FREE SPEED
  • 19
  • 1
  • 1
    Maybe you can chain them and call one after the other.I don't think you can trigger two different `onChange` functions for the same element. Check this answer - https://stackoverflow.com/a/16045729/3183454 – the.marolie Feb 13 '23 at 20:56
  • _"because I'm requesting information from two different tables I can't merge them"_ - of course you could ... Just add the two different sets of data to your data structure that your are eventually encoding as JSON, under two different keys ... – CBroe Feb 14 '23 at 07:14

0 Answers0