0

I have a html form:

<form method="post" action="apiCalls.php">
    <input type="hidden" name="token" value="ghf823y932yd928u">
</form>  

I want to submit this form (so the request get sent to the php script) but without redirecting the page. I tried a lot of things like $.post, $.ajax, form.submit prevent defaults, etc., but without resolving my problem.

2 Answers2

0

What you want is an ajax request

  1. Fetch all the values from your form and put them in a dictionary. See Serialize form data to JSON
  2. Then use jQuery.post and send those values to apiCalls.php.

Something like

// getFormData is defined in the referenced SO post
data = getFormData($("form"))
$.post("apiCalls.php", data)
Andrei Cioara
  • 3,404
  • 5
  • 34
  • 62
  • I did it like this: $.post('apiCalls.php', {token: 'h8934fh9834f'}); Thanks! One more question - why I can't see the request in Network tab in dev tools? – d1qwd3674wef Mar 21 '18 at 23:07
  • You should be able to see it. Try refreshing the page, the network tab has to be active (already open) when you first load the page. – Andrei Cioara Mar 21 '18 at 23:13
  • Yeah, I know it must be active, I just had JS filter by default. Thank you again. – d1qwd3674wef Mar 22 '18 at 07:55
0

You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.

AjaxForm:

$("#formID").ajaxForm({url: 'apiCalls.php', type: 'post'})

Serialize:

$.post('apiCalls.php', $('#formID').serialize())

Also have a look at following resources:

  1. AJAX serialization documentation.
  2. jQuery AJAX submit form
Sumit Jha
  • 1,601
  • 11
  • 18