i found this code in jquery / ajax i edited a little but for some reason the output doesn't have a value.
here my code (javascript file):
function fototoevoegen(){
var fotonaam = document.getElementById('fotonaam').value
var text = document.getElementById('text').value
var file = new FormData();
console.log(fotonaam);
console.log(text);
console.log(file);
file.append('file',$('.file')[0].files[0]);
$.ajax({
url: "../assets/fototoevoegen.php",
type: "POST",
data:{ file, fotonaam, text},
processData: false,
contentType: false,
cache:false,
beforeSend:function(){
$(".result").text("Loading ...");
},
success:function(data){
$(".result").html(data);
alert(data);
}
});
return false;
}
the console.log does have value's but the output file (fototoevoegen say's undifend index to all vars :/
can someone help me on this ! thanks
//HTML file//
<!DOCTYPE html>
<html>
<head>
<title>CMS V1.2</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../css/style2.css">
</head>
<body>
<div class="content">
<h2>Foto Database</h2>
<br/>
<form method="post">
<input type="hidden" name="size" required="required" value="">
<div>
<input type="file" id="file" class="file">
</div>
<br/>
<div>
<input type="text" id="fotonaam" placeholder="fotonaam">
</div>
<br/>
<div>
<textarea id="text" cols="40" rows="4" placeholder="foto omschrijving"></textarea>
</div>
<br/>
<div>
<input type="button" value="Upload Foto" onclick="fototoevoegen();">
</div>
<br/>
</form>
</div>
<div class="container3Titel">
<h2>Alle foto's in het database </h2>
</div>
<div class="container3">
<?php foreach ($fotos as $foto){ ?>
<div class ="container3item">
<form method ="get">
<h2><?= $foto['foto_naam']?></h2>
<img src="<?= $foto['foto_url']?>" width="300" height="170"/>
<p> <?= $foto['foto_omschrijving']?> </p>
<p> <?= $foto['foto_url']?> </p>
<input type=hidden id="fotourl" value="<?= $foto['foto_url']?>">
<input type=hidden id="foto_id" value="<?= $foto['foto_id']?>">
<input type="button" name="verwijderen" value="Foto Verwijderen" onclick="fotoverwijderen();">
</form>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
Sent information to this file (../assets/fototoevoegen.php)
<?php
include_once('../includes/connection.php');
// de folder waar alle foto's worden opgeslagen
$folder = "../foto/";
$info = $_FILES["file"]["name"];
// extentie herkennen van het bestand en deze toevoegen aan de url
$ext = pathinfo($info, PATHINFO_EXTENSION);
$ext = '.'.$ext;
$naam = $_POST['fotonaam'].$ext;
$full_path = $folder.$naam;
// omschrijving en foto naam aan variable geven voor insert query
$omschrijving = $_POST['text'];
$fotonaam = $_POST['fotonaam'];
echo($naam);
echo($fotonaam);
echo($omschrijving);
echo($info);
// de foto of het bestand opslaan in een map (foto's)
if (move_uploaded_file($_FILES['foto']['tmp_name'], $full_path)) {
//als het uploaden gelukt is voer je een query uit naar de database zodat deze later nog gebruikt kan worden.
$query = $pdo->prepare("INSERT INTO fotobibliotheek (foto_naam,foto_omschrijving,foto_url) VALUES(?,?,?)");
$query->bindValue(1,$fotonaam);
$query->bindValue(2,$omschrijving);
$query->bindValue(3,$full_path);
$query->execute();
// succes melding weergeven en redirect naar pagina bibliotheek
echo "De foto is opgeslagen";
} else {
//fout melding als er niet geupload kan worden
echo 'uploaden mislukt';
}
?>
I think the problem is here:
data:{ file, fotonaam, text}
You need to append your values to your formData object and then send that object.
If you rearrange your code a little so that you handle the "submit" event of your form, instead of your button, then this becomes quite straightforward:
HTML:
<form id="fotoForm" method="post" enctype="multipart/form-data">
<input type="hidden" name="size" required="required" value="">
<div>
<input type="file" id="file" name="file" class="file">
</div>
<br/>
<div>
<input type="text" id="fotonaam" name="fotonaam" placeholder="fotonaam">
</div>
<br/>
<div>
<textarea id="text" cols="40" rows="4" name="text" placeholder="foto omschrijving"></textarea>
</div>
<br/>
<div>
<input type="submit" value="Upload Foto">
</div>
<br/>
</form>
JavaScript:
$(function() {
$("#fotoForm").submit(function(event) {
event.preventDefault(); //prevent default non-ajax postback
var data = new FormData(this); //pass the form into the formData object
$.ajax({
url: "../assets/fototoevoegen.php",
type: "POST",
data: data,
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
$(".result").text("Loading ...");
},
success: function(data) {
$(".result").html(data);
alert(data);
}
});
});
});
See also Uploading both data and files in one form using Ajax? for a similar example
Related
I have this doubt of how to process the data brought from my form, I am using javascript with a fetch to receive the data of the form, but I have the doubt of how I should process them in php, nor is the click event of the send button working, the problem is that the server seems not to be receiving the array sent from javascript with the data, agradesco if you give me any source to delve into the topic of fetch api, I am new to javascript and php
my Javascript
registrar.addEventListener("click", () => {
fetch("../add.php", {
method: "post",
body: new FormData(frm) //frm es el id del formulario
}).then(response => response.text()).then
(response => {
// console.log(response);
// si la respuesta sel servidor es "ok" arroja una alerta personalizada
if (response == "ok") {
Swal.fire({
icon: 'success',
title: 'Registrado',
showConfirmButton: false,
timer: 1500
})
frm.reset();
}
}
)
})
<form action="" method="post" id="frm">
<div class="form-group">
<br>
<div class="form-group">
<div class="form-group">
<input type="text" name="name_usu" id="name_usu" class="form-control form-control-md" placeholder="Nombre completo" required >
</div>
<input type="text" name="phone_usu" id="phone_usu" class="form-control form-control-md" placeholder="Numero de teléfono" required>
</div>
<input type="email" name="nom_usu" id="nom_usu" class="form-control form-control-md" placeholder="Email" required></div>
<input type="text" name='torreApto' id="Torre_apto" class="form-control form-control-md" placeholder="Torre y apartamento" required>
<label for="FormControlSelect1" class="text-light">Escoja tipo de residente</label>
<select class="form-control" name="sel_apto" id="sel_apto" required>
<option selected>Propietario</option>
<option selected>Arrendado</option>
<option selected>Otro</option>
</select>
<div class="form-group">
<label for="Textarea1" class="text-light">Mensaje a enviar</label>
<textarea class="form-control" name="mensaje" id="Textarea1" rows="3"></textarea>
</div>
<br>
<input type="button" class="btn btn-outline-light btn-block border-light text-light font-weight-bold" value="registrar" id="registrar">
</form>
addRegister.php
enter if (isset($_POST)) {
$nombre = $_POST['name_usu'];
$telefono = $_POST['phone_usu'];
$email = $_POST['nom_usu'];
$torreApto = $_POST['torreApto'];
$arrendado = $_POST['sel_apto'];
$mensaje = $_POST['mensaje'];
require("connect.php");
// script guardando en la base de datos
$query = $con->prepare("INSERT INTO informacion(nombre,telefono,email,torreApto,arrendado,mensaje) VALUES (:nom, :tel, :ema, :torr, :arr, :men)");
$query->bindParam(":nom", $nombre);
$query->bindParam(":tel", $telefono);
$query->bindParam(":ema", $email);
$query->bindParam(":torr", $torreApto);
$query->bindParam(":arr", $arrendado);
$query->bindParam(":men", $mensaje);
//ejecuta el script
$query->execute();
$con = null;
echo "ok";
}
Try to add
$_POST = file_get_contents('php://input');
at the beginning of your file.
You are not initializing the FormData correctly. To fill it with the data of a form you have to pass in a reference to the form. Currently you are passing in an undefined variable, that just happens to be the same as the ID of the form.
You need to get a reference to the form using, for example, getElementById:
new FormData(document.getElementById("frm"))
I'm trying to show the results of the submit button on the same page. I tried with several codes from here (specially this: Display result in the same page with PHP) but it didn't work.
This is how my html page looks like now:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".mybutton").click(function() {
$.ajax({
type: "post",
url: "https://catadordealfajores.com/wp-content/uploads/2020/calc.php",
data: $("form").serialize(),
success: function(result) {
$(".myresult").html(result);
}
});
});
});
</script>
</head>
<body>
<form>
<input type="radio" name="causa" value="si">
<label for="male">Sí</label><br>
<input type="radio" name="causa" value="No">
<label for="female">No</label><br>
<h3>¿Cuántos años trabajaste?</h3>
<input type="text" name="anios">
<br>
</form>
<button class="mybutton">Calculate</button>
<div class="myresult"></div>
</body>
</html>
Before Ajax, I had:
<!DOCTYPE html>
<html>
<body>
<h1>Calculadora de indemnización</h1>
<form action = "https://catadordealfajores.com/wp-content/uploads/2020/calc.php" method = "post">
<h3>¿Te despidieron con causa?</h3>
<p>Si trabajaste más de 3 meses, se considera 1 año. Si trabajaste 1 año y 3 meses, se consideran 2 años. Y así.</p>
<input type="radio" name="causa" value="si">
<label for="male">Sí</label><br>
<input type="radio" name="causa" value="No">
<label for="female">No</label><br>
<h3>¿Cuántos años trabajaste?</h3>
<input type="text" name="anios">
<br>
<h3>¿Cuál era tu sueldo?</h3>
<input type="text" name="sueldo">
<br>
<br>
<input type="submit" value = "Enviar">
</form>
</body>
</html>
Website: http://abogadoslaboralessanmartin.com.ar/7122-2/
Thank you very much
Could it be?
"return false;" so that it doesn't go to another page.
<script type="text/javascript">
$(document).ready(function() {
$('body').on('submit', 'form', function() {
$.ajax({
type: "post",
url: "https://catadordealfajores.com/wp-content/uploads/2020/calc.php",
data: $("form").serialize(),
success: function(result) {
$(".myresult").html(result);
}
});
return false;
});
});
</script>
I created a contact form for a Wordpress theme (custom) using jQuery/Ajax. When I tested the wp_send_json_sucess with "it works" it returned as suspected. However, when I added $formdata and the name of a field on the form the from returned undefined in the JS alert box. I'm pretty sure I've typed it correctly, as I was following this tutorial: https://www.youtube.com/watch?v=LYvx_L9ESn0. But I cannot seem to get it to work.
Code for functions.php here
add_action('wp_ajax_contact', 'contact_form');
add_action('wp_ajax_nopriv_contact', 'contact_form');
function contact_form()
{
$formdata = [];
wp_parse_str( $_POST['contact'], $formdata );
wp_send_json_success( $formdata ['myName'] );
}
Form Code Here :
<form id="contact">
Name: <input type="text" name="myName" class="contactform
fields" placeholder="name"required><br><br>
Email: <input type="text" name="myEmail" class="contactform
fields" placeholder="you#youremail.com" required><br><br>
<p>What is your inquiry regarding?</p><be>
<input type="radio" name="reason" value="general">
<label for="news">General Inquiry</label><be>
<input type="radio" name="reason" value="course">
<label for="news">Courses</label><br>
<p class="contact_txt">Your Message:</p>
<textarea name="msg" rows="5" cols="700" placeholder="begin
typing message here..." required>
</textarea>
<p class="contact_txt">Would you like to subscribe to our
newsletter?</p>
<br>
<input type="checkbox" name="news" value="Subscribe">
<label for="news">Yes, I would like to subscribe</label>
<br>
<input class="btns" name="btn-send" id="mySubmit" type="submit" value="submit">
<input class="btns" name="btn-reset" id="myReset" type="reset" value="reset">
</form>
Script Here :
<script>
jQuery('#contact').submit( function(event){
event.preventDefault();
var endpoint = '<?php echo admin_url('admin-ajax.php' ); ?>';
var form = jQuery('#contact').serialize();
var formdata = new FormData;
formdata.append('action', 'contact');
formdata.append('contact', 'form');
jQuery.ajax(endpoint, {
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(res){
alert(res.data);
},
error:function(err){
}
})
})
</script>
I have an HTML code that when I submit it it falls into a fetch javascript that is in the post method, but it is updating the page and changing the url, it should not update the page and it is not inserting in the database.
html:
<form id='formcoment' onsubmit="fetchComent(e)">
<h1>Deixar um comentario:</h1>
<textarea rows="5" name="comentario" id="comentariopessoa" placeholder="Seu comentario aqui"></textarea>
<input type="submit" name="Enviar">
</form>
js fetch func:
function fetchComent(e){
e.preventDefault();
var coment = document.getElementById('comentariopessoa').value;
alert(coment)
fetch('comentar.php', {method: 'Post', body: JSON.stringify({ comentario: coment})}).then(function(resp){
if (resp.status == 200){
res.text().then(function(t){
document.getElementbyId('form').innerHTML = t;
})
}
})}
php:
<?php
require_once('conecta.php');
require_once('banco.php');
session_start();
$main = new Main();
if (!empty($_POST['comentario']) && !empty($_SESSION['nomeuser']) && !empty($_SESSION['iduser'])){
$comentario = $_POST['comentario'];
$nome = $_SESSION['nomeuser'];
$faceid = intval($_SESSION['iduser']);
$main->comentario = $comentario;
$main->nome = $nome;
$main->faceid = $faceid;
$main->insereComentario($conexao);
//header('location:./index.php');
?>
<form id='formcoment' onsubmit="fetchComent()">
<h1>Deixar um comentario:</h1>
<textarea rows="5" name="comentario" id="comentariopessoa"
placeholder="Seu comentario aqui"></textarea>
<input type="submit" name="Enviar">
</form>
<p>Comentario feito com sucesso!</p>
Sair
<?php
}else{
?>
<form id='formcoment' onsubmit="fetchComent()">
<h1>Deixar um comentario:</h1>
<textarea rows="5" name="comentario" id="comentariopessoa" placeholder="Seu comentario aqui"></textarea>
<input type="submit" name="Enviar">
</form>
<p>Preencha todos os campos</p>
Sair
<?php
}
?>
the site updates and changes the url to: ....com.br/mae2/?comentario=x+x+x+x+x+&Enviar=Enviar
I'm having issues running my code can any one verifiy it and tell me why it's not working properly?. My javascript doesn't seems to be working fine and the best that I got was the first vars to display. I'm really new to javascript thought.
<!DOCTYPE html>
<html>
<head>
<title> Template Suivi Client </title>
<link rel="icon" href="icone.ico" type="image/x-icon">
<link rel="stylesheet" href="aidememoire.css">
<script>
function myFunction {
alert();
var compte = form.inputcompte.value;
var nom = form.inputnom.value;
var telephone = form.inputtelephone.value;
var quand = form.inputdate.value;
var hdebut = form.inputheuredebut.value;
var hfin = form.inputheurefin.value;
var info = form.inputdescription.value;
document.getElementById("displaycompte").innerHTML = ("Numéro de Compte Client: " + compte);
document.getElementById("displaynom").innerHTML = ("Nom du Client : " + nom);
document.getElementbyId("displaytelephone").innerHTML = ("Numéro de téléphone : ");
document.getElementbyId("displayquand").innerHTML =("Date :" + quand);
document.getElementbyId("displayheured").innerHTML = ("Heure de début : " + hdebut);
document.getElementById("displayheuref").innerHTML = ("Heure de fin: " +hfin);
document.getElementById("displaydescription").innerHTML =("Déscription :" + info);
}
</script>
</head>
<body>
<h2 style="text-align: Center">
Template Suivi Client
</h2>
<form method="get">
Numéro de Compte Client :
<input type="text" name="inputcompte">
<br><br>
Nom du Client :
<input type="text" name="inputnom">
<br><br>
Numéro de téléphone :
<input type="text" name="inputtelephone">
<br><br>
Date :
<input type="date" name="inputdate">
<br><br>
Heure de début :
<input type="time" name="inputheuredebut">
<br><br>
Heure de fin :
<input type="time" name="inputheurefin">
<br><br>
Description du problème :
<input type="text" name="inputdescription">
<br><br>
<button type="button" onclick="myFunction(from.here)"> Soummettre </button>
</form>
<br><br><br>
<p id="displayfinal"> Produit final s'affichera ici </p>
<p id="displaycompte">
</p>
<p id="displaynom">
</p>
<p id="displaytelephone">
</p>
<p id="displayquand">
</p>
<p id="displayheured">
</p>
<p id="displayheuref">
</p>
<p id="displaydescription">
</p>
</body>
</html>`
You are using a variable form that is not defined anywhere.
You can sent the reference to the form from the button:
onclick="myFunction(this.form)"
Catch the parameter in the function:
function myFunction(form) {
try giving the form an id, like <form id="abc" method="GET">...</form>
then use $("#abc").off('submit'); (after the end of the form)
The info that I got from the console [ Uncaught TypeError: Cannot read property 'inputcompte' of undefined ] . It happens to all my variables