简体   繁体   中英

JQuery button takes url and submits php form

I run an application that shortens urls for authenticated users. The form for this application is simply an input for the full url, which then spits out a shortened url.

I would like to build a button that can be added to generated pages (the urls are long and messy) and once clicked would automatically submit the url shortening form.

The url shortening application is run in php. I've read a little bit about using ajax to submit the form. Does this matter if it's on a different website? Does anyone have a good tutorial or starting point for this sort of thing?

Many thanks!

edit to include code:

<form action=""  method="post">
  <label for="form_url">Which URL do you want to shorten?</label>
  <input type="url" id="form_url" name="form[url]" required="required" value="http://">
  <input type="hidden" name="form[_token]">
  <button type="submit" role="button">Shorten URL</button>
</form>



$(document).ready(function() {
  $('a.btn').click(function() {
  var pathname = window.location;

  $.ajax({
    type: "POST",
    url: 'http://url',
    data: $(pathname).serialize,
    success: success,
    dataType: text
  }); 
});
});

There isn't much to go on, considering you didn't post any code, but what I think you're asking is:

<form id="myForm" method="post">
    <input type="text" name="long_url"/>
    <input type="submit" value="Send"/>
</form>

Now in the Javascript, you'd capture the submit event and call and ajax request:

$("#myForm").submit(function(e){
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: "urlOfPhp",
        data: $("#myForm").serialize(),
        success: function(returned_data) {
            // Handle Success Here.
        }
    }).error(function(){
        // Handle an Error Here.
    });
}); 

And that's the basics of Ajax. I'm also not clear on the Generated pages button thing, but this is a good starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM