3

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.

$("#launchId").live('click',function(){
    var id= $("#id").val();
    var data = 'id='+id;
    $.ajax({
        url: "xyz.json",
        type: "post",
        data: data,
        dataType: 'json',
        complete : function(response) {
             window.location.href = response;                  
        }
    });
 });
hemanth
  • 35
  • 1
  • 2
  • 11

5 Answers5

3

Please try this.

var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Ramaraj Karuppusamy
  • 2,350
  • 5
  • 24
  • 35
3

Not using ajax would make this easier:

<form type="POST" action="xyz.json">
    <label for="id">Enter ID:</label><input id="id" name="id">
    <button type="submit" id="launchId">Send</button>
</form>

If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.

If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:

$.ajax({
    url: "xyz.json",
    type: "post",
    data: data,
    dataType: 'html', // it's no JSON response!
    success: function(response) {
         document.write(response); // overwrite current document
    },
    error: function(err) {
         alert(err+" did happen, please retry");
    }
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Your response is an object containing the full HTML for a page in the responseText property.

You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.

...
complete : function(response) {
    $(body).html(response.responseText);
}

But i suggest you don't and there could be style and other conflicts with whats already there on the page.

techfoobar
  • 65,616
  • 14
  • 114
  • 135
0

In your HTML add a div with id as 'content', something like this

<div id='content'/>

Since your response is html in your complete function append the content into the div like this -

 complete : function(response) {
         $('#content').append(response.responseText);
    }

Let me know if you still face issues.

tusharmath
  • 10,622
  • 12
  • 56
  • 83
-2

try this

$("#launchId").live('click',function(){
    var id= $("#id").val();
    var data = 'id='+id;
    $.ajax({
        url: "xyz.json",
        type: "post",
        data: data,
        dataType: 'json',
        complete : function(response) {
             window.location.href = '/yourlocation?'+response;                  
        }
    });
 });