The data is inserted and i receive in console the json response but the page move for the insert php and gives the json response
So i start in page A (form) and after submit moves to page B (insert)giving me the json response.
I'm having a problem getting the response of the following php into ajax
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
} else {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));
This is my ajax
$.ajax({
url: 'nova_formacaoBD.php',
dataType: 'json',
data: data,
success: function(data) {
$('#ajaxDivOk').html('Informação: Esta formação foi registada na base de dados');
if(data.status == "success"){
$('#ajaxDivOk').append(data.message);
}
}
});
And this is my form
<form action="nova_formacaoBD.php" method="post" id="formacao" name="formacao" enctype="multipart/form-data">
UPDATE
The data is all the input fields in the form
Seven strings and upload of one file
<form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">Escola: </label>
<select class="form-control" id="escola" name="escola" onchange="verificaEscola()">
<?php echo $escolaOptions; ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome Formação: </label>
<input class="form-control" id="form" name="form" onchange="verificaNome()">
</input>
<div class="form-group">
<label for="exampleInputEmail1">Data de Início: </label><input type="text" class="form-control" id="data" name="data" onchange="verificaData()" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">Horas: </label><input type="text" class="form-control" id="horas" name="horas" onchange="verificaHoras()">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Local: </label>
<input class="form-control" id="local" name="local" onchange="verificaLocal()">
</input>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Destinatários: </label>
<input class="form-control" id="dest" name="dest" onchange="verificaDest()">
</input>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Data Limite: </label><input type="text" class="form-control" id="datas" name="datas" onchange="verificaDataLimite()"/>
</div>
<div class="form-group">
<label for="exampleInputFile">Programa da Formação</label>
<input type="file" name="fileToUpload" id="fileToUpload" name="fileToUpload">
</div>
<button type="submit" class="btn btn-default" onclick="return checkBoxes(this)">Registar</button>
</form>
This is my form complete
UPDATE 2 (now it works but i have a warning in my console
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
and the beforeSend funtion doesn't work
I don't see the div "Wait while updating the file)
Js code
<script type="text/javascript">
$(document).ready(function () {
$("#formacao").submit(function (event) {
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'nova_formacaoBD.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
beforeSend: function(data){
$('#ajaxDivAlert').html('A carregar o ficheiro...aguarde por favor')
},
success: function (data) {
var result = data.status;
console.log(result);
if(result == 'success'){
$('#ajaxDivAlert').empty();
$('#ajaxDivOk').html('Informação: ' + data.message);
$("#ajaxDivOk").fadeIn();
$("#ajaxDivOk").fadeOut(5000);
}
},
error: function(){
$("#ajaxDivErro").html('Esta formação já está registada na base de dados');
$("#ajaxDivErro").fadeIn();
$("#ajaxDivErro").fadeOut(5000);
}
});
return false;
});
});
</script>
So, i just need to put info to complete the code, the rest is working
You have some changes to do :
Html : Remove the action="nova_formacaoBD.php" like that :
<form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
Then I suppose that you have a ajax called like that :
UPDATE
$(document).ready(function () {
$("#formacao").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var ajaxDivAlert = $('#ajaxDivAlert');
$.ajax({
url: 'nova_formacaoBD.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
ajaxDivAlert.empty().html('A carregar o ficheiro...aguarde por favor')
}
}).done(function (data) {
var result = data.status;
if (result == 'success'){
ajaxDivAlert.empty().fadeIn().html('Informação: ' + data.message).fadeOut(5000);
}
}).fail(function () {
ajaxDivAlert.empty().fadeIn().html('Esta formação já está registada na base de dados').fadeOut(5000);
});
});
});
You had the error XMLHttpRequest because you put async: false. I removed it because since jQuery 1.8, the use of async: false with jqXHR ($ .Deferred) is deprecated
Related
I have this problem that i cant seem to solve, for sure is a noob thing but here it goes, i'm trying to past values and upload file using the same form, but the file is not passing to the php function.
my html with ajax:
<form name="create_batch" method="post" role="form">
<input type="hidden" name="token" value="<?= \Middlewares\Csrf::get() ?>" required="required" />
<input type="hidden" name="request_type" value="create" />
<input type="hidden" name="project_id" value="<?= $data->project->project_id ?>" />
<input type="hidden" name="type" value="batch" />
<div class="notification-container"></div>
<div class="form-group">
<label><i class="fa fa-fw fa-signature fa-sm mr-1"></i> <?= $this->language->create_link_modal->input->location_url ?></label>
<input type="text" class="form-control" name="location_url" required="required" placeholder="<?= $this->language->create_link_modal->input->location_url_placeholder ?>" />
</div>
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<label><i class="fa fa-fw fa-link"></i> <?= $this->language->create_link_modal->input->url ?>
</label>
<input type="text" class="form-control" name="url" placeholder="<?= $this->language->create_link_modal->input->url_placeholder ?>" />
</div>
<div class="text-center mt-4">
<button type="submit" name="submit" class="btn btn-primary"><?= $this->language->create_link_modal->input->submit ?></button>
</div>
</form>
<script>
$('form[name="create_batch"]').on('submit', event => {
$.ajax({
type: 'POST',
url: 'link-ajax',
data: $(event.currentTarget).serialize(),
success: (data) => {
if(data.status == 'error') {
let notification_container = $(event.currentTarget).find('.notification-container');
notification_container.html('');
display_notifications(data.message, 'error', notification_container);
}
else if(data.status == 'success') {
/* Fade out refresh */
fade_out_redirect({ url: data.details.url, full: true });
}
},
dataType: 'json'
});
event.preventDefault();
})
</script>
this will post the data to the php file and the respective funtion, but only the fields are passing through. The file, that is a csv, is not passing. for sure i have something wrong on my ajax script that is only allow to pass the values of the form via post but not the file.
my php is something like this:
<?php
if(!empty($_FILES)){
$fh = fopen($_FILES['file']['tmp_name'], 'r+');
$i=0;
$lines = array();
while( ($row = fgetcsv($fh, 8192)) !== FALSE ) {
$lines[] = $row;
$location_url = $lines[$i][0];
$url = $lines[$i][1];
$umt_source = $lines[$i][2];
$utm_medium = $lines[$i][3];
$utm_campaign = $lines[$i][4];
$utm_term = $lines[$i][5];
$utm_content = $lines[$i][6];
$i=$i+1;
}
fclose($fh);
}
$_POST['project_id'] = (int) $_POST['project_id'];
$_POST['location_url'] = trim(Database::clean_string($_POST['location_url']));
$_POST['url'] = !empty($_POST['url']) ? get_slug(Database::clean_string($_POST['url'])) : false;
...........
Any help? Many thanks.
In order to send multipart form data, you need to create and send a form data object.
see example below -
var formdata = new FormData($('#formId')[0]);
$.ajax({
url: URL,
type: 'POST',
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function (response) {
$('#responseMsg').html(response.msg);
}
});
On server end you can get your data by $_POST and files by $_FILES
the solution.
$("form#create_batch").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'link-ajax',
type: 'POST',
data: formData,
dataType: 'json',
success: (data) => {
if(data.status == 'error') {
let notification_container = $(event.currentTarget).find('.notification-container');
notification_container.html('');
display_notifications(data.message, 'error', notification_container);
}
else if(data.status == 'success') {
/* Fade out refresh */
fade_out_redirect({ url: data.details.url, full: true });
}
},
cache: false,
contentType: false,
processData: false
});
});
I want to send data on the controller into JSON format. but getting into a string. so can I do this?
I used header that is being passed on ajax call but it not converting Form filed into JSON format .
due to string format Laravel not able to process this response.
My Browser Response.
HTML Code
<form id="NoeticeBoardGetAllFrm" name="NoeticeBoardGetAllFrm" role="form" method="post" >
<div class="row">
<div class="col-sm-6">
<label> URL </label>
<input type="text" name="NoeticeBoardGetAllUrl" id="NoeticeBoardGetAllUrl"
class="form-control" placeholder="URL"
value="https://XXXXXXXXXXXX/get-all-notice-board-information"/>
</div>
<div class="col-sm-4">
<label> Session Code </label>
<input type="text" name="scode" id="scode" class="form-control"
value="cFZnMVJUY0JNUUJsTXZBeVZhZmRHZz09"
maxlength="50" minlength="32" placeholder="Session Code"/>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">
<input type="submit" name="NoeticeBoardGetAllBtn" id="NoeticeBoardGetAllBtn"
class="btn btn-danger " value="Get Result" />
</div>
<div class="col-sm-3"> <i class="fa fa-reddit-square"></i>
<span class="inLine">Result :</span>
<div id="NoeticeBoardGetAllResult" class="inLine result_box">---</div>
</div>
</div>
</form>
My Javascript Code
$("#NoeticeBoardGetAllFrm").submit(function(e) {
e.preventDefault();
console.log( new FormData(this));
$.ajax({
url: $("#NoeticeBoardGetAllUrl").val(),
type: 'POST',
headers: {'Accept': 'application/json','Content-Type': 'application/json',
'DBAuth': $("#DBAuth").val(),'Authorization': $("#Authorization").val(),},
dataType: 'json',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
if (data.error == 0) {
$("#NoeticeBoardGetAllResult").html("Record fetched successfully!");
$("#NoeticeBoardGetAllResult").addClass("alert alert-success");
} else {
$("#NoeticeBoardGetAllResult").html(data.errmsg);
$("#NoeticeBoardGetAllResult").addClass("alert alert-warning");
}
}, statusCode: {
500: function (data) {
$("#NoeticeBoardGetAllResult").html("Something went wrong!");
$("#NoeticeBoardGetAllResult").addClass("alert alert-danger");
},
401: function (data) {
$("#NoeticeBoardGetAllResult").html("Login Failed");
$("#NoeticeBoardGetAllResult").addClass("alert alert-danger");
}
}
});
setTimeout(function(){ resetResult(); }, 3000);
});
You can use serialize method to send Data as Json
$('#NoeticeBoardGetAllFrm').serialize()
You should use this in place of
data: new FormData(this),
instead of data: new FormData(this);
use following
data: $(this).serializeArray();
It gets your form data and serialize into array that is ready of convert into JSON.
I have an user information form in my Laravel site and trying to upload image using Ajax.
Blade
<form id="edit_form" enctype="multipart/form-data">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
<div class="form-group">
<label>Image</label>
<input id="edit_form_image" type="file" class="form-control" name="user_image">
</div><!-- end form-group -->
<div class="form-group">
<label>Name</label>
<input id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
</div><!-- end form-group -->
<button type="button" id="edit_form_submit" class="btn btn-orange">Save Changes</button>
Ajax
$('#edit_form_submit').click(function(event) {
var fd = new FormData();
var edit_form_image = $('#edit_form_image')[0].files;
var edit_form_name = $('#edit_form_name').val();
var token = $('input[name=_token]').val();
fd.append( 'image', edit_form_image );
fd.append( 'name', edit_form_name );
fd.append( '_token', token );
$.ajax({
url:"{{ url('/profile-update') }}",
data: fd,
async:false,
type: 'POST',
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
But in my controller I can't get the image file.
controller
if (request()->hasFile('image'))
{
return "file present";
}
else{
return "file not present";
}
Though I upload an image controller always response that `file no present'.
Where is the error? Anybody Help please ?
why dont you name your input tags as you need to send in post method in :
<input name="image" id="edit_form_image" type="file" class="form-control">
<input name="name" id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
And,
$("#edit_form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url:"{{ url('/profile-update') }}",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
This might works.
i have file upload form field,i select one gif','png' ,'jpg' means it will work,and i am select any other file .mp3,.php file it will give error like this **SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 73 of the JSON data**.i want to file type check and file size after that i want to insert the value,but don't know how to do this,i think my PHP code should be wrong...
<?php
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_name= md5($filename.time()).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "horoscope/".$new_name)) {
// FILE TYPE CHECKING
$allowed = array('gif','png' ,'jpg');
if(!in_array($extension,$allowed) ) {
$newuser = array('photoname' => $new_name, "message" => "error");
if($_FILES['file']['size'] > 2459681 ){
$newuser = array('photoname' => $new_name, "message" => "filesize is to large");
}else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}
else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}else{
//echo "Error";
$newuser = array("message" => "file is not moving");
echo json_encode($newuser);
}
?>
<script type="text/javascript">
$(document).ready(function(){
$("#user-submit").click(function(event){
event.preventDefault();
if($("form#newUserForm").valid()){
var formData = new FormData();
var formData = new FormData($('#newUserForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
return false;
}else{
console.log("false");
}
});
});
</script>
<form class="form-horizontal form-bordered" method="POST" id="newUserForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file" value="" aria-required="true" required="" data-msg-required="Please select your file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-info" type="submit" id="user-submit">Submit</button>
</div>
</div>
</form>
Using xhr() could solve your problem... for example :-
var formData = new FormData($('#newUserForm')[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
//if you want progress report otherwise you can remove this part from here to
myXhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100 ;
percentComplete = Math.round(percentComplete);
$("#progress").text(percentComplete + " %");
}
}, false);
//here
return myXhr;
},
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
my problem is that when I click send this not entering the sendmail () function , should show alert, the ajax is the admin- ajax.php is good Request URL:http://localhost:8888/password/wp-admin/admin-ajax.php
Request Method:POST
Status Code:200 OK
HTML FORM:
<div class="form">
<form action="" method="POST" id="ContactForm" enctype="application/x-www-form-urlencoded" novalidate="novalidate" >
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="celular" placeholder="Celular o Teléfono">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="message" placeholder="Your Message *" style="height:175px;"></textarea>
</div>
<div id="loading_icon"><img src='<?php echo get_template_directory_uri(). '/images/loading_spinner.gif'; ?>' alt="loading" style="display: none;"></div>
<input class="btn btn-default" type="submit" name="submit" value="Enviar">
<div id="#response"></div>
</form>
</div>
ajax:
jQuery(document).ready(function($){
$("#ContactForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
celular: "required"
},
messages: {
name: "Por favor digite su nombre",
email: {
required: "Por favor digite su correo",
email: "Porfavor ingrese un email valido"
},
message: "Ingrese el asunto en el que le podemos ayudar",
celular: "Digite su numero de celular o telefono"
},
submitHandler: function(form) {
$('#loading_icon').show();
$('#click').hide();
var params = $(form).serialize();
$.ajax ({
type: 'POST',
url: ajaxurl,
data: params + '&action=sendmail',
success: function(response) {
$('#response').hide();
$('#response').html(response);
$('#response').fadeIn('slow');
$('#loading_icon').hide();
}
});
}
});
});
PHP:
<?php
/*
Plugin Name: Formulario de contacto
Plugin URI: http://www.e-world.co
Description: Formulario de contacto con ajax
Version: 1.0
Author: Jorge Moreno
Author URI: http://www.e-world.co
license: GLP2
*/
function frontend_custom_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','frontend_custom_ajaxurl');
add_action('wp_ajax_sendmail', 'sendmail');
add_action('wp_ajax_nopriv_sendmail', 'sendmail');
function sendmail() {
echo '<script language="javascript">alert("se envió!!");</script>';
}
?>
You cannot run javascript function in the ajax file .. instead run the desired php code in ajaxfile
<?php
add_action('wp_ajax_sendmail', 'sendmail');
add_action('wp_ajax_nopriv_sendmail', 'sendmail');
function sendmail() {
echo 'alert_me';
die;
}
?>
Then is the response you can perform the alerting functionality
submitHandler: function(form) {
$('#loading_icon').show();
$('#click').hide();
var params = $(form).serialize();
$.ajax ({
type: 'POST',
url: ajaxurl,
data: params + '&action=sendmail',
success: function(response) {
$('#response').hide();
$('#response').html(response);
$('#response').fadeIn('slow');
$('#loading_icon').hide();
if(reponse == 'alert_me'){
alert('Alert your required string');
}
}
});
}
I'm not sure what you're trying to accomplish with creating a JS snippet inside PHP.
Hit the admin-ajax route directly in the url. Put your payload in data and the endpoint you want to hit in params: {'action': 'your_endpoint_here'}
$.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
data: data,
params: {'action': 'my_endpoint'}
}).success(function (data) {
// do stuff with response data
}
}).error(function (data) {
// do stuff with error response data
}
});
Your PHP would look like this
add_action('wp_ajax_nopriv_my_endpoint', array($this, 'myMailFunction'));
add_action('wp_ajax_my_endpoint', array($this, 'myMailFunction'));
public function myMailFunction()
{
//send mail here
}