0

I am checking out an order in WordPress via jQuery AJAX. Upon successfully posting, WordPress returns a response to me with a result success value and url value.

I want to get the particular part of this url so I can use the id as an object for my purpose.

This is the structure of the url:
http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459

This is my current code:

j('.my-checkout').on('submit', function(evt) {
  evt.preventDefault();

  var billing_customer_type = j("#billing_customer_type").val();
  // and so on...

  j.ajax({
    type: 'POST',
    url: 'http://localhost/mywebsite/ajax=checkout',
    cache: false,
    data: {
      'billing_customer_type': billing_customer_type,
      // and so on..
    },
    success: function(result) {
      var orderResponseUrl = result.redirect;

      j('.order-response-url').html(orderResponseUrl);
      // http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459

      orderResponseUrl.split("/");
      console.log(orderResponseUrl[3]);
    },
    error: function(xhr, status, error) {
      console.log(error);
    },
    complete: function() {}
  });
});

The result of my code above is just the the letter "p". I think because it started of the first letter of http and I used the index [3].

Do you know how can I get the specific part of the url that is 28564?

0

3 Answers 3

1

If the URL that you need to interact with is always the same, you can split the returned url at the 'order-received/' portion (which gives an array of everything before that, and everything after it).

Then rather than splitting again on the '?" which is another way of doing it - you can use parseFloat() to get the order number. This works since parseFloat returns all numerical values up to but not including the first non-numerical character ("?").

var urlStr = 'http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459';

var orderNumber = parseFloat(urlStr.split('order-received/')[1]);
console.log(orderNumber); //gives 28564

Sign up to request clarification or add additional context in comments.

Comments

1

Because when you do orderResponseUrl.split("/"); it does NOT change orderResponseUrl, it creates a new array.

var parts = orderResponseUrl.split("/");
console.log(parts);

Comments

1

if the length is always same then you can use substring function.

var str = "Hello world!";
var res = str.substring(1, 4);

now res contain

console.log(res); // ell

if you do not know the index, you can find like this.

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");

now n look like

console.log(n); // 13

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.