Ajax post with jQuery

Is it possible to send an identifier with the POST method when an element is clicked? I think jQuery has an AJAX built-in fan ...

<span id="submitThisID"></span> 
+1
source share
5 answers
 $('#submitThisId').click(function() { $.post("postTo.php", { id: $(this).attr('id') }, function(response) { alert(response); }); }); 

This will send your identifier to postTo.php and can be restored using: $id = $_POST['id'];

No matter which postTo.php file is returned, a warning will be displayed on the screen (response).

EDIT: In order to send to the same page and perform some server-side actions (db request, etc.), you will need to place something similar to the following code at the top of the page:

 <?php if (isset($_POST['id'])) { $id = $_POST['id']; // Perform some db queries, etc here $response = 'Format a response here'; // Format a response // This will return your formatted response to the $.post() call in jQuery return print_r($response); } ?> 

When this β€œresponse” (text, html, etc.) returns to jQuery, you can use simple jQuery to insert it on the page where necessary and change the appearance of the page.

+2
source
 #submitThisID.post( 'http://example.com/', { 'foo': 'bar', }, function (data) { console.log( 'data: ' + data ); } ); 
+1
source

This is definitely possible: $.post() .

However, your question does not make sense. Presented values ​​in HTTP messages accept name / value pairs. An example POST body might look like this:

 Name: Jonathan Doe Age: 23 

Will the item id be a name or value? What will be the other?

+1
source

Yes, read the following: http://api.jquery.com/jQuery.post/

0
source
  $('#submitThisID').click(function({ var id = $(this).attr('id'); $.ajax({ url:'/index.php/ajax/', type:'post', dataType:'json', data:{ id:id; }, success:function(data){ console.log('ajax success!'); } }); }); 
0
source

Source: https://habr.com/ru/post/1341921/


All Articles