I have created a simple form consisting of a textarea field, so when user clicks on submit button its linked to a jquery script containing a url executing the process and store the data, but problem is every time i hit submit, ID & created_at data is stored but the data given on textarea is ignored and not stored, never faced this problem before..please help me out!
HTML
<form id="form" name="form" method="POST" action="profile_1.php" class="wizard-big" autocomplete="off" enctype="multipart/form-data" required="">
<div class="form-group col-sm-12">
<textarea type="text" name="status" id="status" placeholder="What's on your mind.." class="form-control" style="height:100px;"></textarea>
</div>
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name="submit" id="submit" value="Post" class="btn btn-success">
</div>
</form>
Jquery
$(document).ready(function() {
$("#submit").click(function(e) {
var status = $('form')[0].checkValidity();
if (status) {
var formData = new FormData($('form')[0]);
$.ajax({
url: "form_post.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json) {
if (json.error) {
alert(json.error_msg);
e.preventDefault();
} else {
alert("Post updated successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
});
php
<?php
session_start();
define('HOST','localhost');
define('USER','**');
define('PASS','**');
define('DB','**');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$status =$_POST['status'];
// create a new user profile
$sql = "INSERT INTO status (via, status, created_at) VALUES ('".$_SESSION['vault_no']."', '$status', NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
$response['via'] = $via;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
Note: The solution is in the comments for other readers of this question
Maybe this helps you out. You need to change it to your wish offcourse
And save this function, it could be usefull for you in the future.
This function serializes the form as how it should be done.
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var formData = $('form').serializeObject();
$.ajax({
data: formData,
type: 'POST',
url: 'form_post.php',
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
return false;
});
});
</script>
Related
I am using Codeigniter and javaScript file upload and insert database but not responce so please check my code abd share valuable idea. share all code heare...view page form data , javascript code responce error and modals submit data code here.....
view
<form id="frm_submit" enctype="multipart/form-data">
<input type="file" name="reportfile" class="form-control">
<button type="submit" class="btn btn-info" name="submit"> Save</button>
</form>
javaScript
$("#frm_submit").on('submit', function (e){
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: $("#frm_submit").serialize()
}).always(function (response){
var r = (response.trim());
if(r !=0){
$(".success").show();
$(".danger").css("display","none");
setInterval('location.reload()',2000);
}else{
$(".danger").show();
$(".success").css("display","none");
}
});
});
models
public function vendors_upload_report_file()
{
$db2 = $this->load->database('bstdc',TRUE);
date_default_timezone_set('Asia/Kolkata');
$vendorsid = $this->session->userdata['vendors_data'][0]['vendor_id'];
$file_request_id = $this->input->post('file_department_id');
$file_request_id = $this->input->post('file_request_id');
$reportfile = $this->input->post('reportfile');
$today_date = date("Y-m-d");
if(!empty($reportfile)){
$filename = $_FILES['reportfile']['name'];
if (!empty($filename)){
$pic = $a.'-'.rand(5,10).time()."".$filename;
move_uploaded_file($_FILES['reportfile']['tmp_name'],'upload/files/'.$pic);
$report_pic_url = ''.base_url().'upload/files/'.$pic.'';
$db2->query('INSERT INTO bstdc_reports_file (request_id,sendor_type,sendor_id,reports_file,reports_file_url,created_date,act_status,del_status)
VALUES ("'.$file_request_id.'","Vendors","'.$vendorsid.'","'.$pic.'","'.$report_pic_url.'", "'.$today_date.'", "Y","N")');
return true;
}else{
return false;
}
}
}
Use FormData object to upload file
$("#frm_submit").on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: new FormData(this), // <== changed from $("#frm_submit").serialize()
}).always(function (response) {
var r = (response.trim());
if (r != 0) {
$(".success").show();
$(".danger").css("display", "none");
setInterval('location.reload()', 2000);
}
else {
$(".danger").show();
$(".success").css("display", "none");
}
});
});
I have built this Mailchimp Newsletter sign up plugin. PHP its not my strength so I am not being able to fix the error it has.
I used This Mailchimp wrapper: https://github.com/drewm/mailchimp-api.
My PHP file is:
<?php
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
function sm_mailchimp_subscribe()
{
// Settings:
$mcAPIKey = '70000000000000000007e-us00';
$mcListID = '323231214212';
$status = 'subscribed';
// Settings End
$MailChimp = new MailChimp($mcAPIKey);
$email = $_POST['email'];
$fname = $_POST['fname'];
$sname = $_POST['sname'];
$merge_vars = array(
'FNAME' => $fname,
'LNAME' => $sname
);
if (isset($email) and isset($fname) and isset($sname)) {
$result = $MailChimp->post("lists/" . $mcListID . "/members", [
'email_address' => $email,
'merge_fields' => $merge_vars,
'status' => $status,
]);
return json_encode($result);
}
}
if ($_POST['ajax']) {
echo sm_mailchimp_subscribe();
} elseif ($_POST['action'] == 'setCookies') {
echo setCookiesTemp();
}
function setCookiesTemp()
{
setcookie('sm_mailchimp-temp', true, time() + (86400 * 28), '/');
}
function setCookiesPerm()
{
setcookie('sm_mailchimp-perm', true, time() + (86400 * 28 * 24), '/');
}
And here is the JS:
jQuery(function($) {
// From wp_localized
const ajaxURL = ajax_obj.ajax_url;
$(document).ready(function() {
var body = $("body");
var modal = `<div class="sm_mailchimp-modal">
<div class="sm_mailchimp-box">
<button class="sm_mailchimp-close">X</button>
<h3>Join Our Mailing List</h3>
<form name="sm_mailchimp-form" method="post" class="sm_mailchimp-form light">
<p>Subscribe to our newsletter and receive tips for a successful business.</p>
<input type="email" name="email" placeholder="Type Your Email" class="sm_sname">
<div class="sm_mailchimp-message"></div>
<button type="submit">SIGN UP</button>
</form>
</div>
</div>`;
if (!document.cookie.includes("sm_mailchimp-temp=1")) {
$(modal)
.hide()
.appendTo(body);
setTimeout(function() {
$(".sm_mailchimp-modal").fadeIn();
}, 5000);
}
$(".sm_mailchimp-close").click(function() {
closeModal();
});
$(".sm_mailchimp-modal").click(function(e) {
if (e.target == this) {
closeModal();
}
});
function closeModal() {
$(".sm_mailchimp-modal").fadeOut();
$.ajax({
url: ajaxURL,
method: "POST",
data: { action: "setCookies" },
success: function(data) {
console.log("Cookie added as sm_mailchimp-temp=1");
}
});
}
$(".sm_mailchimp-form").submit(function() {
var emailVal, fnameVal, snameVal;
emailVal = $(".sm_email", this).val();
fnameVal = $(".sm_fname", this).val();
snameVal = $(".sm_sname", this).val();
if (emailVal === "" || fnameVal === "" || snameVal === "") {
$(".sm_mailchimp-message").html("Please fill out all the fields!");
return false;
} else {
$(".sm_mailchimp-message").html("Adding your email address...");
var form = $(this);
$.ajax({
url: ajaxURL,
type: "POST",
data: form.serialize() + "&ajax=true",
success: function(msg) {
var message = $.parseJSON(msg),
result = "";
if (message.status === "pending") {
result =
"Success! Please click the confirmation link that will be emailed to you shortly.";
} else if (message.status === "subscribed") {
result =
"Success! You have been subscribed to our mailing list.";
} else {
result = "Oops: " + message.title;
console.log("Error: ", message);
}
$(".sm_mailchimp-message").html(result);
}
});
return false;
}
});
});
});
The error is the following:
Once the Sign Up button is clicked the message "Adding your email address..." shows as it should but then it freezes there. The console shows the following error:
Weirdly, it used to work fine. And without a change it stopped. I built it a couple of months ago.
UPDATE
The error is actually coming from the success: function(msg) { line. The msg is empty. So, when it gets to message.status it cannot read the property of status null.
Question: Why is the success callback returning msg empty?
I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});
I am trying to insert more than one data in db using js ajax but it is not working and when i am trying to inserting only one data it is successfully working
Here is my indexa.php
<html>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
</head>
<body>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit" onclick="insert()">
<div id="success_failed_msg"></div>
</body>
</html>
My include.inc.php
if (isset($_POST['first_name'])) {
$firstname = $_POST['first_name'];
if (!empty($firstname)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
and when I am trying this script it
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
my include.inc.php
if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['retype_password'])) {
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$usrname = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if (!empty($firstname) && !empty($lastname) && !empty($usrname) && !empty($password) && !empty($retype_password)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`,`last_name`,`user_name`,`password`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."', '".mysqli_real_escape_string($db_connect,$lastname)."', '".mysqli_real_escape_string($db_connect,$usrname)."', '".mysqli_real_escape_string($db_connect,$password)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
You haven't done concatenation properly. See here,
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
^ missing + ^ missing + ^ missing + ^ missing +
It should be,
parameters = 'first_name='+document.getElementById('firstName').value+'&last_name='+document.getElementById('lastName').value+'&username='+document.getElementById('userName').value+'&password='+document.getElementById('password').value+'&retype_password='+document.getElementById('retypePassword').value;
Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
You are missing plus(+) sign while passing parameter. Please change your code as below:
Old Code:
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
New Code:(Added plus(+) sign wherever it was required)
parameters = 'first_name='+document.getElementById('firstName').value + '&last_name='+document.getElementById('lastName').value + '&username='+document.getElementById('userName').value + '&password='+document.getElementById('password').value + '&retype_password='+document.getElementById('retypePassword').value;
If you wrap the input fields with a form and use jQuery serialize could be easier.
Example HTML:
<form>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit">
<div id="success_failed_msg"></div>
</form>
Example JS:
//you can use the var sending to avoid
// more than one request at the same time
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
//here you can show an ajax loading icon
sending = true;
},
success: function(response){
//here you can show a success message and check if the
//response is correct
//response object depends on the server side response
if (response.success || response.success === 'true') {
//show success message...
} else {
//show error message...
}
},
error: function(err){
//here you can show an error message
},
complete: function(){
//here you can hide the ajax loading icon
sending = false;
}
});
}
});
Documentation from jQuery:
Ajax http://api.jquery.com/jquery.ajax/
Serialize https://api.jquery.com/serialize/
And you can format a json response from the server side
json_encode (with this you "transform" a php array to a js object) http://php.net/manual/en/function.json-encode.php
header('Content-Type: application/json'); with this the app will know what type of response is given
You can read more about json and ajax here:
http://www.json.org/
https://developer.mozilla.org/en-US/docs/AJAX
And a tutorial about how to see the request on Firefox: https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor
And on Chrome: https://developers.google.com/web/tools/chrome-devtools/network-performance/resource-loading
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
console.log("processing");
sending = true;
},
success: function(response){
if (response.success || response.success === 'true') {
('#success_failed_msg').text(response);
} else {
('#success_failed_msg').text('response failed');
}
},
error: function(err){
('#success_failed_msg').text(err);
},
complete: function(){
console.log('process complete');
sending = false;
}
});
}
});
I want to send form data from ajax to php. My ajax retrieves the form data but it doesnt send it i dont see anything wrong with the code maybe i need a much more professional help. Thanks in advance
HTML5 syntax
<div align="center"><a id="hi">Header</a></div>
<a id="signup" data-add-back-btn="true" style="float:right;" data-icon="arrow-r">Sign- In</a>
</div>
<form class="check-user" action="php/sup.php" method="POST">
<label>Username</label>
<input id="Susername" name="username" placeholder="username" type="text" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Email</label>
<input id="Semail" name="email" placeholder="email" type="email" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Password</label>
<input id="Spassword" name="password" placeholder="password" type="password" >
</div>
<!---input type="submit" style="visibility:hidden;" id="send"/-->
</form>
Ajax syntax
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
that.find('[name]').each(function(index, element) {
var that = $(this),
name = that.attr('name'),
element = that.val();
alert(name+'='+element+' '+methods);
data[name] = element;
});
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
PHP syntax
session_start();
$name = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if(isset($name) && isset($email) && isset($password))
{
echo $name;
$_SESSION['username'] = $name;
}
else
{
die('data not set');
}
You can use serialize method on form, it will gather everything correct.
$('#signup').live('click', function(){
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = that.serialize();
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
Try this,
$('#signup').live('click', function(){
$.ajax({
url:’’,//url to submit
type: "post",
dataType : 'json',
data : {
'Susername' : $('#Susername').val(),
'Semail' : $('#Semail').val(),
'Spassword' : $('#Spassword').val()
},
success: function (data)
{
}
});
return false;
});
I solved it works this way on the php side you do this
$name = isset(json_decode($_POST['username']));//htmlentities($values[0]);
$email = isset(json_decode(($_POST['email'])));//htmlentities($values[1]);
$password = isset(json_decode($_POST['password']));//htmlentities($values[2]);
The Ajax side
$(document).ready(function(e) {
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
data = that.serialize();
console.log(data);
$.ajax(
{
url: urls,
type: methods,
dataType:'json',
data : data,
beforeSend: function(response){$.mobile.showPageLoadingMsg(true);},
success: function(response){ $.mobile.showPageLoadingMsg(false);},
error: function(xhr, textStatus, errorThrown){alert(textStatus);},
complete: function(response){},
}
);
return false;
});
});