Here is my HTML Code:
<div class="form-horizontal row-border">
<div class="form-group">
<label class="col-md-2 control-label">Title:</label>
<div class="col-md-10"><input class="form-control" id="title" name="title" type="text"></div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Article:</label>
<div class="col-md-10">
<textarea name="editor1" id="editor" rows="10" cols="80">
Let's go...
</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Tags:</label>
<div class="col-md-10"><input class="tags" id="tags" type="text" value="">
</div>
</div>
<div class="row" style="margin-left:92%;">
<input type="button" id="PostArticle" class="btn btn-success" value="Post Article"></input>
</div>
</div>
Here is my JavaScript code:
<script type="text/javascript">
$("#PostArticle").click(function() {
var title = $("#title").val();
var text = $("#editor").text();
var tags = $("#tags").val();
$.ajax({
url: 'post_new_article.php',
type: 'POST',
data: {
title: title,
tags: tags,
text: text
},
dataType: 'json',
success: function (data) {
noty({text: 'MySite.com:' + data.title + ' was successfully created!', type: 'success'});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
noty({text: 'Failure - The article was not created! Error is: ' + errorThrown + '', type: 'error'});
}
});
});
</script>
Here is the code from: post_new_article.php:
<?php
require "include/config.php";
require "include/functions.php";
ConnectWithMySQLDatabase();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$title = $_POST['title'];
$text = $_POST['text'];
$tags = $_POST['tags'];
$month = date('F');
$year = date('Y');
$day = date('d');
if(isset($_POST['title']))
{
mysql_query("INSERT INTO `Blog` (`id`, `Title`, `Article`, `Autor`, `Date`, `Month`,`Year`, `Tags`, `Image`) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");
}
$result['title'][0] = $title;
echo json_encode($result);
From all things it seems that only the MySQL insert function is not working. I can confirm that ConnectWithMySQLDatabase(); function is working as intended and this function is establishing the connection to MySQL.
Somehow it seems i can not insert the mysql query after i hit the Post Article button. I can confirm that i receive response from post_new_article.php because i receive a notification with the title of the article as a back response. So the json seems to read back the title of the article.
So can you help me out resolve this problem and make it insert the query to the MySQL database ?
Thanks in advance!
Try this
in your form submit button should be
<input type="submit" id="submit" class="btn btn-success" value="Post Article"></input>
And AJAX Should be
<script>
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault();
var title = $("#title").val();
var text = $("#editor").text();
var tags = $("#tags").val();
$.ajax(
{
type:"post",
dataType: 'json',
url: "./post_new_article.php",
data:{ title:title, text:text,tags:tags},
success:function(data)
{
}
});
});
});
</script>
EDIT 01
Change this
mysql_query("INSERT INTO Blog (id, Title, Article, Autor, Date, Month,Year, Tags, Image) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");
Related
check_availability.php
this is my php to check the form if it is already exist.
<?php
require_once("config.php");
//code check email
if (!empty($_POST["CUSUNAME"])) {
$result = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE CUSUNAME='" . $_POST["CUSUNAME"] . "'");
$row = mysqli_fetch_row($result);
$email_count = $row[0];
if ($email_count > 0) echo "<span style='color:red'>Username is already used.</span>";
else echo "<span style='color:green'>Username is available.</span>";
}
// End code check email
//Code check user name
if (!empty($_POST["PHONE"])) {
$result1 = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE PHONE='" . $_POST["PHONE"] . "'");
$row1 = mysqli_fetch_row($result1);
$user_count = $row1[0];
if ($user_count > 0) echo "<span style='color:red'>Phone is already used.</span>";
else echo "<span style='color:green'>Phone number is available.</span>";
}
// End code check username
?>
LogSignModal.php
here is my page.
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"CUSUNAME">Username:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkUserNameAvailability()" id="CUSUNAME" name="CUSUNAME" placeholder=
"Username" type="text" value="">
<span id="username-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"PHONE">Contact Number:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkPhoneAvailability()" id="PHONE" name="PHONE" placeholder=
"Phone Number" type="number" value="">
<span id="Phone-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4" align = "right"for=
"image"></label>
<div class="col-md-8">
<input type="submit" name="submit" value="Sign Up" class="submit btn btn-pup" />
<button class="btn btn-default" data-dismiss="modal" type=
"button">Close</button>
</div>
</div>
</div>
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'CUSUNAME='+$("#CUSUNAME").val(),
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'PHONE='+$("#PHONE").val(),
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
my code is all worked, but I can't make a submit button to appear when the value I input in textbox is available in database and disappear if it is already use.
I hope someone help me, thank you.
Edit: First, you should definitely also check the comment of Dharman and rewrite how you fetch data from MySQL in your PHP code since the current state is vulnerable to SQL Injections and is absolutely not safe to use!
The problem is how you pass your data to your ajax function. The way you do it, the server receives nothing but a plain string, for example 'CUSUNAME=dave'. This way $_POST["CUSUNAME"] will find nothing and your server response will stay empty. So you should pass your data as an object the following way :
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'CUSUNAME': $("#CUSUNAME").val()},
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'PHONE': $("#PHONE").val()},
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
My objective is to send the form data as an email using php and the form div should get replaced by another div. I have done hiding the div part using jquery but not able to send and email. I have also written the code to send email but my issue is how to call the file which has email sending code.
My form code:
<form method="post" id="formsub">
<div id="form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="text" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
</div>
<div class="form-group">
<input type="button" id="addbut" name="submit" value="Submit" class="form-control">
</div>
</div>
</form>
My code to hide the div and tried form submission script:
<script>
$(document).ready(function() {
$("#addbut").on('click', function() {
$.ajax({
type: "POST",
url: "fromemail.php",
data: $(form).serialize(),
success: function(){
$("#form").hide();
$("#address").show();
}
});
});
});
</script>
My php email sending code:
<?php
if($_POST['submit']){
$to = "akhil#redd.xyz"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$phone = $_POST['phone'];
$subject = "Spots Contact";
$message = $first_name . ", with " . $phone . "has enquired for the service";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
if(mail($to,$subject,$message,$headers))
{
echo "<script>alert('We will contact you shortly');</script>";
}
}
?>
Give file name in form action attribute :
<form id="formsub" method="post" action="fromemail.php">
and do ajax code like this :
$(document).ready(function(){
var form=$("#formsub");
$("#addbut").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#formsub").serialize(),
success: function(response){
console.log(response);
}
});
});
});
#Rakhi..
Is this correct??
<script type="text/javascript" src="assets/js/jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function() {
var form=$("#formsub");
var base_url = "www.3ding.in/spots/";
$("#addbut").on('click', function() {
$("#form").hide();
$("#address").show();
$.ajax({
type: "POST",
url: base_url + "fromemail.php",
data: $("#formsub").serialize(),
success: function(response){
alert(1);
console.log(response);
}
});
});
});
I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
alert(data);
var url = '/PubDev/updatePubDev';
$.post(url, data, null, 'json')
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error");
}
})
.fail(function (data) {
alert("ajax error");
})
.always(function () {
});
});
<div class="md-modal md-effect-1" id="updatePubDevModal" >
<div class="md-content">
<div class="modal-header">
<button class="md-close close">×</button>
<h4 class="modal-title">Update Publisher/Developer</h4>
</div>
<form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="row dropzone">
<div class="col-lg-5">
<div class="form-group">
<label for="pubDevName">System Id of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
<input type="hidden" name="pubDevId" id="pubDevId" >
</div>
<div class="form-group">
<label for="pubDevName">Name of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
</div>
<div class="form-group">
<label for="date-founded">Date Founded</label>
<input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
</div>
<div class="form-group">
<label>What type of company is this?</label>
<div class="checkbox-nice">
<input type="checkbox" name="isPub-update" id="isPub-update">
<label for="date-founded-update">
This company is a publisher
</label>
</div>
<div class="checkbox-nice">
<input type="checkbox" name="isDev-update" id="isDev-update">
<label for="isDev-update">
This company is a developer
</label>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="main-box clearfix main-box-frame" >
<header class="main-box-header clearfix">
<h2>Upload Publisher /Developer Logo</h2>
</header>
<div class="main-box-body clearfix imgcontainer center">
<img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
<div class="main-box-body clearfix">
<div id="dropzone" class="drop-zone-frame" >
<input type="file" name="image2" id="image2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
</div>
</form>
</div>
</div>
Here is the php code:
public function updatePubDev() {
$fields = array();
$fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
$fields['name'] = $this->input->post('pubDevName-update');
if ($this->input->post('date-founded'))
$fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
if ($this->input->post('isPub-update'))
$fields['publisher'] = 1;
else
$fields['publisher'] = 0;
if ($this->input->post('isDev-update'))
$fields['developer'] = 1;
else
$fields['developer'] = 0;
$row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());
$file = $_FILES['image2'];
//$idPubDev = $this->input->post("pubDevName");
$ds = DIRECTORY_SEPARATOR;
$path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
//print_r($file);
$info = new SplFileInfo($file['name']);
//var_dump($info->getExtension());
$filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
$result = $this->upload->uploadfile($file, $path, $filename);
//echo "test";
if ($result['status'] === "OK") {
$logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
$this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
$result['message'] = "file saved successfully";
$result['query'] = $this->db->last_query();
}
$result['update_rows']= $row_count;
echo json_encode($result);
}
I tried the .ajax version, but the problem persist, here is the modified jquery:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = '/PubDev/updatePubDev';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false
})
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error!");
}
})
.fail(function (data) {
alert("ajax error!");
})
.always(function () {
});
});
It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:
processData: false,
contentType: false
This way, it solved my problem.
Use FormData as data instead of $(this).serialize();, set processData and contentType to false
var data = new FormData();
data.append("file", $(":file", this)[0].files[0]);
$.ajax({
url: "/PubDev/updatePubDev",
type: "POST",
data: data,
processData: false,
contentType: false
})
Please try to use file_get_contents('php://input'); to get the upload content.
I have textarea with save and cancel buttons for updating textarea text in mysql DB.
Initially my MYSQL db
ID text
1 NULL
If i enter some text in textarea i'm updating my mysql db text with entered value currently i'm able to achieve it but my requirment is once i entered text in textarea it should update my db and that text value should display with EDIT and DELETE buttons.
on clicking EDIT button it should open up textarea with save and cancel buttons. can somebody aid me out how to achieve it Thanks!
http://jsfiddle.net/a32yjx0k/
HTML
<div id="b_news">
<form method="post" action="">
</div>
<div class="breaking_news_content">
<div>
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="submit" class=" save_breaking_news" value="Save Changes"/>
<input type="submit" value="Cancel" class=" breaking_news_cancel">
</div>
</form>
</div>
</div>
</form>
</div>
JQUERY
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').val();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
textcontent:textcontent
},
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
PHP
<?php
if(isset($_POST['textcontent']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "update breakingnews set text='".$breaking_news."'";
$result = mysqli_query($con, $sql);
}
?>
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').text();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
textcontent:textcontent
},
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
To get textbox use (class/id).text();
Your DIV
<div id="b_news">
<form method="post" action="">
</div>
<div class="breaking_news_content">
<div>
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="hidden" id="post_ID" value="2"/>
<input type="button" class=" save_breaking_news" value="Save Changes"/>
<input type="button" value="Cancel" class=" breaking_news_cancel">
</div>
</form>
</div>
</div>
</form>
</div>
YOUR SCRIPT SHOULD BE LIKE THIS
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').text();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
var postID=$("#post_ID").val();
$.ajax({
url: 'index.php',
type: 'post',
data: 'textcontent=' + drvNo+"id="+postID,
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
YOUR PHP CODE FOR UPDATE
<?php
if(isset($_POST['textcontent']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "update breakingnews set text='".$breaking_news."' Where id='".$_POST['id']."'";
$result = mysqli_query($con, $sql);
}
?>
AND IF YOU WANT TO INSERT POST YOUR CODE SHOULD BE LIKE THIS:
<?php
if(isset($_POST['textcontent']) && !isset($_POST['id']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "insert into <TBL NAME> `text` values ('".$_POST['textcontent']."')";
$result = mysqli_query($con, $sql);
}
?>
Your code everything is fine. Instead of calling function use .keyup() function in Jquery.
$("#breaking_news_text").keyup(function(){
var textcontent = $('.breaking_news_text').val();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
alert(textcontent);
$.ajax({
type: "POST",
url: "index.php",
data:
{
textcontent:textcontent
},
success:function(response)
{
alert('breaking news successfully updated');
}
});
}
return false;
});
and when you going to cancel please use input type="reset"
<input type="reset" value="Cancel" class=" breaking_news_cancel">
As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors