Simple PHP AJAX script
It submits or reloads the page. You need to prevent the default action. Change the first two lines:
$("#display").click(function(e) { // Add e (event) parameter.
e.preventDefault(); // Prevent the default action for this event.
You may change to type="button"
, but not sure if it will be effective.
AJAX GET simple PHP Multiple variables
In your PHP:
<?php
echo json_encode(Array(
'name' => "John",
'phone' => "1234567890",
'details' => "Details about..."
));
Your HTML:
<div class="name">Your Name is : <span class="name_value"></span></div>
<div class="phone">Your Phone Number is : <span class="phone_value"></span></div>
<div class="details">Your Details are : <span class="details_value"></span></div>
Your jQuery:
$(document).ready(function(){
$.getJSON('user-info.php',function(data){
$(".name_value").html(data.name);
$(".phone_value").html(data.phone);
$(".details_value").html(data.details);
});
});
Note: you'll set the user-info.php
string to the URL (relative or absolute) of your PHP script that grabs the user info.
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.
Simple Ajax request with php
Try this
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
</body>
</html>
front.js:
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(result) {
$('body').html(result);
});
});
back.php:
<?php echo $_POST['name']; ?>
Submitting basic form data with AJAX to PHP web service
In the success handler you want to catch the data
returned by the ajax call, then output it on the page using $('#results').html(data)
. Additionally, if desired, you want to hide the form using $('#submit').hide()
. Your code should then look like this:
$(document).ready(function () {
$("#submit").on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'results.php',
data: $(this).serialize(),
success: function (data) {
$('#results').html(data);
//$('#submit').hide();
}
});
});
});
Then you should add the following div
to your page:
<div id="results">Results will go here</div>
Simple PHP/AJAX question
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click")
. Then initiate an ajax call $.post
which you will send data to. This data is received on the server via the POST array.
Simple Crud Using AJAX/JQUERY
You MySQL query doesn't have hospital column. Below query should have hospital name column
$query = "INSERT INTO users(first_name, last_name, email, work, MISSING_COLUMN) VALUES('$first_name', '$last_name', '$email', '$work', '$hospital_name')";
Related Topics
How to Remove All Non Printable Characters in a String
Get Specific Columns Using "With()" Function in Laravel Eloquent
What's the Difference Between Isset() and Array_Key_Exists()
Replacing Accented Characters PHP
"Connect Failed: Access Denied For User 'Root'@'Localhost' (Using Password: Yes)" from PHP Function
How to Solve "Fatal Error: Class 'MySQLi' Not Found"
Why Is the Hash Part of the Url Not Available on the Server Side
How to Get Count of Rows in MySQL Table Using PHP
PHP - How to Create a Newline Character
Are PHP Variables Passed by Value or by Reference
How to Extend a Class Using More Than 1 Class in PHP
How to Catch Curl Errors in PHP
Preserve Line Breaks from Textarea
Special Characters in Property Name of Object
How to Perform Static Code Analysis in PHP
What's the Difference Between :: (Double Colon) and -≫ (Arrow) in PHP