Fetch method post - javascript

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

Related

FETCH JavaScript PHP process the data on the server sent with fetch

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"))

Showing "Thank you message" with AJAX and running php script

I have a form and I want when someone click submit, run upis.js write thank you message and run php script for inserting into database. For now it takes values I can see them in my url but it doesnt run upis.php. Can you tell me why?
Here is the code for form:
<form>
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>
and upis.js
<script>
function upis(){
var ime = document.getElementById("ime").value;
var prezime = document.getElementById("prezime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var prezime_slavljenik = document.getElementById("prezime_slavljenik").value;
var email = document.getElementById("email").value;
var dataString = "ime="+encodeURIComponent(ime)+"&prezime="+encodeURIComponent(prezime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik)+"&prezime_slavljenik="+encodeURIComponent(prezime_slavljenik)+"&email="+encodeURIComponent(email);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
data: dataString,
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
and upis.php
<?php
require_once 'include/db.php';
require_once 'include/functions.php';
$allowed_params = allowed_post_params(['ime', 'prezime', 'ime_slavljenik', 'prezime_slavljenik', 'email','submit']);
// niz sadrzi dozvoljene maksimalne duzine za sva polja
$fields_lengths = ['ime' => 64, 'prezime' => 64, 'ime_slavljenik'=>64, 'prezime_slavljenik'=>64, 'email' => 64];
// provera da li su polja odgovoarajuce duzine
foreach ($fields_lengths as $field => $length) {
if (!has_length($_POST[$field], ['min' => 0, 'max' => $length])) {
header('Location: greska.html');
die();
}
}
try {
// Priprema upita za unos podataka u bazu
$prep = $db->prepare("INSERT INTO prijavljeni (ime, prezime, ime_slavljenik, prezime_slavljenik, email) VALUES(:ime, :prezime, :ime_slavljenik, :prezime_slavljenik, :email)");
$prep->bindParam(':ime', $ime);
$prep->bindParam(':prezime', $prezime);
$prep->bindParam(':ime_slavljenik', $ime_slavljenik);
$prep->bindParam(':prezime_slavljenik', $prezime_slavljenik);
$prep->bindParam(':email', $email);
$ime = isset($allowed_params['ime']) ? $allowed_params['ime'] : "";
$prezime = isset($allowed_params['prezime']) ? $allowed_params['prezime'] : "";
$ime_slavljenik = isset($allowed_params['ime_slavljenik']) ? $allowed_params['ime_slavljenik'] : "";
$prezime_slavljenik = isset($allowed_params['prezime_slavljenik']) ? $allowed_params['prezime_slavljenik'] : "";
$email = isset($allowed_params['email']) ? $allowed_params['email'] : "";
// izvrsavanja upita
$rez = $prep->execute();
$htmltable = "Hvala na poslatoj prijavi.";
echo $htmltable;
} catch (PDOException $e) {
echo 'greska kod upita';
}
?>
I cant see what can be problem here because js takes values from form but doesnt actually run upis.php(it doesnt take url upis.php) I dont understand why..
If you're developing your application using Firefox or Chrome look in the network tab of web inspector to ensure the JavaScript resource successfully sends an XHR request. Check the URL that the POST XHR request is sent to.
Is the URL set correctly in the url property of the AJAX settings?
You may need to prepend "upis.php" with a forward slash e.g. "/upis.php"
You should call script from index.php, you missed action and method in form
<form action="upis.php" method="post">
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>

How to Call Ajax from HTML/JS to start PHP Function?

I'm working on a code that will show an alert when form is submitted and then redirect back to home page. If an empty form is submitted, I want to show an error alert. I realize that I cannot call PHP from onclick, and that I need to instead call a JS function that will start my PHP function. Can someone tell me if my PHP code is on the right track, and how to initialize the AJAX function? Trying to do this WITHOUT JQuery. Thanks!
html
<form method="POST" action="contact.php">
<label for='message'>Leave a Message:</label> <br><br>
<textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
<input type="submit" name='submit' value="send!" onclick="startajax()"/>
</form>
and php
<?PHP
$subject="New Message!";
$message=$_POST ["message"];
function leavemessage () {
if(!empty($_POST['message'])) {
echo '<script type="text/javascript">
function error(){
alert("Error!");
window.location.replace=(contact.html);}
</script>';
}
else
{
{mail ($email, $subject, $message, "From:".$from);}
echo '<script type="text/javascript">
function confirmation(){
alert("Message Sent!");
window.location.replace (index.html);}
</script>';
}
}
?>
You can do this with jquery ajax to complete your request like this:
HTML:
<form method="POST" id="contact-form" onsubmit="return startajax()" >
<label for='message'>Leave a Message:</label> <br><br>
<textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
<input type="submit" name='submit' value="send!"/>
</form>
PHP:
<?PHP
$subject="New Message!";
$message=$_POST ["message"];
if(!empty($message)) {
//your email code here
exit(json_encode(array('error' => 0, 'errorMessage' => '')));
} else {
exit(json_encode(array('error' => 1, 'errorMessage' => 'Message is required')));
}
}
?>
Jquery:
<script>
var startajax = function(){
var url = 'contact.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) { // success
$('#contact-form')[0].reset();
alert('SUCCESS MESSAGE');
} else { // error
alert(response.errorMessage);//form is invalid
}
}
})
return false;
}
</script>
Just make sure you have jquery library included to your page.
As per request, Without jQuery code below:
HTML:
<form method="POST" id="contact-form" action="contact.php" >
<label for='message'>Leave a Message:</label> <br><br>
<textarea rows="15" cols="45" name="message" id="message" ></textarea>
<?php if (isset($_GET['error'])) { ?>
<p style="color:red;">Message is required</p>
<?php } ?>
<br><br>
<input type="submit" name='submit' value="send!"/>
</form>
PHP:
<?PHP
if (isset($_POST) && !empty($_POST)) {
$subject="New Message!";
$message=$_POST ["message"];
if(!empty($message)) {
//your email code here
echo '<script>window.location.href="index.html"</script>';
} else {
echo '<script>window.location.href="index.html?error=1"</script>';
}
}
}
?>

call php file from javascript / Google recaptcha

Many apologies if the answer to my question is obvious.
I am trying to incorporate the Google reCaptcha into my website.
This is the javascript in the HEAD of my page:
var onSubmit = function(token) {
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
The reCaptcha is visible and working.
The above code gives me the result of 'success:' BUT is not processing the form using the call to the php file.
All other scripts on the page are working fine.
Here is the contact.php code:
I've made those changes to my code. No change in the result however. Here is the code for the php file:
<?php
//contact form submission code
//Validate data on the form
// define variables and set to empty values
$name = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = contact_input($_POST["name"]);
$email = contact_input($_POST["email"]);
$message = contact_input($_POST["message"]);
}
function contact_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// put your email address here
$youremail = 'my#email.co.uk';
// prepare a "pretty" version of the message
// Important: if you added any form fields to the HTML, you will need to add them here also
$body = "Contact Form from Wilderness Canoe website just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['email'] && !preg_match( "/.+#.+\..+/i", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers );
}
?>
and the code for the form:
<form id="form" method="post" action="assets/php/contact.php" onsubmit="return validate();">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-account mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="name"> Full Name</label>
<input class="mdl-textfield__input " type="text" id="name" required name="name">
<!--error msg ><span class="mdl-textfield__error">Only alphabet and no spaces, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-email mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="email">Your Email</label>
<input class="mdl-textfield__input " type="text" id="email" required name="email">
<!--error msg ><span class="mdl-textfield__error">Valid email only, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-comment-text mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="message">Your Message/Comment</label>
<textarea class="mdl-textfield__input " type="text" rows= "1" max-rows="4" id="message" name="message"></textarea>
</div>
<!-- antispam --><p class="antispam">Leave this empty: <input type="text" name="url" /></p>
<!-- RECAPTCHA -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div class="clear"><button type="submit" value="Send" name="submit" id="mc-embedded-contact" class="send">Submit</button></div>
</form>
The complete javascript:
<script type="text/javascript">
var onSubmit = function(token) {
var formData = $("#form").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
var onloadCallback = function() {
grecaptcha.render('mc-embedded-contact', {
'sitekey' : '6Ldbfg8UAAAAAAaWVBiyo4uGfDqtfcnu33SpOj6P',
'callback' : onSubmit
});
};
</script>
Your ajax request doesnt send any form data in your code. You should add your form data like this:
var onSubmit = function(token) {
var formData = $("#yourFormId").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};

I can see the posted data in the url but nothing happen

its been 2 days that im stuck with this error i can see the data that i post but the next page do not load
when i submit i get http://localhost:8000/android/www/login1.html?username=**********&password=****************&action=SignIn
thanks for ur help.
<script type="text/javascript">
$(document).ready(function() {
$('button[type=submit]').submit(function () {
var username = $('input[name=username]').val();
var password = $('input[name=password]').val();
$.ajax({
type: "POST",
url: "http://localhost/server1/login1.php",
data: $('#login').serialize(),
dataType: 'json',
success:function(json){
if(json.status === 'success') {
alert('Tout est bon');
window.location.href="TestPorteur.html";
}
else{
window.location.href="ResetPassword.html";
}
}
/* */
});
return false;
});
});
</script>
<div class="login-bottom" id="login">
<form id="form" >
<div class="text">
<input type="text" placeholder="Numéro Téléphone" id="username" name="username" />
<span class="men"></span>
<div class="clear"> </div>
</div>
<div class="text">
<input type="password" placeholder="Password..." id="password" name="password" />
<span class="pass"></span>
<div class="clear"> </div>
</div>
<div class="remember">
<div class="remember-top">
Mot de passe oublié?
</span>
</div>
<div class="send">
<button type="submit" id="action" name="action" value="SignIn">Sign In</button>
</div>
<div class="clear"> </div>
</div>
</form>
</div>
<?php
header('Access-Control-Allow-Origin: *');
include('conn.php');
if(isset($_POST["username"])&& isset($_POST["password"])){
$password = $_POST['password'];
$username = $_POST['username'];
echo"Veuillez remplir les champs";
}
$sql7="select * from utilisateur WHERE username='$username'";
$result=mysqli_query($conn, $sql7);
while($result1 = mysqli_fetch_array($result)){
$var=$result['password'];}
if($password!='$var'){
$status="passworderrone";
echo json_encode(['status' => $status]);
}
if($password=='$var'){
$vari='11';
function getRemoteIp(){
if( !ini_get('register_globals') ) {
return $_SERVER['REMOTE_ADDR'];
} else {
return #$REMOTE_ADDR;
}
return "";
}
$ip = getRemoteIp();
$sql2="select * from session WHERE username='$username'";
$usrname=mysqli_query($conn, $sql2);
while($result = mysqli_fetch_array($usrname)){
$vari=$result['username'];
}
if('$vari'==$username){
$status= "dejainscris";
echo json_encode(['status' => $status]);
$sql3 = "INSERT INTO session (username, tps_connx, tcpip)
VALUES ('$username',NOW(),'$ip')";
$res3=mysqli_query($conn, $sql3);
}
else {$status="premiereinscription";
echo json_encode(['status' => $status]);
}
}
?>
There are two things you can do to fix this.
Remove type=submit from button and in JS instead of catching submit event, you should catch click event.
<button id="action" name="action" value="SignIn">Sign In</button>
and in JS you should look for click event.
$('button#action').click(function () {
The reason for this type=submit directly submit the form. So first that needs to be checked, then look for click event and do your thing.
Second way to do this is that instead of catching submit event on button, look for submit event on form because it is meant for forms.
so your JS should
$('#form').submit(function (e) {
e.preventDefault();
...

Categories

Resources