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 want to use Acymailing Joomla! component installed at example.com/mailer to manage subscriptions from non Joomla site on example.com
In that case I have simple script
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize(),
success: function () {
swal('Great success!');
}
});
});
});
and form
<form class="form-inline" action="https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub" method="post">
<div class="form-group">
<label class="sr-only" for="user_name">Email address</label>
<input id="user_name" type="text" name="user[name]" value="" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="user_email">Password</label>
<input id="user_email" type="text" name="user[email]" value="" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Sign Up!</button>
<input type="hidden" name="user[html]" value="1" />
<input type="hidden" name="acyformname" value="formAcymailing1" />
<input type="hidden" name="ctrl" value="sub"/>
<input type="hidden" name="task" value="optin"/>
<input type="hidden" name="redirect" value="https://example.com"/>
<input type="hidden" name="option" value="com_acymailing"/>
<input type="hidden" name="visiblelists" value=""/>
<input type="hidden" name="hiddenlists" value="1"/>
</form>
Everything works fine except success, error states...
Joomla Acymailing have sub.php file to handle ajax responses
if($config->get('subscription_message',1) || $ajax){
if($allowSubscriptionModifications){
if($statusAdd == 2){
if($userClass->confirmationSentSuccess){
$msg = 'CONFIRMATION_SENT';
$code = 2;
$msgtype = 'success';
}else{
$msg = $userClass->confirmationSentError;
$code = 7;
$msgtype = 'error';
}
}else{
if($insertMessage){
$msg = 'SUBSCRIPTION_OK';
$code = 3;
$msgtype = 'success';
}elseif($updateMessage){
$msg = 'SUBSCRIPTION_UPDATED_OK';
$code = 4;
$msgtype = 'success';
}else{
$msg = 'ALREADY_SUBSCRIBED';
$code = 5;
$msgtype = 'success';
}
}
}else{
if($modifySubscriptionSuccess){
$msg = 'IDENTIFICATION_SENT';
$code = 6;
$msgtype = 'warning';
}else{
$msg = $modifySubscriptionError;
$code = 8;
$msgtype = 'error';
}
}
if($msg == strtoupper($msg)){
$source = acymailing_getVar('cmd', 'acy_source');
if(strpos($source, 'module_') !== false){
$moduleId = '_'.strtoupper($source);
if(acymailing_translation($msg.$moduleId) != $msg.$moduleId) $msg = $msg.$moduleId;
}
$msg = acymailing_translation($msg);
}
$replace = array();
$replace['{list:name}'] = '';
foreach($myuser as $oneProp => $oneVal){
$replace['{user:'.$oneProp.'}'] = $oneVal;
}
$msg = str_replace(array_keys($replace),$replace,$msg);
if($config->get('redirect_tags', 0) == 1) $redirectUrl = str_replace(array_keys($replace),$replace,$redirectUrl);
if($ajax){
$msg = str_replace(array("\n","\r",'"','\\'),array(' ',' ',"'",'\\\\'),$msg);
echo '{"message":"'.$msg.'","type":"'.($msgtype == 'warning' ? 'success' : $msgtype).'","code":"'.$code.'"}';
}elseif(empty($redirectUrl)){
acymailing_enqueueMessage($msg,$msgtype == 'success' ? 'info' : $msgtype);
}else{
if(strlen($msg)>0){
if($msgtype == 'success') acymailing_enqueueMessage($msg);
elseif($msgtype == 'warning') acymailing_enqueueMessage($msg,'notice');
else acymailing_enqueueMessage($msg,'error');
}
}
}
And JSON looks like on Joomla side registration to the same form by index.php?option=com_acymailing&ctrl=sub
message Subscribe confirmed
type success
code 3
{"message":"Subscribe confirmed","type":"success","code":"3"}
The question is: how to obtain that submission statuses success, error, already submbited etc on external submission form (at example.com page)?
this simple change may do it for you:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize()
}
}).done(function (data) {
swal('Great success!');
});
});
});
I personally like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
swal('Great success!');
});
since your result is in JSON, that should be more like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
console.log(data); // shows full return object in console
swal('Great success!');
}, "json");
Try the following, I have explained the changes inside comments:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formdata = $(this).serializeArray(); //i really prefer serializeArray better than serialize (up2u)
$.ajax({
type: 'post',
dataType: 'json', //because your data is json
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: formdata,
success: function (d) {//d is the return/response of your url (your question answer)
swal(
d.type+': '+d.code ,
d.message,
d.type
);
},
error: function(d){
swal(
'Oops..' ,
'Something went wrong!', //your json must be in trouble
'error'
);
console.log(d); //delete this in production stage
console.log(d.responseText); //i add this so you will know what happenned exactly when you get this error. delete this too in production stage
}
});
});
});
I don't feel your ajax had issues, what i can see from the Joomla php code, everytime when you request that joomla URL you will always get a response header status code as 200, so your javascript will always land on success block of ajax code, returning with some json based message, when i checked the joomla acymaling (version 5.8.1 for joomla 3.8.3) code for that controller, i saw on line number 74 they are checking if the request is made using ajax, but missing Access-Control-Allow-Origin in php header which will restrict your outside call so you can replace this if condition from :
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
}
to
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
header("Access-Control-Allow-Origin: *");
}
so to allow calls from any other domain as well, but do remember this can also cause vulnerabilities to you joomla code. also you need to change your HTML form as well add one more hidden field in your HTML :
<input type="hidden" name="ajax" value="1" />
so to allow ajax request by your joomla controller file.
now in your success block of ajax you can make a check something like this :
success:function(data, status, xhr){
var json = $.parseJSON(data);
swal(json.message, json.type);
}
I hope this will help you in acomplishing what you want to, Happy coding.
I also face this type of problem.for solving this type of problem i Put a variable in the success as argument html.
e.g. success(html)
and
console.log(html)
this shows all errors including notices and all. turn on errore_reporting['E_ALL'];. and do not set dataType to 'json' .
Simple solution to your question is :
success: function (data) {
$("#<id_of_tag>").html(data);
}
data : Response returned from the server to your AJAX call
id_of_tag : where you want to display your returned output.
Its just an example, you can decide, what kind of data you want to return and what you want to do with your response.
To answer your question: On Success parameter in function will contain your response.
As in my case, i am returning another JSP page, which i want to display in div tag.
Also check below link : I think it might help you
Best way to check if AJAX request was successful in jQuery
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.}
Well my problem is this:
I want to successfully upload 2 files to my server and then send an email attaching this 2 files. But when i call the jquery function it only send the email before it successfuly upload and i don't get any attach. I want to wait untill the upload it's done and then send the email with the 2 files correctly attached. By the way im using PHPmailer.
I have this html
<form enctype="multipart/form-data" class="formulario2">
<label for="cel" class="control-label">PresentaciĆ³n Corporativa</label>
<div class="controls">
<input type="file" name="file_name2" id="presentacion_web" class="inputfile">
<label for="presentacion_web" class="btn btn-primary">Elija un Archivo</label>
<input id="nombre_archivo2" disabled>
<div class="messages2"></div><br /><br />
</div>
</form>
<form enctype="multipart/form-data" class="formulario">
<label for="dni" class="control-label">DiseƱo Aprobado</label>
<div class="controls">
<input type="file" name="file_name1" id="diseno_aprobado_web" class="inputfile">
<label for="diseno_aprobado_web" class="btn btn-primary">Elija un Archivo</label>
<input id="nombre_archivo1" disabled>
<div class="messages"></div><br /><br />
</div>
</form>
this function in jquery:
$var3 = $("#diseno_aprobado_web").val();
$var6 = $("#presentacion_web").val();
$var7 = $var3.substring(12);
$var8 = $var6.substring(12);
$.when( enviando1(), enviando2() ).then( function(){
$.ajax({
type: 'POST',
data: ('var3='+$var7+'&var6='+$var8),
url: 'send_mail.php',
success: function(salida){
alert('Mensaje Enviado');
}
});
}).done( function(){
console.log( ' Everything was OK!' );
})
.fail( function(){
console.log( 'Something was failed' );
});
function enviando1(){
var formData = new FormData($(".formulario")[0]);
var message = "";
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
message = $("<span class='before'>Subiendo el archivo, por favor espere...</span>");
showMessage(message);
},
success: function(data){
message = $("<span class='success'>El archivo ha subido correctamente.</span>");
showMessage(message);
},
error: function(){
message = $("<span class='error'>Ha ocurrido un error.</span>");
showMessage(message);
}
});
};
function showMessage(message){
$(".messages").html("").show();
$(".messages").html(message);
}
function enviando2(){
var formData2 = new FormData($(".formulario2")[0]);
var message2 = "";
$.ajax({
url: 'upload2.php',
type: 'POST',
data: formData2,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
message2 = $("<span class='before'>Subiendo el archivo, por favor espere...</span>");
showMessage2(message2);
},
success: function(data){
message2 = $("<span class='success'>El archivo ha subido correctamente.</span>");
showMessage2(message2);
},
error: function(){
message2 = $("<span class='error'>Ha ocurrido un error.</span>");
showMessage2(message2);
}
});
};
function showMessage2(message2){
$(".messages2").html("").show();
$(".messages2").html(message2);
}
And this php file (send_mail.php) :
require('phpmailer/class.phpmailer.php');
$bodytext = "Correct Message";
$email = new PHPMailer();
$email->From = 'test#mydomain.com';
$email->FromName = 'test bot';
$email->Subject = 'New mail from phpmailer';
$email->Body = $bodytext;
$email->AddAddress( 'test2#test2.com' );
$file_to_attach1 = 'folder/' . $_POST['var6'];
$file_to_attach2 = 'folder/' . $_POST['var3'];
$email->AddAttachment( $file_to_attach1 , $_POST['var6'] );
$email->AddAttachment( $file_to_attach2 , $_POST['var3'] );
return $email->Send();
I was trying a lot of code and i'm really stuck and frustrated now. Sorry if is something simple but i couldn't get an answer to my problem.
Thanks!
Update1:
I found this in my upload.php, and i think it's the problem:
$file = $_FILES['file_name']['name'];
if ($file && move_uploaded_file($_FILES['file_name']['tmp_name'],"folder/".$file))
{
sleep(3);
echo $file;
}
This is returning a success in my ajax after 3 seconds, how i can turn this
"sleep(3)"
Into the time required to upload the file?.
Update 2:
upload.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$file = $_FILES['file_name1']['name'];
if(!is_dir("folder"))
mkdir("folder", 0777);
if ($file && move_uploaded_file($_FILES['file_name1']['tmp_name'],"folder/".$file)){
sleep(3);
echo $file;
}}else{ throw new Exception("Error Processing Request", 1); }
upload2.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$file = $_FILES['file_name2']['name'];
if(!is_dir("folder"))
mkdir("folder", 0777);
if ($file && move_uploaded_file($_FILES['file_name2']['tmp_name'],"folder/".$file))
{
sleep(3);
echo $file;
}}else{ throw new Exception("Error Processing Request", 1);}
Add return's
You have:
function enviando1(){
var formData = new FormData($(".formulario")[0]);
var message = "";
$.ajax({
Must be:
function enviando1(){
var formData = new FormData($(".formulario")[0]);
var message = "";
return $.ajax({
You have:
function enviando2(){
var formData2 = new FormData($(".formulario2")[0]);
var message2 = "";
$.ajax({
Must be:
function enviando2(){
var formData2 = new FormData($(".formulario2")[0]);
var message2 = "";
return $.ajax({
I think you should try .done instead of .then in the following line of your code
$.when( enviando1(), enviando2() ).then( function(){
The method will resolve its .done request as soon as all the request resolve (enviando1(),enviando1()), or reject the .done request as soon as one of the request is rejected.
You want to use dynamic file name but have $var3 and $var6 static. Use this to get the name of the file being uploaded.
$var6 = $(presentacion_web).val().split('\\').pop();
$var3 = $(diseno_aprobado_web).val().split('\\').pop();
I have upload form that allows users to upload multiple files. I decided that a progress bar would be good if the files are quite large. Below is my source code. I am new to jquery normally I would just php but I find that ajax is more user friendly.
<div id="new_upload">
<div class="close_btn"></div>
<div id="uploads"></div>
<form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
<fieldset><legend>Upload an image or video</legend>
<input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
</fieldset>
<div class="bar">
<div class="bar_fill" id="pb">
<div class="bar_fill_text" id="pt"></div>
</div>
</div>
</form>
</div>
<script>
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%') //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
function beforeSubmit(){
console.log('ajax start');
}
function afterSuccess(data){
console.log(data);
}
$(document).ready(function(e) {
$('#upload_file').submit(function(event){
event.preventDefault();
var filedata = document.getElementById("file");
formdata = new FormData();
var i = 0, len = filedata.files.length, file;
for (i; i < len; i++) {
file = filedata.files[i];
formdata.append("file[]", file);
}
formdata.append("json",true);
$.ajax({
url: "global.func/file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
resetForm: true
});
});
});
</script>
The image upload works fine, the array send to ajax but the progress bar doesn't move. In fact the console.log for the two functions called need to produce this don't appear either. Is there a correct way to call the functions in my ajax request that would get this progress bar to work.
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
NOTE that this function 'success: afterSuccess' is working as the console is displaying my data.
This is your HTML form
<form method="post" action="uploadImages.php" name ='photo' id='imageuploadform' enctype="multipart/form-data">
<input hidden="true" id="fileupload" type="file" name="image[]" multiple >
<div id ="divleft">
<button id="btnupload"></button>
</div>
</form>
This is your JQuery and ajax.
By default the fileInput is hidden.
Upload Button clicked
$("#btnupload").click(function(e) {
$("#fileupload").click();
e.preventDefault();
});
$('#fileupload').change(function (e) {
$("#imageuploadform").submit();
e.preventDefault();
});
$('#imageuploadform').submit(function(e) {
var formData = new FormData(this);
$.ajax({
type:'POST',
url: 'ajax/uploadImages',
data:formData,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log(data);
alert('data returned successfully');
},
error: function(data){
console.log(data);
}
});
e.preventDefault();
});
function progress(e){
if(e.lengthComputable){
var max = e.total;
var current = e.loaded;
var Percentage = (current * 100)/max;
console.log(Percentage);
if(Percentage >= 100)
{
// process completed
}
}
}
Your php code looks like this
<?php
header('Content-Type: application/json');
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 30000 * 1024; // max file size in bytes
$json = array();
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
for($i=0;$i<count($_FILES['image']['tmp_name']);$i++)
{
$path="image/uploads/photos/";
if(is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$uid = uniqid();
$date = date('Y-m-d-H-i-s');
$path = $path ."image_" .$date. '_' . $uid . "." .$ext;
$returnJson[]= array("filepath"=>$path);
$filename = "image_" . $date . "_" .$uid . "." . $ext;
$this->createthumb($i,$filename);
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
//$status = 'Image successfully uploaded!';
//perform sql updates here
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
}
else {
$status = 'Bad request!';
}
echo json_encode($json);
?>
You must use a custom XMLHttpRequest to do this with AJAX and jQuery. There's an example here: How can I upload files asynchronously?