Home > OS >  jQuery AJAX - Display responses HTML as a page
jQuery AJAX - Display responses HTML as a page

Time:10-03

I'm using jquery ajax in this way:

$.ajax({
    url: url,
    type: "POST",
    data: data,
    success: function (response) {
        if ( foo ) {               
            alert("foo happened");
            // do stuff
        } else if (bar) {        
            // ??? display response as page ???
        }
    },
    error: { .... }
    }
});

Basically, in case of "foo" I do some ajax stuff on the page, but in case of "bar" I receive a fully-formed page that I simply want to display as-is. As if, basically, I had just clicked a submit button and the browser just did its normal thing with the response received from the server.... Any jQuery/JavaScript function to do that?

In other words, how I can just sort of "forward" the response to the browser so that it gets treated by it normally?

CodePudding user response:

When you are using ajax you can't refresh the whole page, you can only refresh the partial view that should be defined inside of the main view . if you try to return the whole you will get a layout with it too

<div id="myPartialView">
  @Html.Partial("_MyPartialView",Model)
 </div>

ajax

$.ajax({
        
            url: "/MyController/MyAction",
            type: "POST",
            data: {myData:myData}
            success: function (result) {
                    $("#myPartialView").html(result);
            },
            error: function (xhr, exception) {
               
            }
        });

and the action

public partial class MyController : Controller
{
  public IActionResult MyAction(MyData myData)
  {
      ... some code
      var model = new myModel { ... assign model properties  };
     return PartialView("_MyPartialView", model);
 }
}

PS.

if you don' t use MVC you still should have this html

<div id="myPartialView">
  
 </div>

but ajax will be the same.

  • Related