简体   繁体   中英

Submit POST method without a form?

I need to make a button with a similar functionality to "Follow" buttons in social networks. The thing is I need to refresh the page when the user clicks the button since the page content largely depends whether the user is following or not.

I could submit the "follow" with ajax and reload the page when ajax responds. Is it possible to submit data with POST without AJAX (like forms do)?

With JQuery you can do something like

$.post('pageurl.php', {"variable1": "Value1", "Variable2": "Value2"}, function(datareturn){});

And handle it from serverside like normal

$var1 = $_POST["varriable1"];

Depending on the amount of data to be submitted, a regular link can submit data as well.

This, for example, submits the search term this and that

https://www.google.com/search?q=this+and+that

you can create your form dynamically and then remove it:

function postjs (to,method, p) {
  var myForm = document.createElement("form");
  myForm.method=method;
  myForm.action = to ;
  for (var k in p) {
    var myInput = document.createElement("input") ;
    myInput.setAttribute("name", k) ;
    myInput.setAttribute("value", p[k]);
    myForm.appendChild(myInput) ;
  }
  document.body.appendChild(myForm) ;
  myForm.submit() ;
  document.body.removeChild(myForm) ;
}

and call it:

postjs('target.php','post',{field1:'value1',field2:'value2'})

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