Show loading image while my controller execute a function - javascript

need to show an image while my function "Mailcontroller/sendMail" is working sending an email. I passed values to this function from my view by a submit button in a form. I had try with other examples that I saw here, but I can't get what I need.
My view:
<div class="container" style="margin-right: 100px;">
<div class="row">
<div class="col-md-9 col-md-offset-3">
<form class="form-horizontal" enctype='multipart/form-data' method="POST" action="<?=base_url();?>Cpersona/sendMail">
<fieldset>
<div class="form-group">
<div class="col-md-6">
<label style="font-size: 15px; margin-left: 215px;">Destinatarios</label><br />
<input type="button" name="agregardes" id="agregardes" onclick="llenarDestino();correos();" style="font-size: 15px; margin-left: 215px;" value="Agregar Destinatarios">
<input style="margin-left: 215px;" id="email" name="email" type="text" class="form-control" required>
<label style="font-size: 15px; margin-left: 215px;">Asunto</label><br />
<input style="margin-left: 215px;" type="text" class="form-control" name="asunto" id="asunto">
<label style="font-size: 15px; margin-left: 215px;">Mensaje</label><br />
</div>
<div class="col-md-9" style="float: right;">
<textarea id="editor" name="mensaje"></textarea>
</div>
</div>
<section>
<div style="margin-left: 215px;">
<p id="msg"></p>
<input type="file" id="file" name="file" />
</div>
</section>
<div>
<br />
<input style="margin-left: 215px;" class="btn btn-primary" type="submit" id="enviar" name="enviar" value="Enviar">
</div>
</fieldset>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#enviar').click(function(){
//Añadimos la imagen de carga en el contenedor
$('#content').html('<div><img src="../assets/images/loading.gif"/></div>');
var page = $(this).attr('data');
var dataString = 'page='+page;
$.ajax({
type: "GET",
url: "http://localhost/empresa/Cpersona/sendMail",
data: dataString,
success: function(data) {
//Cargamos finalmente el contenido deseado
$('#content').fadeIn(1000).html(data);
}
});
});
});
</script>
An extract of my Controller:
public function sendMail{
$data = array(
'id_usuario' => $usuario,
'fecha' => $fecha,
'id' => $cliente
);
$this->Modelo_datos->historial($data);
$this->email->set_newline("\r\n");
$this->email->from('correopruebas#consultora.cl');
$this->email->to($value);
$this->email->subject($asunto);
$this->email->message($enviar);
//$path = set_realpath('./uploads/');
//$adjunto = $path.$archivo;
if($this->email->send())
{
$this->load->helper("file");
delete_files('./uploads/');
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Correo Enviado!!')
window.location.href='verLista';
</SCRIPT>");
}
else
{
show_error($this->email->print_debugger());
$this->load->helper("file");
delete_files('./uploads/');
}
}
}

first add image(that you want to be displayed) with id loader and make it hidden by using style="display:none";
loader = document.querySelector("#loader");
function sendMail() {
loader.style.display = "block";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
loader.style.display="none";
// some thing here when email is sent
}
};
xhttp.open("GET", "your_send_mail_file.php?send=true", true);
xhttp.send();
}
and in your_send_mail_file.php
<?php
if (isset($_GET["send"]) && $_GET["send"] === "true") {
$test = new your_class(); // that_contain_the_sendMail function;
$test->sendMail();
}

Related

Two form in one page php, but want to submit only one

I have a page where I have a form for signin and an another for signup.
But when I click either on singin or signup button it's always the signup form who is sent.
Where is my error ?
PHP CODE :
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_POST['modification'] == 1)
{
alert("Signin");
}
if ($_POST['modification'] == 2)
{
alert("Signup");
}
}
HTML CODE :
<div class="col-md-6">
<div class="contact-form">
<form id="connecter" name="connecter" method="post">
<div class="row">
<div class="col-sm-6">
<fieldset>
<input name="txtIdentifiant" type="text" class="form-control" id="txtIdentifiant" placeholder="Identifiant" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtMotDePasse" type="text" class="form-control" id="txtMotDePasse" placeholder="Mot de passe" required="">
</fieldset>
</div>
<div class="col-lg-12">
<fieldset>
<button type="submit" id="btnConnecter" name="btnConnecter" class="filled-button" form="connecter" value="btnConnecter">Se connecter</button>
<input type="hidden" name="modification" value="1" />
</fieldset>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-6">
<div class="contact-form">
<form id="inscrire" name="inscrire" method="post">
<div class="row">
<div class="col-sm-6">
<fieldset>
<input name="txtPrenom" type="text" class="form-control" id="txtPrenom" placeholder="Prénom" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtNom" type="text" class="form-control" id="txtNom" placeholder="Nom" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtGSM" type="text" class="form-control" id="txtGSM" placeholder="Numéro de GSM" required="">
</fieldset>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<fieldset>
<input name="txtAdresseMail" type="text" class="form-control" id="txtAdresseMail" placeholder="Email" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtIdentifiantInscription" type="text" class="form-control" id="txtIdentifiantInscription" placeholder="Identifiant" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtMotDePasseInscription" type="text" class="form-control" id="txtMotDePasseInscription" placeholder="Mot de passe" required="">
</fieldset>
</div>
<div class="col-lg-12">
<fieldset>
<button type="submit" id="btnCreerCompte" name="btnCreerCompte" class="filled-button" form="inscrire" value="btnCreerCompte">S'inscrire</button>
<input type="hidden" name="modification" value="2"/>
</fieldset>
</div>
</div>
</form>
</div>
</div>
AJAX CODE :
<script type="text/javascript">
$('#btnConnecter').on('click',function(e){
//prevent submitting form
e.preventDefault();
//Get Input Values
var identifiant = document.getElementById("txtIdentifiant").value;
var motDePasse = document.getElementById("txtMotDePasse").value;
//Form Validation
if (identifiant && motDePasse)
{
//Call Ajax to check if user existed
$.ajax({
type : "POST",
url : "check-signin.php",
dataType: "json",
data:
{
identifiant: identifiant, motDePasse: motDePasse
},
success:function(result)
{
// alert(result.msg);
if (result.msg == "Success")
{
e.preventDefault();
//Submit form if user not existed
$('form').submit();
//alert("Ajax ok");
}
else if (result.msg == "Failed")
{
e.preventDefault();
alert("Identifiant/Mot de passe incorrect");
//C'est chaud
document.getElementById("txtIdentifiant").focus();
return false;
}
else if (result.msg == "Active")
{
e.preventDefault();
alert("Veuillez activer votre compte");
document.getElementById("txtIdentifiant").focus();
return false;
}
}
});
}
else
{
alert("Veuillez remplir tout les champs");
return false;
}
});
</script>
<script type="text/javascript">
$('#btnCreerCompte').on('click',function(e){
e.preventDefault();
var prenom = document.getElementById("txtPrenom").value;
var nom = document.getElementById("txtNom").value;
var mail = document.getElementById("txtAdresseMail").value;
var numGSM = document.getElementById("txtGSM").value;
var minGSM = document.getElementById("txtGSM").length;
var identifiant = document.getElementById("txtIdentifiantInscription").value;
var motDePasse = document.getElementById("txtMotDePasseInscription").value;
if (prenom && nom && mail && numGSM && identifiant && motDePasse)
{
if (isNaN(numGSM) || numGSM.length < 7)
{
alert("Numéro de gsm non valide");
//Phone number invalid
document.getElementById("txtGSM").focus();
return false;
}
else if (validateEmail(mail))
{
$.ajax({
type : "POST",
url : "check-user.php",
dataType: "json",
data: {
identifiant: identifiant
},
success:function(result)
{
if (result.msg == "Success")
{
e.preventDefault();
$('form').submit();
}
else if (result.msg == "Failed")
{
e.preventDefault();
alert("Identifiant déjà existant");
document.getElementById("txtIdentifiantInscription").focus();
return false;
}
}
});
}
else
{
alert("Adresse mail incorrecte");
document.getElementById("txtAdresseMail").focus();
return false;
}
}
else
{
alert("Veuillez remplir tout les champs");
return false;
}
});
</script>
Is it Ajax that break the php submit ?
Because I have the double form in the client section where he can change either his information or his password, and it work over there, I don't know why here it won't work :(
Thank you guys !
do not use button type="submit":
Update to:
<button id="btnCreerCompte" name="btnCreerCompte" class="filled-button" form="inscrire" value="btnCreerCompte">S'inscrire</button>
or:
<input type="button" value="S'inscrire" onclick="submitFormCreerCompte()">
And in the scripts create function "submitFormCreerCompte()" and call ajax to submit form
So I test one or two things, and I somehow make it work like this :
HTML CODE :
<button type="submit" id="btn" name="btn" class="filled-button" form="connecter" value="btnConnecter">Se connecter</button>
<input type="hidden" name="btn" value="btnConnecter" />
<button type="submit" id="btn" name="btn" class="filled-button" form="inscrire" value="btnCreerCompte">S'inscrire</button>
<input type="hidden" name="btn" value="btnCreerCompte"/>
PHP CODE :
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_POST['btn'] == 'btnConnecter')
{
alert("Je suis dedans co");
}
else if ($_POST['btn'] == 'btnCreerCompte')
{
alert("Je suis dedans ins");
}
else
{
alert("Rien fonctionne");
}
}
Thank for the attention guys

Fill in radio input with database data

When I query the form returns the input radio filled with the data of the database, as shown:
<input type="radio" id="Estado" name="Estado" value="Pendente" ' . ( ($row6["Estado"]=='Pendente') ? 'checked' : '' ) .' readonly="true"> Pendente <input type="radio" id="Estado" name="Estado" value="Concluído" ' . ( ($row6["Estado"]=='Concluído') ? 'checked' : '' ) .' readonly="true"> Concluído
I also show in the completed image:
But when I click the edit button it changes the filled input radio and should not, because it no longer fills according to the data of the database, as I show in the image:
script:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
$('#Estado1').prop("checked", data.Estado);
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});
$('#insert_form6').on("submit", function(event){
event.preventDefault();
if($('#Colaborador6').val() == "")
{
alert("Colaborador é necessário");
}
else
{
$.ajax({
url:".conexao26",
method:"POST",
data:$('#insert_form6').serialize()
,
beforeSend:function(){
$('#insert6').val("Inserting");
},
success:function(data){
$('#insert_form6')[0].reset();
$('#exampleModal6').modal('hide');
$('#employee_table').html(data);
location.reload("exampleModal6");
}
});
}
});
HTML:
<form method="post" id="insert_form6">
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Data-name" class="col-form-label">Data</label></h6>
<h6><input type="date" name="data6" id="data6" value="<?php echo date("Y-m-d");?>"></h6>
</div>
</div>
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Colaborador-text" class="col-form-label">Colaborador</label></h6>
<h6><select style="width:150px" name="Colaborador6" id="Colaborador6" required>
<option></option>
<?php
$sql = "SELECT Funcionario FROM centrodb.InfoLuvas WHERE Ativo = '1' AND Funcao = 'Limpeza' AND Valencia = 'LAR'";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Funcionario'].'">'.$ln['Funcionario'].'</option>';
}
?>
</select></h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Tarefa Pendente</label></h6>
<textarea type="text" id="Observacao6" name="Observacao6" class="form-control"></textarea>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Estado</label></h6>
<div style="clear:both;"></div>
<h6><input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente <input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído</h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="disabled form-group">
<h6><label for="Observacao-name" class="col-form-label">Conclusão</label></h6>
<textarea type="text" id="Conclusao" name="Conclusao" class="form-control"></textarea>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="Nome6" id="Nome6" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="NomeConc" id="NomeConc" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Sair</button>
<input type="hidden" name="employee_id6" id="employee_id6" />
<input type="submit" name="insert6" id="insert6" value="Registo" data-toggle="modal" class="btn btn-success" />
</div>
</form>
I'm trying these ways but I still do not solve the problem:
1st form:
var tipo_conta = $('.tipo_conta').val(data.Estado);
if(tipo_conta == 'Pendente'){
$('#Estado1').prop('checked' , true);
}else{
$('#Estado2').prop('checked' ,true);
}
2st form:
var radios = document.getElementsByName("Estado");
if (radios.value == "Pendente") {
radios.checked = true;
}else{
radios.checked = true;
}
Can anyone help?
I found the issue inside the HTML file. As #daddygames suggested you have used the same ID in both Radio button. see below
<h6>
<input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente
<input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído
</h6>
An ID must be unique. Update the ID and make it unique. Then change the code in .ajax script according to your need. This will help you.
First I created the variable lis to receive the value that the radio input receives from the database:
var lis = $("#Estado").val();
Then inside the data function I created another variable with the value that the radio input receives from the function:
var teste = data.Estado;
and finally I check with if:
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
Full Code:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
var lis = $("#Estado").val();
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
var teste = data.Estado;
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});

Prefilled the form data from the another page's input

I am trying to pass some data from one web page to another
while clicking on the button.
Blade Page:
<div class="container">
<div class="row">
<div class="col-md-7 info" style="padding-right: 35px;padding-top: 40px" >
<h1 style="text-align: right;margin-bottom: 0px; font-style:italic;font-size:28px">"Wǒ bù zhīdào cóng nǎlǐ kāishǐ, píngtái bāng wǒ zhǎodàole zhīchí. Wǒ zhēn de hěn xǐhuān tāmen rúhé gēnjù wǒ de yùsuàn wèi wǒ tígōng duō zhǒng xuǎnzé bìng bāngzhù wǒ pínggū tāmen.</h1>
<br>
<p style="text-align:right; font-weight:bold; font-size:16px">Alvin R., Entrepreneur</p>
</div>
<div class="col-md-5" style="padding-left: 35px;">
<div class="card" style="border-radius: 20px !important;">
<div class="card-head" style="text-align: center;font-weight: bold;padding-top: 25px;">
<header style="font-size: 25px;color: #3f9ae5;">GET STARTED</header>
</div><!--end .card-head -->
<div class="card-body" style="font-weight: bold;font-size: 16px;padding-left: 30px;">
<div class="form" style="padding-left: 15px;padding-right: 15px;">
<div class="row">
<div class="col-md-12">
<div class="form-group" style="margin-bottom: 20px;">
<select style="margin-top: 15px;font-size: 16px;" id="aops" class="form-control select2-list" name="areas">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" id="req_options">
<div class="form-group">
<select style="margin-top: 15px;color: grey;font-size: 16px;" id="request_type" class="form-control select2-list" name="request_types" >
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" placeholder="Title " style="margin-top: 10px;padding-left: 10px;font-size: 16px;" class="form-control" name="title" id="title">
</div>
</div>
</div>
</div>
<button class="btn btn-theme effect standard btn-sm" id="post_request" style="background-color: #3f9ae5 !important;border-style: none;color:#ffffff;font-weight:bold;width: 100%;font-size: 16px">Post a Request</button>
<p style="font-size: 13px;padding-top: 24px;text-align: center;">By signing up you agree to the <u> terms of use</u> and <u>privacy policy</u></p>
</div><!--end .card-body -->
</div><!--end .card -->
</div>
</div>
</div>
I have one simple template page where user can select two dependent drop-downs, AreaOfPractice and RequestsType and the other 'title' text filled, as user selects on the get started he will redirect to the new page where he will the requests filling form with 5-6 fields wherein 3 fields would be prefilled with user's input from the previous page.
I have tried to do it with jQuery & Ajax.
$.ajax({
url:"getAops",
type: "POST",
data:{_token:csrf_token},
success:function (result) {
var options_grp = "";
options_grp = "<option></option>";
for(i=0;i<result.length;i++){
options_grp = options_grp + "<option value='" +result[i].name+"_"+result[i].id+"'>"+result[i].name+"</option>"
}
$(options_grp).appendTo('#aops');
$('#aops').select2({
placeholder: "Select Category *"
});
}
});
$('#aops').on('change',function () {
$.ajax({
url:"getRequestTypes",
type: "POST",
data:{_token:csrf_token,aop_id:$('#aops').val().split('_')[1]},
success:function (result) {
$('#request_type').empty().trigger('change');
$('#req_options').css('display','block');
var options = "<option></option>";
for (var i = 0;i<result.length;i++){
options = options + "<option value='" +result[i].name+"_"+result[i].id+"'>"+result[i].name+"</option>";
}
$(options).appendTo('#request_type');
$('#request_type').select2({
placeholder: "Select Request Type *"
})
}
});
});
$('#post_request').on('click', function () {
var data = new FormData();
if($('#aops').select2('data') != null){
aop = $('#aops').select('data').text;
}
if($('#request_type').select('data') != null){
request_type = $('#request_type').select2('data').text;
}
data.append("aop", $('#aops').val());
data.append("request_type",$('#request_type').val());
data.append("title",title);
if(aop == "" || request_type == "" || title == "" ){
show_notification("error","Please fill all required fields");
return false;
}else {
$.ajax({
url: "createNewRequest",
type: "POST",
async: false,
data: data,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function () {
$('#aops').html(aop);
$('#request_type').html(request_type);
$('#title').val(title);
return true;
},
contentType: false,
processData: false
});
}
});
Here is a basic example to the technique.
You can save many fields by making an object like {name-field:name-data,x-field:x-data} and so on. You can retrieve this on other page and set it to the form inputs.
$("#setbutton").click(()=>localStorage.setItem("form-data",$("#set").val()))
$("#getbutton").click(()=>{
var data=localStorage.getItem("form-data")
$("#get").val(data);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="set"/>
<button id="setbutton">Set</button>
<br><br><br>
<input type="text" id="get"/>
<button id="getbutton">Get</button>

Form in ajax post method sends empty object

I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.

Post request with multiple type of data

I've created below form, which when the submit button is pressed is suppose to make a post request and in the php add this to mysql. However i keep getting a Post 500 (Internal Server Error) when the post request is executed.
form
<form method="post" action="">
<div class="reg_section personal_info">
<input type="text" id="title" value="" placeholder="Campnavn" required="required" maxlength="25">
<textarea name="textarea" id="description" value="" placeholder="Beskrivelse" required="required" minlength="100"></textarea>
<div class="upload">
<input type="file" name="upload" accept="image/*" id="image" />
<span class="fileName">Select file..</span>
</div>
</div>
<div>
<span class="submit" style="text-align: left; padding: 0 10px;"><input type="submit" id="insert" value="Tilføj"></span>
<span class="submit" style="text-align: right; padding: 0 10px;"><input TYPE="button" value="Fortryd" onclick="div_hide();"></span>
</div>
</form>
javascript
$( document ).ready(function() {
$("#insert").click(function(e) {
var description = $('#description').val();
var title = $('#title').val();
var image = $("#image").serialize()
$.post("insert.php",
{
title: title,
body: description,
longitude: currentMarker.lng(),
latitude: currentMarker.lat(),
image: image
}, function (data) {
}).error(function () {
});
});
});
insert.php
<?php
include('config.php');
if (isset($_POST['title']) && isset($_POST['body']) && isset($_POST['longitude']) && isset($_POST['latitude']))) {
$target_dir = "image/";
$title = $_POST['title'];
$body = $_POST['body'];
$longitude = (float)$_POST['longitude'];
$latitude = (float)$_POST['latitude'];
$image = $_FILES['image'];
$strSQL = $db->query("INSERT INTO camps (title, body, longitude, latitude, image) VALUES ('$title', '$body', '$longitude','$latitude', '$image')");
}
?>
try this please, I change the <form> tag I add id and name,
and change the submit button to normal button
<button type="button" onclick="postdata();" id="insert" >Tilføj</button>
after I define a onclick function to button...
form
<form id="FormData" name="FormData">
<div class="reg_section personal_info">
<input type="text" id="title" value="" placeholder="Campnavn" required="required" maxlength="25">
<textarea name="textarea" id="description" value="" placeholder="Beskrivelse" required="required" minlength="100"></textarea>
<div class="upload">
<input type="file" name="upload" accept="image/*" id="image" />
<span class="fileName">Select file..</span>
</div>
</div>
<div>
<span class="submit" style="text-align: left; padding: 0 10px;">
<button type="button" onclick="postdata();" id="insert" >Tilføj</button>
</span>
<span class="submit" style="text-align: right; padding: 0 10px;">
<input TYPE="button" value="Fortryd" onclick="div_hide();"></span><br><br>
<span id="result" style="color:#9B0E11; font-size:13px; font-weight:700"></span>
</div>
</form>
JavaScript
<script type="text/javascript">
function postdata() {
var description = $('#description').val();
var title = $('#title').val();
var image = $("#image").serialize();
$.ajax({
type: 'POST',
url: 'insert.php',
data: {
desc: desctiption,
title: title,
image:image,
longitude: currentMarker.lng(),
longitude: currentMarker.lat(),
},
success: function (answer) {
$("#result").html(answer) // if you wanna get response from insert.php
$("#FormData")[0].reset(); // if you wanna reset form after submit
}
})
}
</script>
PS: in insert.php you add more one ")" in end of if statement you must delete it
if (isset($_POST['title']) && isset($_POST['body']) && isset($_POST['longitude']) && isset($_POST['latitude'])){

Categories

Resources