1

I use scala.js with scala.js-react. In order to send ajax request, I wrote something like:

def send(e: ReactEventFromInput) = Callback{
  val v = e.currentTarget.value
  val formData = new FormData()
  formData.append("myVar", v)

  val xhr = new XMLHttpRequest
  xhr.onreadystatechange = (e: org.scalajs.dom.Event) => {
    if (xhr.readyState == XMLHttpRequest.DONE) {
      if (xhr.status == 200) {
        println("Sended!")
      } else {
        println("Error!")
      }
    }
  }

  xhr.open("POST", "/my-api-route", true)
  xhr.setRequestHeader("X-Requested-With", "XMLHTTPRequest")
  xhr.send(formData)
}

It works, but code is terribly long.

Does it provides fetch method like javascript fetch?

P.S. Sorry for my English, it's not my native

1 Answer 1

1

Found the Ajax object:

def send(e: ReactEventFromInput) = Callback{
    val v = e.currentTarget.value
    val formData = new FormData
    formData.append("myVar", v)

    Ajax.post("/my-api-route", formData) map (r =>
      println("Sended!")
    ) onFailure {
      case dom.ext.AjaxException(r) => println("Error:" + r.response)
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Where is the Ajax object? (The import)
org.scalajs.dom.extensions, unless I'm mistaken,

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.