views:

198

answers:

2

Here a sample use case:

I request a simple form via an ajax request. I want to submit the result to the same page that I requested. Is there a way to access the URL of that request in the resulting request's javascript?

Below is some code that accomplishes what I want via javascript AND PHP. The downside to this is that I have to include my javascript in the same file as myajaxform.php. I'd rather separate it, so I can minify, have it cached etc.

I can't use location.href, b/c it refers to the window's location not the latest request.

frm.submit(function () {
 if (frm.validate()) {
     var data = frm.serialize();
     jQuery.ajax({
      url : '<?= $_SERVER['PHP_SELF'] ?>',
      type : 'POST',
      data : data,
                dataType: "html",
      success : function (data) {

      }
     });
 }
 return false;
});

If there's not a way to access it via javascript directly, how would you solve this problem so that the javascript can go in it's own file? I guess that I could in the original ajax request's success handler, create some sort of reference to the URL. Thoughts? Maybe something using the jQuery data method?

A: 

Forgive me if I totally misinterpret your question, as I find it somewhat confusing. What about

frm.submit(function () {
    if (frm.validate()) {
        var data = frm.serialize();
    jQuery.ajax({
            url : window.location.href,
            type : 'POST',
            data : data,
            dataType: "html",
            success : function (data) {

            }
    });
    }
    return false;
});
Jamie
window.location.href would refer to the window's location, not the URL of the ajax request ... thx though
Keith Bentrup
+3  A: 

You can store the url to submit to in the action attribute of the form, and then set the url to frm.action:

jQuery.ajax({
             url : frm.action,
             type : 'POST',
             data : data,
             dataType: "html",
             success : function (data) {
            }
});
Rudd Zwolinski
ah, yes ... simple, obvious answer. just <form action="<?= $_SERVER['PHP_SELF'] ?>" first ... :Pthanks!
Keith Bentrup