AJAX Maile sender + Multiple Attachment + Bootstrap plugin - php

i just have write script for sending emails. It take random email and send with random values - all works fine. Now i just want add option to send multiple images - Select random one and send with email.
I using bootstrap and i was find this plugin: http://plugins.krajee.com/file-input
But when i try to upload images i get 405 error. Meaby do you know any other way to send attachments with ajax?
Here is my code:
$("#dodawarka").submit(function(e){
e.preventDefault();
var tytul = $("#tytul").val();
var kontos = $("#lkonta").val();
var tresc = $("#tresc").val();
var jemail = $("#kemaile").val();
var jemail = $("#kemaile").val();
var dataString = 'listakont=' + kontos + '&tytul=' + tytul + '&tresc=' + tresc + '&emailjaki=' + jemail;
$.ajax({
type: "POST",
url: "dodaj.php",
data: dataString,
beforeSend: function(){
$('#tytul, #tresc, #przyciskx').prop( "disabled", true );
$('.wczytywanie').show();
},
success: function(){
$('#ddodaneok').show();
$('#dodawarka').slideUp();
$('#linkizwrotne').show();
},
error: function(){
$('#kurwasabledy').show();
}
});
return false;
});
And:
<form role="form" enctype="multipart/form-data" id="dodawarka" method="post">
<div class="form-group" id="listakont" style="visibility:hidden; position: absolute;">
<label for="listakont">Lista kont na które zostaną wysłane wpisy</label>
<textarea class="form-control" rows="10" id="lkonta" disabled></textarea>
</div>
<div class="form-group" id="ssssemail" style="visibility:hidden; position: absolute;">
<label for="ssssemail">Emaile z których będzie można wysyłam wpisy podaj w formacie</label>
<textarea class="form-control" rows="10" id="kemaile"></textarea>
</div>
<div class="form-group">
<label for="tytul">Podaj tytuł wpisu <em>+spintax</em></label>
<input type="tytul" class="form-control" id="tytul" required>
</div>
<div class="form-group">
<label for="tresc">Treść wpisu <em>+spintax</em></label>
<textarea class="form-control" rows="25" id="tresc" required></textarea>
</div>
<div class="form-group">
<label for="obrazki">Dodaj obrazki</label>
<input id="input-id" type="file" class="file" data-preview-file-type="text" multiple=true data-min-file-count="1">
</div>
<button type="submit" class="btn btn-default" id="przyciskx"><img src="img/infinity.gif" class="wczytywanie" /> Wyślij na zaplecza</button>
</form>

Try :
<input id="input-id" type="file" class="file" data-preview-file-type="text" multiple name="files[]" data-min-file-count="1">
Added: name="files[]"and only multiple not multiple=true.
And in php do:
$output = '';
if(is_array($_FILES)){
foreach($_FILES['files']['name'] as $name => $value)
{
$file_name = explode(".", $_FILES['files']['name'][$name]);
$allowed_ext = array("jpg", "jpeg", "png", "gif");
if(in_array($file_name[1], $allowed_ext))
{$new_name = $userid.md5(rand()).".".$file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$targetPath = "uploadedimages/".$new_name;
include_once("connection.php"); // your connection to DB and select DB
$sql = "INSERT into images(userid, imgpath) VALUES ('$userid', '$targetPath')";
$query = $conn->query($sql);
if($query && move_uploaded_file($sourcePath, $targetPath))
{
$output .= '<div class="col-md-3"><img src="'.$targetPath.'" class="img-thumbnail" width="150px" height="180px"/></div>';
}
}
}
}
echo $output;

Related

File upload not submitting through ajax

I created a form upload which contains some inputs but when I submitted the form to ajax, ajax was unable to grap the file name.
I keep on getting Notice: Undefined index: userImage in C:\wamp\www\osun\i_admin\php_action\uploadImage.php on line 14 . userImage is the name of the file
index.php
<?php include('header.php'); ?>
<?php include('top.php'); ?>
<?php include('links.php'); ?>
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Worker of the Month</h2>
</div>
<!-- Basic -->
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div id="error" class="closeit"></div>
<div id="messages"></div>
<div class="body">
<form enctype="multipart/form-data" id="uploadImageForm">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="name" id="name">
<label class="form-label">Worker's Name</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="dept" id="dept">
<label class="form-label">Department</label>
</div>
</div>
<div class="form-group form-float">
<div class="input-group">
<div class="form-line">
<input type="text" data-type="date" id="date" name="date" placeholder="Date" class="form-control datepicker">
</div>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<textarea name="description" id="description" cols="30" rows="5" class="form-control no-resize"></textarea>
<label class="form-label">Description</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Photo</label>
<div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>
<div class="kv-avatar center-block" style="width:200px">
<input id="avatar-2" name="userImage" type="file" class="file-loading">
</div>
</div>
<div class="form-group" align="center">
<button type="input" name="submit" class="btn btn-success btn-md btn-icon waves-effect" id="btn-submit" ><i class="fa fa-check-square-o"></i> Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- #END# Basic -->
</div>
</section>
<?php include('footer.php'); ?>
uploadimage.php
include('../../includes/functions.php');
if($_POST) {
$valid = array('success' => false, 'messages' => array());
$name = $mysqli->real_escape_string($_POST['name']);// user name
$dept = $mysqli->real_escape_string($_POST['dept']);
$desc = $mysqli->real_escape_string($_POST['description']);// user email
$yr = $mysqli->real_escape_string($_POST['date']);
$fileName = $_FILES['userImage']['name'];
$type = explode('.', $fileName);
$type = $type[count($type) - 1];
$url = '../user_images/' . uniqid(rand()) . '.' . $type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {
// insert into database
$sql = "INSERT INTO worker_of_the_month (name, dept, description, given, img) VALUES ('$name','$dept','$desc','$yr', '$url')";
if($mysqli->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully Saved.";
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
$mysqli->close();
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
}
}
echo json_encode($valid);
// upload the file
}
Ajax.js
$('document').ready(function() {
/* validation */
$("#uploadImageForm").validate({
rules:
{
name:{
required: true
},
dept:{
required: true
},
description:{
required: true
},
date:{
required: true
},
},
messages:
{
name: "Worker name required",
dept: "Worker department name required",
description: "Enter description for this honour.",
date: "Please select date",
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#uploadImageForm").serialize();
$.ajax({
type : 'POST',
url : 'php_action/uploadImage.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> processing');
},
success : function(data)
{
if(data.success == true)
{
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> Saving ...');
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
data.messages +
'</div>');
$('#uploadImageForm')[0].reset();
/*setTimeout(' window.location.href = "success.php"; ',4000);*/
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="fa fa-check-square-o"></span> Save');
});
}
}
});
return false;
}
/* form submit */
});
</script>
What am I doing wrong?
You need to use a FormData() to pass files.
Change
var data = $('#uploadImageForm').serialize();
to
var form = $('#uploadImageForm')[0];
var data = new FormData(form);
As #ThisGuyHasTwoThumbs pointed you should set cache, contentType and processData via your ajax call
$.ajax({
cache: false,
processData: false,
contentType: false,
//other ajax parameters
});
You cannot POST files via AJAX like you have your code now.
This is how you can upload files using javascript and way better option:
PHP:
<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
'username' => $_REQUEST['username'],
'accountnum' => $_REQUEST['accountnum']
));
echo $json;
?>
HTML:
<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (ericbidelman#chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>
<input type="file" name="afile" id="afile" accept="image/*"/>
<script>
document.querySelector('#afile').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>
Quick example taken from: https://gist.github.com/ebidel/2410898

I am not getting any text value in form input in codeigniter

I am very new to Codeigniter. I m trying to create a form with some text input field along with two image upload field. The image uploading working fine but the text input field value are not coming. Can anyone please check my code and tell me where I am doing wrong Here is my Code:
Front End
<body>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data"">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
</script>
Controller Script is this
public function upload(){
$uploadData = "";
//Get the details
$productName = $_POST['product_name'];
$productCode = $this->input->post('product_code');
$productLink = $this->input->post('product_link');
$uploadData = $productName.','.$productCode.','.$productLink;
// setting cofig for image upload
$config['upload_path'] = 'uploads/profile/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
//$config['max_size'] = '1024'; //1 MB
// Get the profile image
$errorMsg = "";
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
$errorMsg = 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/profile/' . $_FILES['file']['name'])) {
$errorMsg = 'File already exists : uploads/profile/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$errorMsg = $this->upload->display_errors();
} else {
$data = $this->upload->data();
$errorMsg = 'File successfully uploaded : uploads/profile/' . $_FILES['file']['name'];
$uploadData = $uploadData.','.$data['full_path'];
}
}
}
} else {
$errorMsg = 'Please choose a file';
}
//upload product screenshots
$config['upload_path'] = 'uploads/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
$link="";
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
$errorMsg = "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
$errorMsg = 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
$fileOriginalNmame = $_FILES["files"]["name"][$i];
$explodeFile = explode(".",$fileOriginalNmame);
$fileExtenstion = end($explodeFile);
$fileName = md5(md5(uniqid(rand(), true)).$_FILES["files"]["name"][$i]).'.'.$fileExtenstion;
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $fileName);
$link= $link.$fileName.',';
}
}
}
$uploadData =$uploadData .','. $link;
$errorMsg = $uploadData;
} else {
$errorMsg = 'Please choose at least one file';
}
echo $errorMsg;
}
And if anyone can improve my controller code that will be very helpful tnx.
FormData() Method:
As per our definition .FormData() submit a element data in a Key/Value form. The Form element must have a name attribute. One advantage of FormData() is now you can post a files on next page.
Simple Syntax:
var formData = new FormData(form);
Highlight Points:
This method does post files.
This method post complete form using Get & Post method including files.
var formData = new FormData();
formData.append('username', 'joe');
In addition you could add a key/value pair to this using FormData.append.
So your code broke because you need to pass value of input as key/pair format that you missed except for file.
Hope this will help you.
Please find solution describe below.
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
var inputs = $('#product-upload input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
formData.append(name, value);
});
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
Let me know if it not works for you.

How to return PHP response to HTML page using AJAX

I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">

While inserting Data into MySQL using Ajax and PHP, taking limited data?

While inserting Data into MySQL using Ajax and PHP, taking limited data from rich textarea,Is there any problem?
JQuery Script
$('#adddesc').click(function(e)
{
e.preventDefault();
var txtcategoryname=tinyMCE.get('txtcategoryname').getContent();
var txttitle=$('#txttitle').val();
var selectError1=$("#selectError1").val();
var selectError2=$("#selectError2").val();
var selectError3=$("#selectError3").val();
//var fimage=$("#fimage").val();
//alert($("#selectError2").val().length);
var dataString;
var err;
err=(txttitle!='' && txtcategoryname!='' && $("#selectError1").val()!='0' && $("#selectError2").val()!='0' && $("#selectError3").val()!='0')?'0':'1';
// var dataString1="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2;
//dataString1="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2+"& subcat="+selectError3;
// alert(dataString1);
if(err=='0')
{
dataString="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2+"& subcat="+selectError3;
//alert(dataString);
$.ajax({
type: "POST",
url: "aAddDescription.php",
data: dataString,
cache: true,
beforeSend: function(){ $("#adddesc").val('Adding Des.....');},
success: function(html){
//$("#txtcategoryname").val('');
tinyMCE.get('txtcategoryname').setContent('');
$("#txttitle").val('');
//$("#selectError1").get(0).selectedIndex = 0;
//$("#error").removeClass("alert alert-error");
$("#error").addClass("alert alert-success");
$("#error").html("<span style='color:#cc0000'>Success:</span> Description Added Successfully. ").fadeIn().delay(3000).fadeOut();
}
});
HTML Form script
<form class="form-horizontal" method="POST" action="" enctype="multipart/form-data" autocomplete="off">
<fieldset>
<div class="control-group">
<label class="control-label" for="selectError">Select Cateogry</label>
<div class="controls">
<?php
$result=mysqli_query($db,"SELECT * FROM categories ");
//$count=mysqli_num_rows($result);
$op="<option value='0'>Select Category</option>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$op.="<option value='".$row['id']."'>".$row['title']."</option>";
}
?>
<select id="selectError1" >
<?php echo $op; ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError">Select Sub Cateogry</label>
<div class="controls">
<select id="selectError3">
<option selected="selected" value="0">--Select Sub--</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">Enter Title:: </label>
<div class="controls">
<input class="form-control" type="text" id="txttitle" name="txttitle" value="" placeholder="Enter Title"><span id="user-availability-status"></span> <img src="LoaderIcon.gif" id="loaderIcon" style="display:none;width:20px;height:20px;" />
</div></div>
<div class="control-group">
<textarea rows="10" cols="20" name="content" style="width:100%; height:150px" id="txtcategoryname"></textarea>
</div>
<div class="control-group">
<label class="control-label" for="selectError1">Tags(select All with Press Ctrl)</label>
<div class="controls">
<?php
$result=mysqli_query($db,"SELECT * FROM tags ");
//$count=mysqli_num_rows($result);
$op1='';
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$op1.="<option value='".$row['title']."'>".$row['title']."</option>";
}
?>
<select id="selectError2" multiple >
<?php //echo $op1; ?>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="adddesc">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
aAddDescription.php
<?php
include("common/db.php");
session_start();
if(isSet($_POST['description']) && isSet($_POST['txttitle']))
{
// username and password sent from Form
$description=$_POST['description'];
$txttitle=mysqli_real_escape_string($db,$_POST['txttitle']);
$catname=mysqli_real_escape_string($db,$_POST['catname']);
$subcat=mysqli_real_escape_string($db,$_POST['subcat']);
$tags=mysqli_real_escape_string($db,$_POST['tags']);
//$fimage=$_FILES['fimage']['name'] ;
$cby=$_SESSION['login_user'];
//$result=mysqli_query($db,"SELECT * FROM categories WHERE title='$categoryname'");
//$count=mysqli_num_rows($result);
//$target_dir = "uploads/";
//$target_file = $target_dir.$_FILES['fimage']['name'];
//move_uploaded_file($_FILES['fimage']['tmp_name'],$target_file);
//$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
/*if($count>0)
{
echo "0";
}
else
{
mysqli_query($db,"INSERT INTO categories(title) VALUES('".$categoryname."')");
echo "1";
}*/
//date_default_timezone_set('Asia/Delhi');
mysqli_query($db,"INSERT INTO description(title,description,cat_id,tags_id,created,modified,createdby,modifiedby,subcat_id) VALUES('".$txttitle."','".$description."','".$catname."','".$tags."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".$cby."','".$cby."','".$subcat."')");
$cid=mysqli_insert_id($db);
$cresult=mysqli_query($db,"SELECT * FROM counter WHERE cont_id='$cid'");
$ccount=mysqli_num_rows($cresult);
if($ccount==0)
{
mysqli_query($db,"INSERT INTO counter(cont_id) VALUES(".$cid.")");
}
echo "1";
}
?>
Please help me any thing wrong in this code?...even i changed cache to false also getting same problem. if i type 1000/less or more lines data, always it is taking limited data. Please help me. thanks in Advance
I'd be willing to bet that your text has characters in it that are interfering with the url like "&", "?", "/", "=", etc.
You should encode your text with encodeURIComponent() like this:
var txtcategoryname=encodeURIComponent(tinyMCE.get('txtcategoryname').getContent());
var txttitle=encodeURIComponent($('#txttitle').val());
var selectError1=encodeURIComponent($("#selectError1").val());
var selectError2=encodeURIComponent($("#selectError2").val());
var selectError3=encodeURIComponent($("#selectError3").val());

jquery ajax form success message not working

jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.

Categories