TinyMCE and AJAX is not sending data to php in mysql server - php

<!-- Page containing form -->
Paragraph
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//tinymce.cachefly.net/4.2/tinymce.min.js"></script>
<!-- Just be careful that you give correct path to your tinymce.min.js file, above is the default example -->
<script>tinymce.init({selector:'textarea'});</script>
</head>
-->
<div class="container">
<br />
<br />
<h2 align="center">Enter a new paragraph</h2>
<div class="form-group">
<form name="add_paragraph" id="add_paragraph">
<div class="table-responsive">
<table class="table table-bordered
id="dynamic_field">
<tr>
<textarea id = "paragraph" type="text" name="paragraph" placeholder="Enter paragraph text"></textarea>
</tr>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body> </html> <script> $(document).ready(function(){
$('#submit').click(function(){
$.ajax({
url:"form1_support.php",
method:"POST",
data:$('#add_paragraph').serialize(),
success:function(data)
{
alert(data);
$('#add_paragraph')[0].reset();
}
});
}); }); </script>
require 'db/connect.php';
$number = count($_POST["paragraph_name"]); //it said experience
before, maybe experience_list?
if($number > 0) {
for($i=0; $i<$number; $i++)
{
if(trim($_POST["paragraph_name"] != ''))
{
$paragraph_name = mysqli_real_escape_string($db, $_POST['paragraph_name']);
$paragraph_text = mysqli_real_escape_string($db, $_POST['paragraph']);
$sql = "INSERT INTO paragraph (paragraph_name, paragraph_text)
VALUES( '$paragraph_name', '$paragraph_text')";
mysqli_query($db, $sql);
}
}
echo "Data Inserted"; } else {
echo "Please Enter Your Paragraph."; } ?>

If you are replacing a textarea with TinyMCE then the actual textarea does not get updated automatically unless one of the following happens:
You perform a standard HTML form submission - in this scenario TinyMCE will automatically update the textarea at the start of the form submission process.
You use the triggerSave() API to force TinyMCE to update the textarea.
Try adding a triggerSave() call before you send the AJAX request.
https://www.tiny.cloud/docs/api/tinymce/root_tinymce/#triggersave

<textarea id="editor" name="editor" type="text"></textarea>
tinyMCE.triggerSave();
var content = $("textarea[name=editor]").val();
var formData = new FormData();
formData.append("content", content);
$.ajax({
url: '../boot/newBlog.php',
method: 'POST',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
switch (response){
}
}
});

Related

how to pass a validation from php to ajax

How can I make my error messages appear after validation in PHP using AJAX
Hi, I'm currently working on my ajax and I'm tryng to figure out on how will my error message appear on my form. I've already tried to echo the error but what I want is show the error on every invalid field.
here's my html code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
span{
display: none;
}
</style>
</head>
<body>
<form action="test2.php" method="POST" id="formLogin" class="pass">
name: <input type="text" name="name" id="name">
<span id="name">Invalid!</span>
<br>
description: <textarea name="description" id="description"></textarea>
<span id="desc">Invalid!</span>
<br>
image file: <input type="file" name="image" id="image">
<button type="submit" ></button>
</form><br>
<p class="form-message"></p>
<script src="ajax.js"></script>
</body>
heres my ajax code:
$(document).ready(function(){
$("#formLogin").submit(function(event){
event.preventDefault();
$.ajax({
url: 'test2.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data)
{
if(data.name == "1"){
$("span#name").css("display","block");
}else{
$("span#name").css("display","none");
}
if(data.desc == "1"){
$("span#desc").css("display","block");
}else{
$("span#desc").css("display","none");
}
}
});
});
});
and my php code;
<?php
$myObj = new stdClass();
if(empty($_POST['name'])){
$myObj->name = "1";
}
if(empty($_POST['description'])){
$myObj->description = "1";
}
$myJSON = json_encode($myObj);
echo $myJSON;
?>
In success of ajax, you receive the data in json formate , before use the data.name you have to reqiure parse json like
data=$.parseJSON(data) OR data=JSON.parseJSON(data)
then use data.name

PHP $_GET content in <div>

first of all i'm new here so if I do mistakes pls let me know^^"
I try to get the content of a div element with php $_POST and I dont really know how to do it. I use MVC patter if that matters.
My div is editable and the answer box to write something on the page.
<form action="index.php?page=addPost&topic_id={TOPIC_ID}" method="post">
<div id="editor" name="editor">
Lorem Ipsum...
</div>
<input type="submit" name="submit" value="senden" >
</form>
I can't just use a textarea but I would like to get everything between the div element with something like
$text = $_POST['editor'];
is that possible?
You could use a hidden textarea, and add the contents of the div to the textarea on form submit:
<form action="index.php?page=addPost&topic_id={TOPIC_ID}" method="post" onsubmit="getEditorContents(this);">
<div id="editor">
Lorem Ipsum...
</div>
<textarea style="display:none;" name="editor"><!-- --></textarea>
<input type="submit" name="submit" value="senden" >
</form>
<script>
function getEditorContents(form){
var html = document.getElementById("editor").innerHTML;
form.editor.value = html;
return true;
}
</script>
Use ajax or just use a textarea form element
<form id="data" method="post" enctype="multipart/form-data">
<div id="editor" name="editor">
Lorem Ipsum...
</div>
<input type="submit" name="submit" value="senden" >
<input type="hidden" id="topicId" value="{TOPIC_ID}" >
</form>
<script>
$(document).ready(function(){
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
formData.append('editor', $('#editor').html());
$.ajax({
url: 'index.php?page=addPost&topic_id='+$('$topicId').val(),
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data);
location.reload();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
Here is how you can proceed with:
<script>
$(document).ready(function(){
$("#myform").on("submit",function(e){
e.preventDefault(); //Prevent default form submission
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText == "true") {
//success message
} else {
//error message
}
}
}
xmlhttp.open("POST", "index.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //to maintain HTML format though you pass value through POST
xmlhttp.send("page=addPost&topic_id="+$('#topicID').val()+"value=" + $('#editor').html());
});
});
</script>
Small rework with your form:
<form id="myform" method="post">
<div id="editor" name="editor">
Lorem Ipsum... in WYSIWYG format
</div>
<input type="hidden" id="topicID" value="{TOPIC_ID}"/>
<input type="submit" name="submit" value="senden" />
</form>

how to insert value in database using php, jquery and ajax

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

execute jquery .submit AFTER ajax success return new form

I believe my problem has something to do with the fact that my first form RETURNS a new form via ajax success .html(result) AFTER DOM has executed. My jquery within DOM isn't being recognized because elements aren't visible until after the submit of first form. HOW to get my $("#fullFormMA").on(submit,(function(e){ to execute is eluding me. Here is my html
<?php
session_start();
require_once('functions.php');
include('header.htm');?>
<title>Membership Application</title>
<meta name="description" content="">
</head>
<body>
<div id="container">
<div id="loginBanner">
<?php include ("loginMenu.php"); ?>
<?php include ("bannerIcons.php"); ?>
</div> <!--end loginBanner-->
<div id="header" class="clear">
</div> <!--end header-->
<div id="content"><div class="content">
<div id="colLt">
<?php include('tabContent.php');?>
<?php include('leftSidebar.php');?>
</div>
<div id="colRt"><div class="content">
<h1>New Member Application</h1>
<ul><li>submitting an application</li><li>submitting payment</li></ul><h6>Step #1—the application</h6>Please enter an email which will ultimately be used as your website username. This email will remain as your private email.</p><br><br>
<form method="post" name="checkUserMA" id="checkUserMA">
<label class="clear" style="width:120px">Username/Email<br><span class="small"></span></label>
<input type="text" name="usernameMA" id="usernameMA" class="green" style="width:300px;"/><br><br>
<input type="submit" id="checkUserMA" class="submit" value="Submit" />
</form>
<div class="clear"></div>
<div id="errorMA" style="background:yellow;width:200px;height:100px"></div>
<div id="resultMA"></div>
</div></div>
<div class="clear"></div>
</div></div><!--end content-->
<div id="footer">
<?php include("footer.htm") ?>
<!--<?php include("disclaimer.htm") ?>-->
</div><!--end footer-->
<div class="clear"></div>
</div><!--end container-->
<div class="clear"></div>
</body>
</html>
Here is my jquery:
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
});//end dom
Here is checkMA.php...
<?php
session_start();
include('functions.php');
connect();
$username = urldecode(protect($_POST['usernameMA']));
$_SESSION['guestUser'] = $username;
$sql2 = mysql_query("SELECT username FROM members WHERE username = '$username'");
$checkNumRows = mysql_num_rows($sql2);
if (!$username){
echo "<p class='red'>Enter an email to be used as your username...</p>";
} else if ($checkNumRows == 1){
echo "<span style='font-weight:bold'>The username: ".$username." is already in use.</span>";
} else if ($checkNumRows == 0){
echo "<hr><p class='green'>This username is available.</p><p>Please continue with the registration process...</p><br>";?>
<form method="post" name="fullFormMA" action="memberAppProcess.php">
<h6>Public Information - this information will be displayed to website visitors</h6>
<label class="clear" style="width:75px">Name</label>
<label class="error" id="name_error">This field is required.</label>
<input type="text" name="firstName" id="firstName" class="left inputCheck" style="width:150px" placeholder="first name"/>
<input type="text" name="lastName" id="lastName" class="inputCheck" style="margin-left:10px" placeholder="last name"/><br><br>
<input type="submit" name="fullFormMA" id="fullFormMA" class='submit right' onClick='submitFullForm();' value="Submit application">
</form>
<?php
}?>
My #checkUserMA works but my #fullFormMA doesn't work. I would love to understand why (DOM already loaded?) and how I might fix my code to allow for a form added "after the fact" via ajax .html(result). Thank you.
The DOM is ready before your ajax success so you can write this JQuery full code
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
RunAfterAjax();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
function RunAfterAjax(){
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
}
});//end dom
It's executing, you just aren't waiting long enough for it to exist. Move the event binding for the new form to the line right after you add the new form to the document.
$("#resultMA").html(result).fadeIn();
$("#fullFormMA").on(submit,(function(e){...
$("#fullFormMA").on(submit,(function(e){ /* ... */ });
fullFormMA is an <input>, you should bind click instead of submit, and use quotes around the event name.
When you use $('#something').on('event', ...), it only works if the #something element already exists.
You could fix your code by delegating the listener to an upper existing element :
$('#content').on('click', '#fullFormMA', function() { /* ... */ });
This code will detect the click event on #fullFormMA event if it is added after an ajax response.

Ajax stopped working after executing a query

I am trying to load comments from a php file using ajax.
index.php
<div id="commentsonpost" value="<?php echo $_GET['post'];?>">
</div>
<script type="text/javascript">
$(document).ready(function() {
var postid = $('#commentsonpost').attr("value");
alert(postid);
var dataString = 'getpostcomm=1&postid='+ postid;
$.ajax({
type: "get",
url: "getcomments.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
alert("re");
$("#commentsonpost").append(html);
}
});
return false;
});
</script>
getcomments.php
if(isset($_GET['getpostcomm'])){
$var=$_GET['postid']; // Adding this line causing problems
$querycomm = "select U.fname,U.lname,U.usernick,C.bcommentid,C.comment,C.date,C.visible from blogcomments as C natural join users as U where C.visible=1 and U.visible=1 and C.bpostid='{$var}' ORDER BY C.date ASC";
$resultcomm = mysql_query ( $querycomm, $connection );
echo "<div id='pcomments'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$_POST['post'].'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
}
Whenever i add that $var=$_GET['postid']; line in getcomments.php ajax script stop working. As soon as i remove $var=$_GET['postid']; from getcomments.php, excluding query part(obviously) form is displaying correctly.
Any ideas?
At ajax better set data fields as array values as:
$.ajax({
type: "get",
url: "getcomments.php",
data: {'getpostcomm':1,'postid':postid},
And at your PHP you have to sanitize your Id.. (if its int you may at least cast (int) )...
$var = (int) $_GET['postid'];
Also at your PHP add check if isset($_GET['postid'])...
if(isset($_GET['getpostcomm']) && isset($_GET['postid'])){
var dataString = 'getpostcomm=1&postid='+ toString(postid);

Categories