0

I try lots of ways to convert my XMLHTTPRequest into jQuery ajax but I couldn't be successful.

I would be really appreciate if anyone could help me solve this issue.

here is my XMLHttpRequest Code:

    var url = url;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url);    
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
    xhr.onreadystatechange = function () {
       if (xhr.readyState === 4) {
           console.log(xhr.status);
           console.log(xhr.responseText);
    }};
    
    var data = "ajax=1";  
    xhr.send(data); 

and here is my attempt but its not working

$.ajax({
             url: "<?php echo $this->ui_url('onlineexamcats', 'all'); ?>",
             data: JSON.stringify("ajax=1"),
             type: "POST",
             processData: false,
             contentType: false,
             beforeSend: function(xhr){xhr.setRequestHeader('Content-Type',  "application/x-www-form-urlencoded");},
             success: function(res) { console.log(res); }
          });
2
  • What was your attempt? Should be straight forward. api.jquery.com/jquery.post Commented May 19, 2022 at 20:39
  • I just edit my question you can see my ajax code @epascarello Commented May 19, 2022 at 20:43

1 Answer 1

1

Try this

$.ajax({
    url: "<?php echo $this->ui_url('onlineexamcats', 'all'); ?>",
    data: "ajax=1",
    type: "POST",
    processData: false,
    success: function(res) { console.log(res); }
});
Sign up to request clarification or add additional context in comments.

4 Comments

thanks but I need to post my data as raw string and contentType: "application/x-www-form-urlencoded"
@FarzaneKhazaei you mean you want to send the data as ajax=1 instead of {ajax: 1}?
exactly! @ruleboy21
@FarzaneKhazaei I've updated my answer. Kindly check it out. Note that application/x-www-form-urlencoded is the default contentType that is why I ignored. But you can still set it manually if you like.

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.