how to Getting error when submitting a form by ajax to page msg.php
file 1 = msg.php
<?php
$id = $_SESSION['id'];
$touser = htmlspecialchars($_GET['iduser']);
$postid = htmlspecialchars($_GET['post']);
?>
<div id="send">
<div id="title">صندوق المحادثة</div>
<form id="my-form" method="post" enctype="multipart/form-data">
<textarea id="_text" name="text" required=""></textarea>
<input id="_from" name="from" type="hidden" value="<?php echo $id; ?>"/>
<input name="to" type="hidden" value="<?php echo $touser; ?>"/>
<input name="post" type="hidden" value="<?php echo $postid ?>" />
<div class="file">
<li>ملفات .zip فقط</li>
<input class="up" type="file" name="up" />
</div>
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token_madmoun']; ?>" />
<button class="submit">ارسال الان</button>
</form>
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
</div>
chat_a.php
<?php
include "config.php";
if(!$user->is_logged_in()){
header('Location: unregistered.php');
exit();
}
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token_madmoun']) {
$id = $_SESSION['id'];
$data = date('Y-m-d');
$time = time();
$post = htmlspecialchars($_POST['post']);
$to = htmlspecialchars($_POST['to']);
$file_name = $_FILES['up']['name'];
$file_size = $_FILES['up']['size'];
$FileType = pathinfo($file_name,PATHINFO_EXTENSION);
if(!empty($_POST['text'])){
if(empty($FileType)) {
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->execute();
}else {
if($FileType != "zip" && $FileType != "ZIP") {
$error = "<center><div id='no-ok'>قم برفع ملفات بصيغة .zip فقط</div></center>";
}else {
if ($file_size > 104857600) {
$error = "<div id='no'>ممنوع حجم الملف اكبر من 100 ميجا</div>";
}else {
$time_digit = time() . '_';
$new_file_name = $time_digit.'.zip';
move_uploaded_file($_FILES['up']['tmp_name'], "upload-msg/".$new_file_name);
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text, _file = :_file");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->bindParam(':_file', $new_file_name);
$sqladdcontent->execute();
}
}
}
}
}
?>
how to Getting error when submitting a form by ajax to page msg.php
The name of the variable is the error = $error
collect errors in php script as $errors array, then finaly ouput it as JSON:
print json_encode($errors);
and process it in success event handler
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(msg)
{
json = $.parseJSON(msg);
if (json.error[1] != "") //
$("#div-error-1").html(json.error[1]);
if (json.error[2] != "") //
$("#div-error-2").html(json.error[2]);
// and so on. Or you can use foreach construction. it will make code more universal
}
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
Related
I'm beginner in PHP and Magento,
I have Plugin which has a admin menu which refers to a page.
What I want to do is adding an admin controller for uploading a file to server from the page.
this is my structure:
MyPlugin/KnownUser/Controller/Adminhtml/Admin/Index.php
<?php
namespace MyPlugin\KnownUser\Controller\Adminhtml\Admin;
require_once( __DIR__ .'../../../../IntegrationInfoProvider.php');
use \DateTime;
class Index extends \Magento\Backend\App\Action
{
/**
* #var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$configProvider = new \MyPlugin\KnownUser\IntegrationInfoProvider();
$configText = $configProvider->getIntegrationInfo(true);
$customerIntegration = json_decode($configText, true);
$resultPage = $this->resultPageFactory->create();
$layout = $resultPage->getLayout();
$block = $layout->getBlock('main_panel');
$block->setAccountId($customerIntegration["AccountId"]);
$block->setVersion($customerIntegration["Version"]);
$block->setPublishDate($customerIntegration["PublishDate"]);
$block->setUploadUrl($this->getUrl('knownuser/admin/process/index'));
$block->setIntegrationConfig( $configText);
return $resultPage;
}
}
MyPlugin\knownuser\view\adminhtml\templates\admin.phtml
<p>
<label style="width:200px">Publisher</label>
<br />
<input readonly type="text" value="<?php echo $this->getAccountId() ?>"> </input>
</p>
<p>
<label style="width:100px">Version</label>
<br />
<input readonly type="text" value="<?php echo $this->getVersion() ?>">
</input>
</p>
<p>
<label style="width:100px">Publish Date</label>
<br />
<input readonly type="text" value="<?php echo $this->getPublishDate() ?
>" > </input>
</p>
<p>
<label style="width:100px">IntegrationdedConfig</label>
</p>
<textarea rows="10" cols="200" readonly>
<?php echo $this->getIntegrationConfig() ?>
</textarea>
<form id='form' method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script>
const url = '<?php echo $this->getUploadUrl()?>';
alert(url);
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
debugger;
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
</script>
So what I want to do is add a new controller and post my file to server, but I don't know how can I do that.
I tried to add another controller and post my file from JavaScript but it didn't work and just redirect my request.
my controller is like this:
MyPlugin\knownuser\Controller\Adminhtml\Process
<?php
namespace MyPlugin\KnownUser\Controller\Adminhtml\Admin;
class Index extends \Magento\Framework\App\Action\Action
{
public function execute()
{
die('test index');
echo('just for sure it has been ran');
}
}
Finally I found the solution, I just needed to add another controller like this and use it in my html:
<?php
namespace Queueit\KnownUser\Controller\Adminhtml\Admin;
class UploadConfig extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$configProvider = new \Queueit\KnownUser\IntegrationInfoProvider();
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
print_r('{');
$errors = "";
$extensions = ['json'];
$uploads = new \Zend_File_Transfer_Adapter_Http();
$files = $uploads->getFileInfo();
$file_name= '';
$file_tmp ='';
foreach ($files as $file => $fileInfo) {
if ($uploads->isUploaded($file)) {
if ($uploads->isValid($file)) {
if ($uploads->receive($file)) {
$info = $uploads->getFileInfo($file);
$file_name = $info[$file]['name'];
$file_type = $info[$file]['type'];
$file_tmp = $info[$file]['tmp_name'];
$file_ext1 = explode('.', $file_name);
$file_ext2 = end($file_ext1);
$file_ext = strtolower($file_ext2);
if (!in_array($file_ext, $extensions)) {
$errors = 'extension not allowed: ' . $file_name . ' ' . $file_type;
}
}
}
}
break;
}
$strConfig = "";
if ($file_name != "") {
if ($errors == "") {
$strConfig = file_get_contents($file_tmp);
$objectConfig = json_decode($strConfig);
$configProvider->updateIntegrationInfo($objectConfig->integrationInfo, $objectConfig->hash);
print_r("\"stat\" : \"Successful\",");
$configText = $configProvider->getIntegrationInfo(false);
print_r("\"configText\" : " . $configText);
}
} else {
$errors = 'Config file is not found in your request!';
}
if ($errors) {
print_r("\"errors\" : \"");
print_r($errors);
print_r("\"");
}
print_r('}');
}
}
}
<div class="form-group">
<p>
<label style="width:200px">Publisher: </label>
<label id="AccountId"><?php echo $this->getAccountId() ?></label>
</p>
<p>
<label style="width:100px">Version: </label>
<label id="Version"><?php echo $this->getVersion() ?> </label>
</p>
<p>
<label style="width:100px">Publish Date: </label>
<label id="PublishDate" class="form-control"> <?php echo $this->getPublishDate() ?> </label>
</p>
<button id='asdf' class="collapsible">Display JSON Integration Configuration</button>
<div class="content">
<div id="Config">
</div>
</div>
</div>
<hr class="HR_1" />
<div> <span>Select your new Integration Configuration to update the old one:</span></div>
<br />
<div style="overflow: auto">
<form id='form' method="post" enctype="multipart/form-data">
<label class="button" style="float:left">
<input type="file" name="files[]" accept=".json" id="files[]" class="button">
<i class="fa fa-cloud-upload"></i> Select configuration:
</label> <input type='text' id="upload-file-name" class="input-text" style='margin-left: 5px;margin-right: 10px;padding-bottom: 4px;width:400px;float:left'>
<button id="submit-uplode-file" class="button" type="submit" disabled name="submit" style="float:left">
<span id="SPAN_3">Update Configuration</span>
</button>
</form>
</div>
<br />
<div id="announcement"></div>
<script>
require([
'jquery'], function ($) {
var configString = '<?php echo $this->getIntegrationConfig() ?>';
if (configString != '') {
var config = JSON.stringify(JSON.parse(configString), null, '\t');
}
function output(inp) {
var configNode = document.getElementById("Config");
while (configNode.firstChild) {
configNode.removeChild(configNode.firstChild);
}
configNode.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
(function() {
if (config) {
output(syntaxHighlight(config));
}
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
const url = '<?php echo $this->getUploadUrl() ?>';
document.getElementById('files[]').onchange = function(e) {
if (e.target.files.length > 0) {
var filename = e.target.files[0].name;
document.getElementById("upload-file-name").value = filename;
document.getElementById("announcement").innerHTML = '';
document.getElementById("submit-uplode-file").disabled = false;
}
};
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
console.log(files);
jQuery.ajax({
url: url,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
console.log('Sending');
},
success: function(data) {
console.log(data);
try {
var jsonData = JSON.parse(data);
} catch (e) {
jQuery("#announcement").html("<Span style='color:red'>" + "Some thing went wrong!" + "</Span>").fadeIn();
jQuery("#announcement").html("<Span style='color:red'>" + data + "</Span>").fadeIn();
}
if (jsonData.stat != undefined && jsonData.stat == 'Successful') {
jQuery("#AccountId").text(jsonData.configText.AccountId);
jQuery("#PublishDate").text(jsonData.configText.PublishDate);
jQuery("#Version").text(jsonData.configText.Version);
output(syntaxHighlight(JSON.stringify(jsonData.configText, null, '\t')));
// jQuery("#Config").text(JSON.stringify(jsonData.configText, null, '\t'));
jQuery("#announcement").html("<Span style='color:#4CAF50'>The File is uploaded successfully!</Span>").fadeIn();
document.getElementById("submit-uplode-file").disabled = true;
} else {
if (jsonData.errors != undefined && jsonData.errors != '') {
jQuery("#announcement").html("<Span style='color:red'>" + jsonData.errors + "</Span>").fadeIn();
} else {
jQuery("#announcement").html("<Span style='color:red'>" + "Some thing went wrong!" + "</Span>").fadeIn();
}
}
},
error: function(e) {
console.log(e);
jQuery("#announcement").html("Uploading file is faild!").fadeIn();
}
});
});
})();
});
</script>
I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},
I'm trying to save some data into db using AJAX.It says it's successfully done but nothing happens.No data is being saved.Just keeps saying "Success".
index.php // form
<div id="cont">
<div id="kayit" style="display:none;">
Success
</div>
<div id="basarisiz" style="display:none;">
Empty or Fail
</div>
<form method="post" id="yaz" onsubmit="return false">
<input type="text" name="title" id="baslik" placeholder="Başlık" required><br/>
<textarea name="content" ></textarea><br/>
<input type="submit" name="gonder" value="Gönder" id="gonder" onclick="kayit()">
</form>
yaz.js
function kayit()
{
var baslik = $("input[name=title]").val();
var icerik = $("input[name=content]").val();
if (baslik =="" || icerik == "")
{
$('#basarisiz').show(1);
$('#kayit').hide(1);
}else
{
$.ajax ({
type: "POST",
url: "yazikaydet.php",
data: $("#yaz").serialize(),
success: function (sonuc) {
if (sonuc == "hata") {
alert ("unable to connect to db");
}else {
$('#kayit').show(1);
$('#basarisiz').hide(1);
$("input[name=title]").val("");
$("input[name=content]").val("");
}
}
}) }}
yazikaydet.php //the file which will save the data,not processing
<?php
include 'giris.php'; //sessions and connection strings
if(isset($_POST["gonder"]))
{
$baslik = $_POST["title"];
$icerik = $_POST["content"];
$tarih = date("d/m/20y");
$kull = $_SESSION["username"];
$kaydet = mysqli_query($connect,"INSERT INTO gonderiler (yazar,tarih,baslik,icerik) VALUES ('$kull','$tarih','$baslik','$icerik')");
if($kaydet)
{
echo "Yes";
}
else
{
echo "No";
}
}
?>
I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}
I have an upload field in my form.
I had this code in my form.php
<form id="photoform" name="photoform" method="post" onSubmit="return false" enctype="multipart/form-data">
<div id="upphotosection"></div>
<label>Upload photo</label>
<input name="uploadphoto" id="uploadphoto" type="file" />
<div class="innerformclear"></div>
<input id="hidden" value="" name="hidden" type="hidden" />
<label> </label>
<input name="upphoto_submit" id="upphoto_submit" type="submit" value="Submit"/>
<div style="clear:both;"> </div>
<label> </label>
<div id="result_upphoto_submit"></div>
</form>
This is the code in formaction.php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
include("../../../wp-load.php");
session_start();
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if($upphoto = $_FILES['uploadphoto']["name"] != '' ){
$path = 'images/profilephotos/';
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}
$postid = 52;
############### Check Duplication
$sel_photo = "SELECT * FROM `pro_table` WHERE `post_id` = '".$postid."'";
$sel_res = mysql_query($sel_photo) ;
if(mysql_num_rows($sel_res) == 0){
$ins_photo = "Insert into pro_table (post_id,photo_photo,int_status) values ('$postid','$upphoto','0')";
$ins_res = mysql_query($ins_photo);
}
else{
$upd_photo = "Update pro_table set photo_photo = '$upphoto' ,int_status='0' where post_id = '$postid' ";
$upd_res = mysql_query($upd_photo);
}
echo $_GET['callback'] . '('.json_encode("success").')';
This is the code in java script file.
$(document).ready(function() {
///////////// Submit action for upload photo
$("#upphoto_submit").click(function() {
if(document.getElementById('uploadphoto').value == '' ){
alert("Please upload Photo");
document.getElementById('uploadphoto').focus();
return false;
}
else {
$('#result_upphoto_submit').html('<img src="http://www.test.com/test/uploads/2012/04/ajax-loader.gif" class="loader" align="absmiddle" /> ').fadeIn();
var input_data = $('#photoform').serialize();
$.ajax({
type: "POST",
url: "http://www.test.com/test/themes/test/formaction.php",
dataType: 'jsonp',
data: input_data,
success: function(msg){
$('#result_upphoto_submit').html(' ');
if(msg == 'success') {
msg = '<p class="success_custom">Photo successfully added.</p>';
$('<div>').html(msg).appendTo('div#upphotosection').hide().fadeIn('slow');
} else {
msg = ' Exists';
alert("Error in updation");
}
}
});
return false;
}
});
});
If i browse an image and click submit it showed me the success message Photo successfully added. But there is no image in profile photos folder and there is no data stored in admin panel. I couldn't track the error. How do i correct that?
is there an error in?
$_FILES["uploadphoto"]["error"];
also i dont know how wordpress handle images but i miss the file movement:
if ($_FILES["uploadphoto"]["error"] != UPLOAD_ERR_OK) {
$tmp_name = $_FILES["uploadphoto"]["tmp_name"];
$name = $_FILES["pictures"]["name"];
$path = "images/profilephotos/".$name;
move_uploaded_file($tmp_name,$path);
}
or i suppose it is called here?
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}