jQuery Ajax POST example with PHP
Basic usage of .ajax
would look something like this:
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
jQuery:
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
Note: Since jQuery 1.8, .success()
, .error()
and .complete()
are deprecated in favor of .done()
, .fail()
and .always()
.
Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready()
handler (or use the $()
shorthand).
Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();
PHP (that is, form.php):
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;
Note: Always sanitize posted data, to prevent injections and other malicious code.
You could also use the shorthand .post
in place of .ajax
in the above JavaScript code:
$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.
Jquery AJAX post to PHP
Why don't you try constructing your data like this
var postData = {};
$('#items tr').not(':first').each(function(index, value) {
var keyPrefix = 'data[' + index + ']';
postData[keyPrefix + '[supp_short_code]'] = $(this).closest('tr').find('.supp_short_code').text();
postData[keyPrefix + '[project_ref]'] = $(this).closest('tr').find('.project_ref').text();
// and so on
});
Then in your AJAX call
data: postData,
Now your PHP script can process the data as a multi-dimensional array
<?php
if (isset($_POST['data']) && is_array($_POST['data'])) {
foreach ($_POST['data'] as $row => $data) {
echo $data['supp_short_code'];
echo $data['project_ref'];
// and so on
}
}
How to POST data to php file using AJAX
When using Ajax, the request is sent by ajax and you can see the response in the success method. Any direct call to the action URL will sends new request which is empty in this case for the line
window.location.assign("http://localhost:8888/checkout.php")
Remove that line of code and change your jQuery.Ajax like bellow to see what's the response.
var request = $.ajax({
type: "POST",
url: "http://localhost:8888/checkout.php",
data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Using jquery $.ajax to PHP post GET values
You can put the data into a data section, I think that will solve your problem.
$.ajax({
url : '../command/test.php',
data: {command: "apples",login: "succes"}
}).done(function(data) {
console.log("result: " + data);
});
Also, you can see what you get as a response, open developer tools and you can see under network
your request appearing when made, click on that and you can see the response.
AJAX POST & PHP POST In Same Page
Finally after waiting more than 7 days trying to figure this out, I couldn't AJAX post
to the same page probably because there are too much of <html>
elements already in the same page. But here goes it using an external post.php
file. Only these changes were required for me to get this working other than mentioned in my original question above.
<script>
$(function()
{
$('#drpcategory').change(function()
{
$.ajax({
method: 'post',
url: 'post.php',
data: $(this).serialize(),
success: function(data)
{
$('#drpitem').html(data);
}
});
});
});
</script>
Then I had to save this post.php
in the root website directory where index.php
is located. Change your directory as necessary and also remember to change the url
field in the above AJAX function.
<?php include 'config.php';?> //this is where the $dir variable is derived in my website. i had to include this since post.php is an external file that doesn't know about the variable.
<?php
$category = $_POST["drpcategory"];
$item = ''.$dir.'/template/post/'.$category.'/item.txt';
$item = file($item, FILE_IGNORE_NEW_LINES);
foreach($item as $item)
{
echo "<option value='".$item."'>$item</option>";
}
?>
Thank you for each and everyone of you for walking me through this. I would have marked someone of you as the answer if a direct answer was given but if someone already given this, I'm sorry for not understanding you properly. But I think the end goal is for someone to use this as help.
Sending POST data to PHP script - jQuery, AJAX & PHP
Looking over your code, it seems like you are getting null because you are requesting the fetchpost.php
script twice. Once when you contact the script via $.ajax(...);
and once more when you call $.getJSON(...);
. When you contact via $.getJSON(...);
, though, you are not POST
ing data and it seems like your script does not have a properly defined way to handle GET
requests, so the script doesn't know how to react and it returns null information.
I would change the JavaScript/jQuery to the following:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: {'editpostid': jsonObj },
success: function(sData) {
var data = JSON.parse(sData);
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
},
error: function( e ) {
console.log(e.message);
}
});
});
Additionally, PHP is going to be expecting an application/x-www-form-urlencoded
value to be able to interact with $_POST[...]
. As such, if you want to feed it JSON, then in your PHP, you will need to implement a solution such as: $postedData = json_decode(file_get_contents('php://input'));
(See more about that in this answer; for more about json_decode
, see the official PHP documentation for json_decode.)
Note: While outside of the scope of your question, and you may know this already, I find it important to point out that your MySQL is insecure and vulnerable to SQL injection due to just blindly trusting that the postId
has not been tampered with. You need to sanitize it by saying $postid = $dbconnect->real_escape_string($postid);
after you initialize $dbconnect
and connect to the database, but before you put the $postid
into your SQL query string.
Perform AJAX post request to the same PHP page (Jquery Form Plugin)
I build a sample in local with your code, there is no problem with ajax or new post request on complete. the two change that I made is this:
in form set action
<form id="jquery-form-plugin-test-id" class="form" action="test.php" method="post" novalidate="novalidate">
because I want to see what params post and pass 404 error.
and
change input name for description :
<input class="form-control" id="id_description" maxlength="30"
name="desc" placeholder="Project Description" required="required" title="" type="text" />
for sending as a separated param.
you can try your self :
test.php file:
<?php
var_dump($_POST);
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
(function ($) {
$('#jquery-form-plugin-test-id').ajaxForm({
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];
alert('About to submit: \n\n' + queryString);
$('#result').text(queryString);
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property
// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property
// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server
//$('#result').text(statusText);
alert("Submitted");
$.ajax({
url: 'https://reqres.in/api/users?page=2',
method : 'GET',
success : function (data){
result.html(result.html()+JSON.stringify(data));
}
})
}
}(jQuery));
});
</script>
</head>
<body>
<div id="result"></div>
<form id="jquery-form-plugin-test-id" class="form" action="test.php" method="post" novalidate="novalidate">
<div class="form-group required row">
<label class="col-md-2 col-form-label">Name</label>
<div class="col-md-4">
<input class="form-control" id="id_name" maxlength="30" name="name"
placeholder="Project Name" required="required" title="" type="text" />
</div>
</div>
<div class="form-group required row">
<label class="col-md-2 col-form-label">Description</label>
<div class="col-md-4">
<input class="form-control" id="id_description" maxlength="30" name="desc"
placeholder="Project Description" required="required" title="" type="text" />
</div>
</div>
<div class="form-actions">
<button type="submit" name="submit" class="btn btn-primary" id="register-submit-btn">
<span class="fa fa-plus"></span> Create
</button>
</div>
</form>
</body>
</html>
and you see in network tab that params send successfully. even the second post request look like well.
Related Topics
Removing or Replacing a Stylesheet (A ≪Link≫) With JavaScript/Jquery
How to Access and Process Nested Objects, Arrays, or Json
Animating Addclass/Removeclass With Jquery
Add Active Navigation Class Based on Url
Select All Elements That Have a Specific Css, Using Jquery
How to Pause and Resume Css3 Animation Using JavaScript
How Do JavaScript Closures Work
Dynamically Access Object Property Using Variable
Using Async/Await With a Foreach Loop
What Is the Most Efficient Way to Deep Clone an Object in JavaScript
How to Access CSS Generated Content With JavaScript
How to Loop Through or Enumerate a JavaScript Object
How to Include a JavaScript File in Another JavaScript File
From an Array of Objects, Extract Value of a Property as Array
Accessing Nested JavaScript Objects and Arrays by String Path
Get Computed Font Size For Dom Element in Js
How to Preserve Line Breaks When Getting Text from a Textarea