I'm making a AJAX call and I'm trying to receive json from an array json_encode(), but doesn't seem to be working. Thanks for any help.
I'm not getting any errors and i've checked some other stackoverflow questions, but can't find a complete example.
The problem is i'm nothing it going in to the div (#form_response) when the ajax is called and its returning everything from results
The response I get using the code below is:
{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}
HTML & AJAX:
<script type="text/javascript" src="js/jquery.js"></script>
<div class="" id="form_response"></div>
<form id="add_property_form" action="" method="POST">
<input type="text" name="input">
<button type="submit">Send</button>
</form>
<script type="text/javascript">
$("#add_property_form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'thescript.php',
type: 'POST',
data: formData,
async: false,
cache:false,
contentType: false,
processData: false,
dataType: "json",
success: function (data) {
$('#form_response').html(data);
}
});
return false;
});
</script>
thescript.php
header('Content-Type: application/json');
$success = true;
$false = false;
$results = array(
'success' => $success,
'complete' => '<div class="ser_mess">success</div>',
'error' => $false,
'error_msg' => array('empty' => '<div class="ser_mess">empty</div>',)
);
if(empty($_POST['input']) ){
$results['error'];
$results['error_msg']['empty'];
}else{
$results['success'];
$results['complete'];
}
echo json_encode($results);
exit();
My testing steps with your code. Resolving problems.
If you are submitting the data with an ajax request, then you don't want to natively submit the form. So, use just a button of type "button", not of type "submit". Statements like evt.preventDefault(); and return false are correctly used only when the form should be natively submitted (e.g. not through a button of type "submit", or similar) and, for example, you are validating it. If the user input is not valid, then you apply such statements, so that you can stop the form from submitting.
Your ajax doesn't start, because it's not included into a $(document).ready(function () {...}.
I receive "TypeError: 'append' called on an object that does not implement interface FormData. Use var formData = $('add_property_form').serialize(); instead of var formData = new FormData($(this)[0]);.
The async:false property gave the warning: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/ jquery-3.2.1.min.js:4:15845". So, remove async. Also, you don't need cache, contentType, processData. Remove them.
Since, by setting dataType: "json", you are already telling the server that you are expecting JSON encoded data back from the server, you don't need to send the response header with header('Content-Type: application/json');. Remove it.
Use method: "post" instead of type: "post", because the latter is used only up to version 1.9.0 of jquery. Read the ajax specification.
Your php code inside the if statements was error-prone. I made my version out of it.
If you are receiving JSON encoded data from the server, you can not directly pass it as html content into a div. You must read its values separately and do something with them. In analogy: in php you can also not simply write echo $results, because then you would receive Notice: Array to string conversion. The same is with the client-side code.
test.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#add_property_form").submit(function (evt) {
evt.preventDefault();
var formData = $('#add_property_form').serialize();
$.ajax({
url: 'thescript.php',
type: 'POST',
dataType: "json",
data: formData,
success: function (data, textStatus, jqXHR) {
var formResponse = $('#form_response');
var success = data.success;
var message = data.message;
if (success) {
formResponse.removeClass('error').addClass('success');
} else {
formResponse.removeClass('success').addClass('error');
}
formResponse.html(message);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
return false;
});
});
</script>
<style type="text/css">
.success,
.error {
max-width: 400px;
color: white;
margin-bottom: 15px;
}
.success {
background-color: green;
}
.error {
color: white;
background-color: red;
}
</style>
</head>
<body>
<div id="form_response" class="message"></div>
<form id="add_property_form" action="" method="POST">
<input type="text" name="input">
<button type="submit">Send</button>
</form>
</body>
</html>
thescript.php
<?php
if (empty($_POST['input'])) {
$results['success'] = false;
$results['message'] = 'No input value provided!';
} else {
$results['success'] = true;
$results['message'] = 'You provided the value ' . $_POST['input'];
}
echo json_encode($results);
exit();
Another example
Since you were looking for a complete example I took the liberty to create one for you.
The main point of it is to define an "error" callback for the ajax request. Because, when you throw errors, you actually want your ajax "error" callback take its role. For activating it, you just have to send a custom response header - having a status code of class "4xx: Client errors" - from the server (search.php) to the client (custom.js). Such a header is used like this: "Dear browser, I, the server, am sending you this response: 'HTTP/1.1 420 Please provide the city.'. As you see, its status code is 420, e.g. of class 4xx. So please be so kind and handle it in the 'error' callback of your ajax request". Here is the List ofStatus Codes.
You can run the code as it is. Create a folder in your document root, paste the files in it, then let test.php running.
test.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<!-- CSS resources -->
<link href="custom.css" type="text/css" rel="stylesheet" />
<!-- JS resources -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<div class="page-container">
<form class="user-input">
<div class="messages">
Here come the error/success messages
</div>
<div class="form-group">
<label for="city">City:</label>
<input type="text" id="city" name="city" placeholder="City">
</div>
<div class="form-group">
<button type="button" id="searchButton" name="submit" value="search">
Search
</button>
</div>
</form>
<div class="cities">
Here comes the list of the found cities
</div>
</div>
</body>
</html>
search.php
<?php
// Get the posted values.
$city = isset($_POST['city']) ? $_POST['city'] : '';
// Validate the posted values.
if (empty($city)) {
/*
* This custom response header triggers the ajax error because the status
* code begins with 4xx (which corresponds to the client errors). Here is
* defined "420" as the custom status code. One can choose whatever code
* between 401-499 which is not officially assigned, e.g. which is marked
* as "Unassigned" in the official HTTP Status Code Registry. See the link.
*
* #link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
header('HTTP/1.1 420 Please provide the city.');
exit();
} /* Other validations here using elseif statements */
/* The user input is valid. */
/*
* Perform the search operation in a database, for example, and get the data.
* Here just an array simulating a database result set with two records.
*/
$foundCities = [
[
'name' => 'Athens',
'isCapital' => 'is a capital',
],
[
'name' => 'Constanta',
'isCapital' => 'is not a capital',
],
];
// Print the response.
$response = [
'message' => 'Great. ' . count($foundCities) . ' cities were found.',
'cities' => $foundCities,
];
echo json_encode($response);
exit();
custom.js
$(document).ready(function () {
$('#searchButton').click(function (event) {
ajaxSearch();
});
});
function ajaxSearch() {
$.ajax({
method: 'post',
dataType: 'json',
url: 'search.php',
data: $('.user-input').serialize(),
success: function (response, textStatus, jqXHR) {
/*
* Just for testing: diplay the whole response
* in the console. So look unto the console log.
*/
console.log(response);
// Get the success message from the response object.
var successMessage = response.message;
// Get the list of the found cities from the response object.
var cities = response.cities;
// Display the success message.
displayMessage('.messages', 'success', successMessage);
// Display the list of the found cities.
$('.cities').html('');
$.each(cities, function (index, value) {
var city = index + ": " + value.name + ' (' + value.isCapital + ')' + '<br/>';
$('.cities').append(city);
});
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle the raised errors. In your case, display the error message.
handleAjaxError(jqXHR);
},
complete: function (jqXHR, textStatus) {
// ... Do something here, after all ajax processes are finished.
}
});
}
/**
* Display a user message.
*
* #param selector string The jQuery selector of a message container.
* #param type string The message type: success|danger|warning.
* #param message string The message text.
* #return void
*/
function displayMessage(selector, type, message) {
$(selector).html('<div class="message ' + type + '">' + message + '</div>');
}
/**
* Handle an error raised by an ajax request.
*
* If the status code of the response is a custom one (420), defined by
* the developer, then the corresponding error message is displayed.
* Otherwise, e.g. if a system error occurres, the displayed message must
* be a general, user-friendly one. So, that no system-related infos will be shown.
*
* #param jqXHR object The jQuery XMLHttpRequest object returned by the ajax request.
* #return void
*/
function handleAjaxError(jqXHR) {
var message = 'An error occurred during your request. Please try again, or contact us.';
if (jqXHR.status === 420) {
message = jqXHR.statusText;
}
displayMessage('.messages', 'danger', message);
}
custom.css
body {
margin: 0;
padding: 20px;
}
.page-container {
padding: 30px;
background-color: #f4f4f4;
}
.messages {
margin-bottom: 20px;
}
.message {
padding: 10px;
margin-bottom: 10px;
border: 1px solid transparent;
}
.success {
color: #3c763d;
border-color: #d6e9c6;
background-color: #dff0d8;
}
.danger {
color: #a94442;
border-color: #ebccd1;
background-color: #f2dede;
}
.warning {
color: #8a6d3b;
border-color: #faebcc;
background-color: #fcf8e3;
}
form {
width: 400px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: inline-block;
min-width: 40px;
}
button {
padding: 7px 10px;
margin: 10px;
display: block;
color: #fff;
font-size: 14px;
border: none;
background-color: #8daf15;
}
success: function (data) {
$('#form_response').html(data);
}
this block is your response handler - and data is the JSON object you're getting back from the AJAX call. if you want to display a particular attribute of your JSON object, you'll want to reference something like data.complete, which looks like a little bit of HTML, which you can then put into your div#form_response
success: function (data) {
$('#form_response').html(data.success);
}
you can access all of the object in the same way:
{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}
so to get the html for the "empty" error message, you'd use
$('#form_response').html(data.error_msg.empty);
alternatively, if i misunderstand the question, if you want the RAW json to appear in div#form_response, you can convert the json object into a string:
json_string = JSON.stringify( data );
$('#form_response').html( json_string );
I am fairly confident this should work for you :)
Your HTML/JS file:
<script type="text/javascript" src="js/jquery.js"></script>
<div class="" id="form_response"></div>
<form id="add_property_form" action="" method="POST">
<input type="text" name="input">
<button type="submit">Send</button>
</form>
<script type="text/javascript">
$("#add_property_form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'thescript.php',
type: 'POST',
data: formData,
async: false,
cache:false,
contentType: false,
processData: false,
dataType: "json",
success: function (data) {
var resultData = data.response_msg; // get HTML to insert
$('#form_response').html(resultData);
// You can also use data.status (= true or false), to let you know which HTML was inserted :)
}
});
return false;
});
</script>
your PHP file:
header('Content-Type: application/json');
// construct original array
$results = array(
'status' => false,
'response_msg' => ''
);
// analyze $_POST variables
if(empty($_POST['input'])){ // if input post is not empty:
$results['status'] = false;
$results['response_msg'] = '<div class="ser_mess">empty</div>';
}else{ // if input post is empty:
$results['status'] = true;
$results['response_msg'] = '<div class="ser_mess">success</div>';
}
echo json_encode($results); // encode as JSON
exit();
Related
I am trying to send data from a form to a database. Here is the form I am using:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.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.
To make an Ajax request using jQuery you can do this by the following code.
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript:
Method 1
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Method 2
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* Request can be aborted by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// Show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// Show error
$("#result").html('There is error while submit');
});
The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.
MDN: abort() . If the request has been sent already, this method will abort the request.
So we have successfully send an Ajax request, and now it's time to grab data to server.
PHP
As we make a POST request in an Ajax call (type: "post"), we can now grab data using either $_REQUEST or $_POST:
$bar = $_POST['bar']
You can also see what you get in the POST request by simply either. BTW, make sure that $_POST is set. Otherwise you will get an error.
var_dump($_POST);
// Or
print_r($_POST);
And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.
And if you want to return any data back to the page, you can do it by just echoing that data like below.
// 1. Without JSON
echo "Hello, this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
And then you can get it like:
ajaxRequest.done(function (response){
alert(response);
});
There are a couple of shorthand methods. You can use the below code. It does the same work.
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.
First of all, create two files, for example form.php and process.php.
We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.
form.php
<form method="post" name="postForm">
<ul>
<li>
<label>Name</label>
<input type="text" name="name" id="name" placeholder="Bruce Wayne">
<span class="throw_error"></span>
<span id="success"></span>
</li>
</ul>
<input type="submit" value="Send" />
</form>
Validate the form using jQuery client-side validation and pass the data to process.php.
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
//Validate fields if required using jQuery
var postForm = { //Fetch form data
'name' : $('input[name=name]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php', //Your form processing file URL
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
}
else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
Now we will take a look at process.php
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else { //If not, process the form, and return true on success
$form_data['success'] = true;
$form_data['posted'] = 'Data Was Posted Successfully';
}
//Return the data back to form.php
echo json_encode($form_data);
The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.
You can use serialize. Below is an example.
$("#submit_btn").click(function(){
$('.error_status').html();
if($("form#frm_message_board").valid())
{
$.ajax({
type: "POST",
url: "<?php echo site_url('message_board/add');?>",
data: $('#frm_message_board').serialize(),
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
}
else
{
alert('Server error');
return false;
}
}
});
}
return false;
});
HTML:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" class="inputs" name="bar" type="text" value="" />
<input type="submit" value="Send" onclick="submitform(); return false;" />
</form>
JavaScript:
function submitform()
{
var inputs = document.getElementsByClassName("inputs");
var formdata = new FormData();
for(var i=0; i<inputs.length; i++)
{
formdata.append(inputs[i].name, inputs[i].value);
}
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
}
xmlhttp.open("POST", "insert.php");
xmlhttp.send(formdata);
}
I use the way shown below. It submits everything like files.
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
If you want to send data using jQuery Ajax then there is no need of form tag and submit button
Example:
<script>
$(document).ready(function () {
$("#btnSend").click(function () {
$.ajax({
url: 'process.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('success');
}
});
});
});
</script>
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
In your php file enter:
$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";
and in your js file send an ajax with the data object
var data = {
bar : 'bar value',
time: calculatedTimeStamp,
hash: calculatedHash,
uid: userID,
sid: sessionID,
iid: itemID
};
$.ajax({
method: 'POST',
crossDomain: true,
dataType: 'json',
crossOrigin: true,
async: true,
contentType: 'application/json',
data: data,
headers: {
'Access-Control-Allow-Methods': '*',
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Access-Control-Allow-Origin": "*",
"Control-Allow-Origin": "*",
"cache-control": "no-cache",
'Content-Type': 'application/json'
},
url: 'https://yoururl.com/somephpfile.php',
success: function(response){
console.log("Respond was: ", response);
},
error: function (request, status, error) {
console.log("There was an error: ", request.responseText);
}
})
or keep it as is with the form-submit. You need this only, if you want to send a modified request with calculated additional content and not only some form-data, which is entered by the client. For example a hash, a timestamp, a userid, a sessionid and the like.
Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:
var formData = formData;
$.ajax({
type: "POST",
url: url,
async: false,
data: formData, // Only input
processData: false,
contentType: false,
xhr: function ()
{
$("#load_consulting").show();
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#addLoad .progress-bar').css('width', percentComplete + '%');
}
}, false);
// Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
qyuraLoader.startLoader();
},
success: function (response, textStatus, jqXHR) {
qyuraLoader.stopLoader();
try {
$("#load_consulting").hide();
var data = $.parseJSON(response);
if (data.status == 0)
{
if (data.isAlive)
{
$('#addLoad .progress-bar').css('width', '00%');
console.log(data.errors);
$.each(data.errors, function (index, value) {
if (typeof data.custom == 'undefined') {
$('#err_' + index).html(value);
}
else
{
$('#err_' + index).addClass('error');
if (index == 'TopError')
{
$('#er_' + index).html(value);
}
else {
$('#er_TopError').append('<p>' + value + '</p>');
}
}
});
if (data.errors.TopError) {
$('#er_TopError').show();
$('#er_TopError').html(data.errors.TopError);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
else
{
$('#headLogin').html(data.loginMod);
}
} else {
//document.getElementById("setData").reset();
$('#myModal').modal('hide');
$('#successTop').show();
$('#successTop').html(data.msg);
if (data.msg != '' && data.msg != "undefined") {
bootbox.alert({closeButton: false, message: data.msg, callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
} else {
bootbox.alert({closeButton: false, message: "Success", callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
}
}
}
catch (e) {
if (e) {
$('#er_TopError').show();
$('#er_TopError').html(e);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
}
});
I am using this simple one line code for years without a problem (it requires jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>
Since the introduction of the Fetch API there really is no reason any more to do this with jQuery Ajax or XMLHttpRequests. To POST form data to a PHP-script in vanilla JavaScript you can do the following:
async function postData() {
try {
const res = await fetch('../php/contact.php', {
method: 'POST',
body: new FormData(document.getElementById('form'))
})
if (!res.ok) throw new Error('Network response was not ok.');
} catch (err) {
console.log(err)
}
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>
Here is a very basic example of a PHP-script that takes the data and sends an email:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test#example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
Please check this. It is the complete Ajax request code.
$('#foo').submit(function(event) {
// Get the form data
// There are many ways to get this data using jQuery (you
// can use the class or id also)
var formData = $('#foo').serialize();
var url = 'URL of the request';
// Process the form.
$.ajax({
type : 'POST', // Define the type of HTTP verb we want to use
url : 'url/', // The URL where we want to POST
data : formData, // Our data object
dataType : 'json', // What type of data do we expect back.
beforeSend : function() {
// This will run before sending an Ajax request.
// Do whatever activity you want, like show loaded.
},
success:function(response){
var obj = eval(response);
if(obj)
{
if(obj.error==0){
alert('success');
}
else{
alert('error');
}
}
},
complete : function() {
// This will run after sending an Ajax complete
},
error:function (xhr, ajaxOptions, thrownError){
alert('error occured');
// If any error occurs in request
}
});
// Stop the form from submitting the normal way
// and refreshing the page
event.preventDefault();
});
Pure JS
In pure JS it will be much simpler
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
This is a very good article that contains everything that you need to know about jQuery form submission.
Article summary:
Simple HTML Form Submit
HTML:
<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
JavaScript:
$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get the form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = $(this).serialize(); // Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#server-results").html(response);
});
});
HTML Multipart/form-data Form Submit
To upload files to the server, we can use FormData interface available to XMLHttpRequest2, which constructs a FormData object and can be sent to server easily using the jQuery Ajax.
HTML:
<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="file" name="my_file[]" /> <!-- File Field Added -->
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
JavaScript:
$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = new FormData(this); // Creates new FormData object
$.ajax({
url : post_url,
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData: false
}).done(function(response){ //
$("#server-results").html(response);
});
});
I hope this helps.
That's the code that fills a select option tag in HTML using ajax and XMLHttpRequest with the API is written in PHP and PDO
conn.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
category.php
<?php
include 'conn.php';
try {
$data = json_decode(file_get_contents("php://input"));
$stmt = $conn->prepare("SELECT * FROM events ");
http_response_code(200);
$stmt->execute();
header('Content-Type: application/json');
$arr=[];
while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
array_push($arr,$value);
}
echo json_encode($arr);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
script.js
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (let i in data) {
$("#cars").append(
'<option value="' + data[i].category + '">' + data[i].category + '</option>'
)
}
}
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>Document</title>
</head>
<body>
<label for="cars">Choose a Category:</label>
<select name="option" id="option">
</select>
<script src="script.js"></script>
</body>
</html>
I have one other idea.
Which the URL that of PHP files which provided the download file.
Then you have to fire the same URL via ajax and I checked this second request only gives the response after your first request complete the download file. So you can get the event of it.
It is working via ajax with the same second request.}
I am trying to pass my $model['id'] from a foreach to a modal which contains a form which heavily requires the $model['id'] for if statements and functions.
I have tried putting a link around the button to use the usual $_GET however that forces the page to refresh and therefore closes the modal box, is there a way to prevent the modal from closing if the url contains an id?
Alternatively I have tried using the data-id passing through an AJAX post method and retrieving it in the modal. However the $_POST is not being defined, have I missed something or can it not $_POST to the same page? I am not good with AJAX so any help or ideas would be greatly appreciated.
There is way too much code in my page to post it all so here's a snippet of the important stuff
<button data-id="<?php echo $model['id']; ?>" data-modal-type="type3" class="modal_button customer_button right">New Customer</button>
<div class="modal" id="type3">
<div class="modal-content">
<div class="modal-title"><h3>New Customer</h3></div>
<div class="modal-padding">
<?php
$customer_model_id = (isset($_POST['id'])) ? $_POST['id'] : 'ID not found';
echo $customer_model_id; // Always shows ID not found
?>
</div>
</div>
</div>
<script>
$(".modal_button").click(function () {
$(".modal").hide();
var Type = $(this).data("modal-type");
$("#" + Type).show();
var id = $(this).data("id");
alert($(this).data("id")); // Alert box shows the correct ID
$.ajax({
type: "POST",
url: '<?php echo doc_root('index.php');//post to the same page we are currently on ?>',
data: "id=" + id,
});
});
</script>
EDIT:
I think I'm getting closer with this JavaScript.
<script>
$(".modal_button").click(function(){
$(".modal").hide();
var Type = $(this).data("modal-type");
var id = $(this).data('id');
$.ajax({
type : 'POST',
url : 'customer_complete.php',
data : 'id='+ id,
cache: false,
success : function(data){
$('.customer_complete').html(data);
}
})
$("#"+Type).show();
});
</script>
I decided to write some code for you, because I found the task an interesting one. The code simulates the situation that you've presented in your question and comments, and is relatively easy to follow. You can run it as it is, but don't forget to replace my db credentials with yours, in connection.php. All files are on the same niveau in the file system hierarchy. So you can create a folder, bring all files in it, and run the index.php page. I used prepared statements to insert into db, thus avoiding any sql injections risc. I also commented that part, just in case you are not familiarize with it.
Have fun.
index.php
This is the main page.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Modal</title>
<!-- CSS assets -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<style type="text/css">
body { padding: 20px; }
.success { color: #32cd32; }
.error { color: #ff0000; }
</style>
<!-- JS assets -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#type3').on('show.bs.modal', function (event) {
var modal = $(this);
var button = $(event.relatedTarget);
var modelId = button.data('model-id');
$.ajax({
method: 'post',
dataType: 'html',
url: 'new_customer.php',
data: {
'modelId': modelId,
'modalId': 'type3'
},
success: function (response, textStatus, jqXHR) {
modal
.find('.modal-padding')
.html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
modal
.find('.modal-messages')
.removeClass('success')
.addClass('error')
.html('An error occurred during your request. Please try again, or contact us.');
}
});
});
$('#type3').on('hide.bs.modal', function (event) {
var modal = $(this);
modal.find('.modal-padding').html('');
modal
.find('.modal-messages')
.removeClass('success error')
.html('');
});
});
</script>
</head>
<body>
<button type="button" data-model-id="13" data-modal-type="type3" data-toggle="modal" data-target="#type3" class="modal_button customer_button right">
New Customer
</button>
<div class="modal" id="type3">
<div class="modal-content">
<div class="modal-title">
<h3>New Customer</h3>
</div>
<div class="modal-messages"></div>
<div class="modal-padding"></div>
</div>
</div>
</body>
</html>
new_customer.php
This page contains the form for adding a new customer into customers table.
<?php
$modelId = $_POST['modelId'] ?? NULL;
$modalId = $_POST['modalId'] ?? NULL;
?>
<script type="text/javascript">
$(document).ready(function () {
$('#saveCustomerButton').on('click', function (event) {
var form = $('#addCustomerForm');
var button = $(this);
var modalId = button.data('modal-id');
var modal = $('#' + modalId);
$.ajax({
method: 'post',
dataType: 'html',
url: 'add_customer.php',
data: form.serialize(),
success: function (response, textStatus, jqXHR) {
modal
.find('.modal-messages')
.removeClass('error')
.addClass('success')
.html('Customer successfully added.');
$('#resetAddCustomerFormButton').click();
},
error: function (jqXHR, textStatus, errorThrown) {
var message = errorThrown;
if (jqXHR.responseText !== null && jqXHR.responseText !== 'undefined' && jqXHR.responseText !== '') {
message = jqXHR.responseText;
}
modal
.find('.modal-messages')
.removeClass('success')
.addClass('error')
.html(message);
}
});
});
});
</script>
<style type="text/css">
#addCustomerForm {
padding: 20px;
}
</style>
<form id="addCustomerForm" action="" method="post">
<input type="hidden" id="modelId" name="modelId" value="<?php echo $modelId; ?>" />
<div class="form-group">
<label for="customerName">Name</label>
<input type="text" id="customerName" name="customerName" placeholder="Customer name">
</div>
<button type="button" data-modal-id="<?php echo $modalId; ?>" id="saveCustomerButton" name="saveCustomerButton" value="saveCustomer">
Save
</button>
<button type="reset" id="resetAddCustomerFormButton" name="resetAddCustomerFormButton">
Reset
</button>
</form>
add_customer.php
This page consists of code for handling the saving of the customer into the database.
<?php
require 'connection.php';
require 'InvalidInputValue.php';
use App\InvalidInputValue;
try {
$modelId = $_POST['modelId'] ?? NULL;
$customerName = $_POST['customerName'] ?? NULL;
// Validate the model id.
if (empty($modelId)) {
throw new InvalidInputValue('Please provide the model id.');
} /* Other validations here using elseif statements */
// Validate the customer name.
if (empty($customerName)) {
throw new InvalidInputValue('Please provide the customer name.');
} /* Other validations here using elseif statements */
/*
* Save the customer into db. On failure exceptions are thrown if and
* only if you are setting the connection options correspondingly.
* See "connection.php" for details.
*/
$sql = 'INSERT INTO customers (
model_id,
name
) VALUES (
?, ?
)';
/*
* Prepare the SQL statement for execution - ONLY ONCE.
*
* #link http://php.net/manual/en/mysqli.prepare.php
*/
$statement = mysqli_prepare($connection, $sql);
/*
* Bind variables for the parameter markers (?) in the
* SQL statement that was passed to prepare(). The first
* argument of bind_param() is a string that contains one
* or more characters which specify the types for the
* corresponding bind variables.
*
* #link http://php.net/manual/en/mysqli-stmt.bind-param.php
*/
mysqli_stmt_bind_param($statement, 'is', $modelId, $customerName);
/*
* Execute the prepared SQL statement.
* When executed any parameter markers which exist will
* automatically be replaced with the appropriate data.
*
* #link http://php.net/manual/en/mysqli-stmt.execute.php
*/
mysqli_stmt_execute($statement);
/*
* Close the prepared statement. It also deallocates the statement handle.
* If the statement has pending or unread results, it cancels them
* so that the next query can be executed.
*
* #link http://php.net/manual/en/mysqli-stmt.close.php
*/
mysqli_stmt_close($statement);
/*
* Close the previously opened database connection.
* Not really needed because the PHP engine closes
* the connection anyway when the PHP script is finished.
*
* #link http://php.net/manual/en/mysqli.close.php
*/
mysqli_close($connection);
} catch (InvalidInputValue $exc) {
/*
* Throw an error to be catched by the "error" callback of the ajax request.
* This can be achieved by sending a specific or a custom response header to the client.
*
* - Specific header: A header containing any already assigned status code.
* - Custom header: A header containing any NOT already assigned status code. This type of
* headers have the reason phrase "Unassigned" in the official HTTP Status Code Registry.
*
* #link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
echo $exc->getMessage();
exit();
} catch (Exception $exc) {
// For all other system failures display a user-friendly message.
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
echo 'An error occurred during your request. Please try again, or contact us.';
exit();
}
connection.php
<?php
/*
* This page contains the code for creating a mysqli connection instance.
*/
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');
/*
* Enable internal report functions. This enables the exception handling,
* e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
* (mysqli_sql_exception).
*
* MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
* MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
*
* #link http://php.net/manual/en/class.mysqli-driver.php
* #link http://php.net/manual/en/mysqli-driver.report-mode.php
* #link http://php.net/manual/en/mysqli.constants.php
*/
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
/*
* Create a new db connection.
*
* #see http://php.net/manual/en/mysqli.construct.php
*/
$connection = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE, PORT);
InvalidInputValue.php
This is a custom exception class. An exception of this type is thrown when posted user input values are invalid.
<?php
namespace App;
use Exception;
/**
* Custom exception. Thrown when posted user input values are invalid.
*/
class InvalidInputValue extends Exception {
}
Definition of "customers" table
I didn't create a models table, so there is no FK.
CREATE TABLE `customers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`model_id` int(11) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
As I understood, you already have correct id value on the page. Looks like you get it from php script ($model['id']) and store in data-id of your button.
Also, looks like you're already able to get this id, when button is clicked. The further action depends on what exactly you are going to do.
$(".modal_button").click(function () {
var id = $(this).data("id"); //here you have an id
$(some_selector).html(id); //to put it inside elements html
$(another_selector).attr("placeholder", id); //to use it as placeholder (or any other attribute
});
This is for usage with js on the same page.
For POSTing it to the server:
$.ajax({
type: "POST",
url: your_url,
data: {
id: id
},
success: function(result) {
console.log(result);
//some actions after POSTing
}
});
On the server access it via $_POST["id"].
Why what you did was wrong?
Your POST request worked. You can check this using Chrome Dev Tools (Network tab). It posted to the same page and it's ok. The response of the server was an html page with id's built in modals, just as you wanted. But that was the response to the AJAX call and it had no influence to the page you already have loaded. Also, reloading the page you always had "ID not found" because reloading page doesn't make POST request.
Here is the general logic of what you need:
You already have id on the page. To transfer it to other elements on the same page, building into html markup and so on use JS.
To transfer data to the server (for SQL for example) use AJAX. You'd better create a separate file that would be an AJAX handler. That script will deal with POSTed id, make all required actions (like inserting new user to db) and send response (simple success-error code, string or JSON) back to the caller. Then, in AJAX.success you can handle the response and for example notify user if the operation was failed.
Hope this helps.
Your data parameter is wrong.
try this:
var idx = $(this).data("id");
$.ajax({
type: "POST",
url: '<?php echo doc_root('index.php'); ?>',
data: {id: idx}
}).done(function( data ) {
console.log( data );
});
Im returning "true"/"false" (text) from PHP into javascript via AJAX, but my JAVASCRIPT IF condition doesn't seem to be executing even though the condition is correct.
Javascript
var request = $.ajax({
type: "POST",
dataType: "text",
url: "",
data: {
'clientSecret': clientSecret,
'oauthCode':oauthCode
},
});
request.done(function(msg) {
alert(msg);
if(msg=="false"){ <----- DOES NOT EXECUTE
//do stuff
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
PHP
if(checkData($key,$oauthCode)==true){
header("Content-Type: text/plain");
echo "true";
}
else{
header("Content-Type: text/plain");
echo "false";
}
Javascript succesfully alerts "false",
but the if condtion never gets executed.
Is something wrong with the return data type or? What exaclty am i missing here?
Just a suggestion, because I already started to work on this alternative for your question as you found out the problem.
I don't recommend you to work with headers for such tasks. They are sensible to beforehand-outputs, as you saw. You can use the json approach (dataType: 'json') - as #charlietfl kindly suggested, or work with dataType = 'html'.
With json would look something like this:
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Test</title>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
function startTestScript() {
var clientSecret = $('#clientSecret').val();
var oauthCode = $('#oauthCode').val();
var ajax = $.ajax({
method: 'post',
dataType: 'json',
url: 'checkOauth.php',
data: {
'clientSecret': clientSecret,
'oauthCode': oauthCode
}
});
ajax.done(function (response, textStatus, jqXHR) {
if (response === true) {
alert('Response is ' + response + '. COOL!');
} else {
alert('Response is ' + response + '. UPS!');
}
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
alert('Request failed: ' + textStatus + '\n' + errorThrown);
});
ajax.always(function (response, textStatus, jqXHR) {
// alert('Finished executing this cool script.');
});
}
</script>
<style type="text/css">
body {
padding-top: 30px;
text-align: center;
}
button {
padding: 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
</style>
</head>
<body>
<div>
<label for="clientSecret">Client secret (int)</label>
<input type="text" id="clientSecret" name="clientSecret" value="123">
<br/><br/>
<label for="oauthCode">OAuth code (int)</label>
<input type="text" id="oauthCode" name="oauthCode" value="123">
<br/><br/>
<button type="button" name="testButton" onclick="startTestScript();">
Start ajax
</button>
</div>
</body>
</html>
checkOauth.php
<?php
/**
* Check data.
*
* #param mixed $value1
* #param mixed $value2
* #return TRUE if values are equal, FALSE otherwise.
*/
function checkData($value1, $value2) {
return intval($value1) === intval($value2);
}
// Fetch posted values.
$clientSecret = isset($_POST['clientSecret']) ? $_POST['clientSecret'] : 0;
$oauthCode = isset($_POST['oauthCode']) ? $_POST['oauthCode'] : 0;
// Check data.
$dataIsValid = checkData($clientSecret, $oauthCode);
// Output the JSON-encoded result of checking data.
echo json_encode($dataIsValid);
I am trying to send data from a form to a database. Here is the form I am using:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.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.
To make an Ajax request using jQuery you can do this by the following code.
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript:
Method 1
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Method 2
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* Request can be aborted by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// Show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// Show error
$("#result").html('There is error while submit');
});
The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.
MDN: abort() . If the request has been sent already, this method will abort the request.
So we have successfully send an Ajax request, and now it's time to grab data to server.
PHP
As we make a POST request in an Ajax call (type: "post"), we can now grab data using either $_REQUEST or $_POST:
$bar = $_POST['bar']
You can also see what you get in the POST request by simply either. BTW, make sure that $_POST is set. Otherwise you will get an error.
var_dump($_POST);
// Or
print_r($_POST);
And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.
And if you want to return any data back to the page, you can do it by just echoing that data like below.
// 1. Without JSON
echo "Hello, this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
And then you can get it like:
ajaxRequest.done(function (response){
alert(response);
});
There are a couple of shorthand methods. You can use the below code. It does the same work.
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.
First of all, create two files, for example form.php and process.php.
We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.
form.php
<form method="post" name="postForm">
<ul>
<li>
<label>Name</label>
<input type="text" name="name" id="name" placeholder="Bruce Wayne">
<span class="throw_error"></span>
<span id="success"></span>
</li>
</ul>
<input type="submit" value="Send" />
</form>
Validate the form using jQuery client-side validation and pass the data to process.php.
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
//Validate fields if required using jQuery
var postForm = { //Fetch form data
'name' : $('input[name=name]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php', //Your form processing file URL
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
}
else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
Now we will take a look at process.php
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else { //If not, process the form, and return true on success
$form_data['success'] = true;
$form_data['posted'] = 'Data Was Posted Successfully';
}
//Return the data back to form.php
echo json_encode($form_data);
The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.
You can use serialize. Below is an example.
$("#submit_btn").click(function(){
$('.error_status').html();
if($("form#frm_message_board").valid())
{
$.ajax({
type: "POST",
url: "<?php echo site_url('message_board/add');?>",
data: $('#frm_message_board').serialize(),
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
}
else
{
alert('Server error');
return false;
}
}
});
}
return false;
});
HTML:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" class="inputs" name="bar" type="text" value="" />
<input type="submit" value="Send" onclick="submitform(); return false;" />
</form>
JavaScript:
function submitform()
{
var inputs = document.getElementsByClassName("inputs");
var formdata = new FormData();
for(var i=0; i<inputs.length; i++)
{
formdata.append(inputs[i].name, inputs[i].value);
}
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
}
xmlhttp.open("POST", "insert.php");
xmlhttp.send(formdata);
}
I use the way shown below. It submits everything like files.
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
If you want to send data using jQuery Ajax then there is no need of form tag and submit button
Example:
<script>
$(document).ready(function () {
$("#btnSend").click(function () {
$.ajax({
url: 'process.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('success');
}
});
});
});
</script>
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
In your php file enter:
$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";
and in your js file send an ajax with the data object
var data = {
bar : 'bar value',
time: calculatedTimeStamp,
hash: calculatedHash,
uid: userID,
sid: sessionID,
iid: itemID
};
$.ajax({
method: 'POST',
crossDomain: true,
dataType: 'json',
crossOrigin: true,
async: true,
contentType: 'application/json',
data: data,
headers: {
'Access-Control-Allow-Methods': '*',
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Access-Control-Allow-Origin": "*",
"Control-Allow-Origin": "*",
"cache-control": "no-cache",
'Content-Type': 'application/json'
},
url: 'https://yoururl.com/somephpfile.php',
success: function(response){
console.log("Respond was: ", response);
},
error: function (request, status, error) {
console.log("There was an error: ", request.responseText);
}
})
or keep it as is with the form-submit. You need this only, if you want to send a modified request with calculated additional content and not only some form-data, which is entered by the client. For example a hash, a timestamp, a userid, a sessionid and the like.
Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:
var formData = formData;
$.ajax({
type: "POST",
url: url,
async: false,
data: formData, // Only input
processData: false,
contentType: false,
xhr: function ()
{
$("#load_consulting").show();
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#addLoad .progress-bar').css('width', percentComplete + '%');
}
}, false);
// Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
qyuraLoader.startLoader();
},
success: function (response, textStatus, jqXHR) {
qyuraLoader.stopLoader();
try {
$("#load_consulting").hide();
var data = $.parseJSON(response);
if (data.status == 0)
{
if (data.isAlive)
{
$('#addLoad .progress-bar').css('width', '00%');
console.log(data.errors);
$.each(data.errors, function (index, value) {
if (typeof data.custom == 'undefined') {
$('#err_' + index).html(value);
}
else
{
$('#err_' + index).addClass('error');
if (index == 'TopError')
{
$('#er_' + index).html(value);
}
else {
$('#er_TopError').append('<p>' + value + '</p>');
}
}
});
if (data.errors.TopError) {
$('#er_TopError').show();
$('#er_TopError').html(data.errors.TopError);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
else
{
$('#headLogin').html(data.loginMod);
}
} else {
//document.getElementById("setData").reset();
$('#myModal').modal('hide');
$('#successTop').show();
$('#successTop').html(data.msg);
if (data.msg != '' && data.msg != "undefined") {
bootbox.alert({closeButton: false, message: data.msg, callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
} else {
bootbox.alert({closeButton: false, message: "Success", callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
}
}
}
catch (e) {
if (e) {
$('#er_TopError').show();
$('#er_TopError').html(e);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
}
});
I am using this simple one line code for years without a problem (it requires jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>
Since the introduction of the Fetch API there really is no reason any more to do this with jQuery Ajax or XMLHttpRequests. To POST form data to a PHP-script in vanilla JavaScript you can do the following:
async function postData() {
try {
const res = await fetch('../php/contact.php', {
method: 'POST',
body: new FormData(document.getElementById('form'))
})
if (!res.ok) throw new Error('Network response was not ok.');
} catch (err) {
console.log(err)
}
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>
Here is a very basic example of a PHP-script that takes the data and sends an email:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test#example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
Please check this. It is the complete Ajax request code.
$('#foo').submit(function(event) {
// Get the form data
// There are many ways to get this data using jQuery (you
// can use the class or id also)
var formData = $('#foo').serialize();
var url = 'URL of the request';
// Process the form.
$.ajax({
type : 'POST', // Define the type of HTTP verb we want to use
url : 'url/', // The URL where we want to POST
data : formData, // Our data object
dataType : 'json', // What type of data do we expect back.
beforeSend : function() {
// This will run before sending an Ajax request.
// Do whatever activity you want, like show loaded.
},
success:function(response){
var obj = eval(response);
if(obj)
{
if(obj.error==0){
alert('success');
}
else{
alert('error');
}
}
},
complete : function() {
// This will run after sending an Ajax complete
},
error:function (xhr, ajaxOptions, thrownError){
alert('error occured');
// If any error occurs in request
}
});
// Stop the form from submitting the normal way
// and refreshing the page
event.preventDefault();
});
Pure JS
In pure JS it will be much simpler
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
This is a very good article that contains everything that you need to know about jQuery form submission.
Article summary:
Simple HTML Form Submit
HTML:
<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
JavaScript:
$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get the form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = $(this).serialize(); // Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#server-results").html(response);
});
});
HTML Multipart/form-data Form Submit
To upload files to the server, we can use FormData interface available to XMLHttpRequest2, which constructs a FormData object and can be sent to server easily using the jQuery Ajax.
HTML:
<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="file" name="my_file[]" /> <!-- File Field Added -->
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
JavaScript:
$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = new FormData(this); // Creates new FormData object
$.ajax({
url : post_url,
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData: false
}).done(function(response){ //
$("#server-results").html(response);
});
});
I hope this helps.
That's the code that fills a select option tag in HTML using ajax and XMLHttpRequest with the API is written in PHP and PDO
conn.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
category.php
<?php
include 'conn.php';
try {
$data = json_decode(file_get_contents("php://input"));
$stmt = $conn->prepare("SELECT * FROM events ");
http_response_code(200);
$stmt->execute();
header('Content-Type: application/json');
$arr=[];
while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
array_push($arr,$value);
}
echo json_encode($arr);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
script.js
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (let i in data) {
$("#cars").append(
'<option value="' + data[i].category + '">' + data[i].category + '</option>'
)
}
}
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>Document</title>
</head>
<body>
<label for="cars">Choose a Category:</label>
<select name="option" id="option">
</select>
<script src="script.js"></script>
</body>
</html>
I have one other idea.
Which the URL that of PHP files which provided the download file.
Then you have to fire the same URL via ajax and I checked this second request only gives the response after your first request complete the download file. So you can get the event of it.
It is working via ajax with the same second request.}
I am trying to create an async file upload but I am hitting a wall. Here is what I have, in an element:
Element:
<div style="border:0px solid darkgray; width:100%; text-align: right; text-decoration: underline; font-weight: bold;">
<form id="upload_form" enctype="multipart/form-data">
<input type="file" accept="" id = "templatePath" name = "templatePath" name="MAX_FILE_SIZE" value="104857600">
<input type="submit" value="Submit" id = "bntSubmit" name = "bntSubmit" onclick="submitFileUpload();" >
</form>
</div>
JQuery:
function submitFileUpload(){
try{
var FileUrl = "/staff/passport/upload_file/";
var request_timeout = 50000;
var formData = new FormData();
var files =$( '#templatePath' )[0].files[0];
formData.append( 'templatePath', files);
$.ajax({
url: FileUrl,
type: 'POST',
timeout: request_timeout,
cache: false,
contentType: false,
processData: false,
data:formData,
beforeSend: function(xhr ){
},
success: function(data) {
try{
if(data.status =='ok'){
}else{
}
}catch(ex){
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
return false;
}catch(ex){
}
}
Controller function:
public function upload_file(){
try{
$this->autoRender = false;
} catch (Exception $e){
return $this->EncodeError($e);
}
}
The jquery seems to be fine. Break points are hit and I can see that the object "files" is created and has the file attributes. The controller function also gets called but the form data does not show up in my debugger (nothing in "this" or _FILES[] or any other variable). Can anyone help out?
thanks
jason
Based on your comment, you are nesting the File upload element within another form. From nesting is not valid HTML and will confuse browsers besides not giving you the expected result. Refer to this answer.
The only solution is to remove the file upload form from within your original outer form and place it outside. Use CSS to make the upload form appear within your original form.