Checkbox array insert with ajax - php

I am creating the form with checkbox, like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form7" method="POST">
<li>
<label for="Produto">Estado Resguardo</label>
<ul class="flex-outer">
<div class="form-check">
<label class="toggle">
<input type="checkbox" id="Resguardo1" name="Resguardo[]" value="Cheiro"> <span class="label-text"> Cheiro</span>
</label>
</div>
<div class="form-check">
<label class="toggle">
<input type="checkbox" id="Resguardo2" name="Resguardo[]" value="Deteriorado"> <span class="label-text">Deteriorado</span>
</label>
</div>
<div class="form-check">
<label class="toggle">
<input type="checkbox" id="Resguardo3" name="Resguardo[]" value="Molhado/Sujo"> <span class="label-text">Molhado/Sujo</span>
</label>
</div>
</ul>
</li>
<li style="float: right">
<button type="button" class="btn btn-danger btn7" data-dismiss="modal">Cancelar</button>
<button class="btn btn-success" onclick="inserir_registo6()">Gravar</button>
</li>
</form>
I am sending the data this way:
function inserir_registo6()
{
var dadosajax = {
'Resguardo' : $("#Resguardo").val()
};
$.ajax({
url: './registosobremesa',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$('.form7')[0].reset();
}
});
}
In the script with php I have as follows:
$Colaborador = $_SESSION['usuarioId'];
if (isset($_POST["Resguardo"])) {
$optionArray = $_POST["Resguardo"];
$teste = implode(',', $optionArray);
for ($i=0; $i<count($teste); $i++) {
$query = 'INSERT INTO RegistoResguardos (``Resguardo`, `Colaborador`) VALUES ( ?, ?)';
$stmt = $conn->prepare( $query );
$stmt->bind_param("ss", $teste, $Colaborador);
$stmt->execute();
}
Returns no error in the browser console, but also does not insert into the database table.
I also tried this on ajax:
function inserir_registo6()
{
var dadosajax = {
'Resguardo' : $("input[name=Resguardo]").val()
};
$.ajax({
url: './registosobremesa',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$('.form7')[0].reset();
}
});
}
But I still have the same problem of not inserting into the database.

I solved the problem by doing this:
(function ($) {$(document).ready(function(){
$("#form7").submit(function(e){
e.preventDefault();
var Utente = form7.Utente.value;
var Quantidade1 = form7.Quantidade1.value;
if (!Utente) {
alert('Preencha o campo com o Utente');
form7.Utente.focus();
return false;
}
if (!Quantidade1) {
alert('Preencha o campo com a Quantidade');
form7.Quantidade1.focus();
return false;
}
$.ajax({
type: "POST",
url: "./registoresguardos",
data: $("#form7").serialize(), // serializes the form's elements.
dataType: "json",
success: function (data)
{
$(".success_messages").removeClass('hide'); // success message
},
error: function(data){
$(".error_message").removeClass('hide'); // error message
},
complete: function()
{
$('.form7')[0].reset();
}
});
});
});
})(jQuery);

Related

AJAX post form with file upload

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
});
});

Ajax keeps refreshing the entire page instead of just the comment section

I'm working on a project with codeigniter and I decided to implement ajax into the comment section so that the whole page is not refreshed when the user submits his comment. The comment is displayed automatically but the page keeps getting refreshed. I don't know what I am doing wrong here but any help would be appreciated.
MODEL:
public function create_comments($post_id){
$data = array(
'post_id' => $post_id,
'body' => $this->input->post('body'),
'users_id' => $this->session->userdata('user_id')
);
return $this->db->insert('comments',$data);
}
CONTROLLER:
public function create($post_id){
//checking if user is logged in
if(!$this->session->userdata('isLoggedIn')){
redirect('users/login');
}
$slug = $this->input->post('slug');
$data['post'] = $this->post_model->get_posts($slug);
$this->form_validation-> set_rules('body', 'Comment', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
$this->session->set_flashdata('comment_error', 'comment field is empty comment');
redirect('posts/'.$slug,'refresh');
} else {
$this->comments_model->create_comments($post_id);
redirect('posts/'.$slug);
}
}
VIEW:
<?php echo form_open_multipart('comments/create/'.$post['id'], 'id="comnt"'); ?>
<div class="panel-footer">
<!--//THIS IS THE FIELD WHICH COMMENTS WOULD BE ADDED-->
<div class="">
<input type="hidden" name="slug" value="<?php echo $post['slug']; ?>">
<small class="text-center text-danger"><?php echo form_error('body'); ?></small>
<div class="input-field">
<textarea id="icon_prefix2" name="body" class="materialize-textarea" rows="3"></textarea>
<label for="icon_prefix2">Comments</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" id="submit">comment <i class="material-icons right">send</i></button>
</div>
</div>
</form>
AJAX:
$('#submit').click(function() {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Use jquery preventDefault() function to prevent your form to be submitted
$('#submit').click(function(e) {
e.preventDefault();
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>"+"comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Try the done property to set the success handler. Also, as this is an event over a DOM element, you should attach it when the DOM is ready:
$(document).ready(function() {
$('#submit').click(function(event) {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
}).done(function(msg) {
alert(msg);
}).fail(jqXHR, textStatus) {
alert('ERROR: ' + textStatus);
});
// return is not necessary here
// return true;
});
$("#comnt").submit(function(e) { // Prevent the form submitting
e.preventDefault();
});
});
As this already attaches an event, you should remove the onclick="comment()" property from your button:
<button class="btn waves-effect waves-light" type="submit" id="submit">comment
<i class="material-icons right">send</i>
</button>
Try this hope it work
$('#submit').click(function(event) {
e.preventDefault(); //stop actual action of browser
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Change button type button instead of submit
<button class="btn waves-effect waves-light" type="button" name="action" id="submit">comment
<i class="material-icons right">send</i>
</button>

Cannot post data with JQuery and Ajax

I'm new with php. I'm trying to post some input with ajax but it doesn't work.
This is my HTML for input:
<div class="form-group">
<h3>Answer:</h3>
<div class="input-group">
<textarea name="q1" id="q1" class="form-control" rows="4" ></textarea>
</div>
</div>
<button type="button" id="button" class="btn btn-primary btn-lg">Submit</button>
And this is my jquery function to post data:
$(function(){
$('button').click(function(){
var q1= $('#q1').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
q1: q1
},
success: function (response) {
console.log( response);
}
});
});
});
My test.php is a simple code to display the input:
<?php
$q1= $_POST['q1'];
echo $q1;
?>
I don't know why in my test.php I get this error : Notice: Undefined index: q1 in C:\xampp\htdocs\series\file\test.php on line 2
Can anyone tell me where is the issue?
First of all you are trying to post a json data to your php file so jQuery may not create correct payload for your request since you getting undefined index:q1. Can you try the code below;
$(function () {
$('button').click(function () {
var q1 = $('#q1').val();
$.ajax({
type : 'post',
url : 'test.php',
data : "q1="+q1,
success : function (response) {
console.log(response);
}
});
});
});
Try this:
$('document').ready(function(){
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'url',
type: 'POST',
data: formData,
async: false,
success: function (data)
{
alert(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
}
<form id="data" method="post">
<div class="form-group">
<h3>Answer:</h3>
<div class="input-group">
<textarea name="q1" id="q1" class="form-control" rows="4" ></textarea>
</div>
</div>
<input type="submit" id="button" class="btn btn-primary btn-lg">
</form>

Cancel submit jquery

This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/

how to find a parent?

i have a problem with finding parent for form in this code:
<li class="comment<?php echo $comment[id]?>">
<div class="comment-content">
<div class="comment-top">
<div class="comment-nme">
<?php echo $comment[name]?>
</div>
<div class="comment-dt">
<?php echo $comment[dt]?>
</div>
</div>
<div class="comment">
<?php echo $comment[comment]?>
</div>
<a class="reply" href="#comment<?php echo $comment[id]?>">Ответить</a>
</div>
<div class="answer-form">
<form method="post" name="answer-form" class="ans">
<textarea class="comment-textarea" name="comment"></textarea>
<div class="a-comment-inputs">
<input type="hidden" name="parent_id" value="<?php echo $comment[id]?>">
<input type="hidden" name="status" value="new">
<div class="a-comment-name">
Имя</br>
<input type="name" name="name" class="a-comment-name">
</div>
<div class="a-comment-email" >
Eмейл</br>
<input type="email" class="a-comment-email" name="email">
</div>
</div>
<div class="comment-apply">
<button value="submit" onclick="return sendDataChild();" class="answer-but">Добавить</button>
</div>
</form>
</div>
<?php if($comment[childs]){ ?>
<ul class="commentsRoot<?php echo $comment[id]?>">
<?php echo commentsString($comment[childs]) ?>
</ul>
<?php } ?>
</li>
i use this jQuery function:
function sendDataChild() {
var form = $('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};
but it select every form that find on button click.
Can somebody advise how to solve it?
one possible solution
<button value="submit" onclick="return sendDataChild(this);" class="answer-but">Добавить</button>
then
//pass the clicked button reference then find the parent form of the button
function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};
Bind submit event on the form and pass the object to the form object to your method
$(document).ready(function(){
$("form[name='answer-form']").on('submit', function(){
sendDataChild($(this));
});
});
function sendDataChild(form) {
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form.reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};

Categories