Jquery Ajax Post to PHP

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.

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 );
});

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
}
}

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.

Sending POST parameters between PHP files using AJAX calls

A slightly different version of the above which should help you solve your problem. For ease in debugging it is all one page but you can clearly see the script in operation once you click the button. Simply echoing javascript in the php code and hoping it will execute client side is not going to work - simply echo a message or a JSON object would be better.

<?php

if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();

print_r( $_POST );

exit();
}

?>
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>

</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<script>
$('#link').click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: location.href,
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}

});
alert('function end');
});
</script>
</body>
</html>

As 2 separate pages ( both in same directory otherwise edit page to the ajax target )

<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>

</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<br /><br />
<script>
$('#link').click(function(e) {
e.preventDefault();

$.ajax({
url: 'jquery-ajax-target.php',
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
});
</script>
</body>
</html>

And the ajax target, jquery-ajax-target.php

<?php

if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();

$parameter1=( isset( $_POST['parameter1'] ) ) ? $_POST['parameter1'] : false;
$parameter2=( isset( $_POST['parameter2'] ) ) ? $_POST['parameter2'] : false;

$_POST['modified']=array(
'p1'=>sprintf('modified %s', strrev( $parameter1 ) ),
'p2'=>sprintf('modified %s', strrev( $parameter2 ) )
);

$json=json_encode( $_POST );
echo $json;

exit();
}

?>

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 POSTing 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.



Related Topics



Leave a reply



Submit