JS/Ajax alert box error - javascript

I have an alert box that keeps prompting "Image uploaded", even though $imagename is empty.
Here's the script:
<script>
function ajax_post1(ca){
var cat = ca;
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var image = document.getElementById("image").value;
if ($.isEmptyObject(image)) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;//build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "uploadsignuppackageresponse.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//$("#imagebox").append(response);
//$("#contentText").val(''); //empty text field on successful
//alert("haha");
}, error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
};
</script>
This is the main page:
<?php
$sql1 = mysql_query ("SELECT * FROM dumimage WHERE email = '$user_signup' AND cat='company' ");
$row = mysql_fetch_array($sql1);
$imagename = $row['name'];
?>
Name:
<input id="name" type="text" ></input>
<input id="image" type="hidden" value="<?php echo $imagename ?> "></input>
Description
<textarea id="description" rows="7" cols="42"></textarea>
Keywords:
<input id="keyword" type="text" placeholder="3 Maximum Keywords" ></input>
<input type="submit" value="Upload" class="pre" style="float:left; onClick="ajax_post1('company')">

Try this to see if your objects empty
if (image.length < 1) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}

Try to replace this line:
if ($.isEmptyObject(image)) {
With this one:
if (image != '') {
You also have to correct your php code because you have closed the bracket in the wrong place and you are missing a semicolon:
<input id="image" type="hidden" value="<?php echo $imagename;?>"></input>

Related

PHP form > JS OnUpdate > AJAX > should return MySQLi data, but I don't understand the code

I take no credit for the JS or AJAX code and I don't understand it. (Thank you Alon Alexander)
I have no AJAX knowledge and I would rather use PHP/JS with no JQuery, but I don't understand how to make it work.
I have a form that uses OnUpdate to fire a JS code that then uses AJAX to perform a SQLi query that should return the search data.
Problem is the return is alway the same even if I use data I KNOW should be returned true (file already exists), but Always returns 'New Entry' in my "Notice" Paragraph
Further, if record found I will then use JS to update form fields with record data. But that is for the next step in this. First need this to work.
i.e. "Record Exists" and form populates with that record info
or "New Entry" and forms stays blank.
index.php //reduced to needed info only
<?php include("process.php"); ?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/phone.js"></script>
<script type="text/javascript" src="js/entrynum.js"></script>
</head>
<body>
<?php
if (isset($_POST['reg-submit'])) {
echo "<p id='notice' style='padding: .5em; border: 2px solid red;'>Entry $entrynum Saved!<br>$timenow on $datenow</p>";
} else {
echo "<p id='notice' style='display: none; padding: .5em; border: 2px solid red;'></p>";
}
?>
<main>
<div class="Container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend><h1>Registration</h1></legend>
<label for="entrynum">Entry Number</label>
<input type="number" pattern="\d*" name="entrynum" id="entrynum" value="" required="true" placeholder="" autofocus onchange="entry_check()" />
<label for="fname">First Name</label>
<input type="text" name="fname" id="fname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<label for="lname">Last Name</label>
<input type="text" name="lname" id="lname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<input type="submit" name="reg-submit" id="reg-submit" value="Submit" />
</fieldset> <!-- Registration Form-->
</form>
</div>
</main>
</body>
</html>
entrynum.js
function entry_check() {
var entrynum = $("#entrynum").val();
// Send the AJAX call
$.post(
'entrysearch.php', // TO search.php page
{entrynum: entrynum}, // the DATA sent with the request
function(data) { // a CALLBACK function
if (data == 'none') { // no rows were found or an error occurred
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
return;
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}
);
}
entrysearch.php
<?php
include("includes/connect.php");
if (!isset($_POST['entrynum'])) {
echo 'none';
die();
}
$sql = $db->prepare("SELECT * FROM HeatWaveData WHERE entrynum=%d", $_POST['entrynum']);
$results = $db->query($sql);
$result = $results[0];
if (!$result) {
echo 'none';
die();
}
echo json_encode($result);
?>
I suggest you to use $.ajax function instead of post.
You can try by adding an id to the form by adding id="myform", then change entrynum.js as it follows:
// Change onSubmit behaviour for the form
$("#myform").on("submit", function(e) {
// Prevent page reload
e.preventDefault();
$.ajax({
// Get form action or uses current page.
url : $(this).attr('action') || window.location.pathname,
type: "POST",
// Get all input to submit and serialize on array (this will become $_POST)
data: $(this).serialize(),
success: function (data) {
//Here you have server response
},
error: function (jXHR, textStatus, errorThrown) {
// If error thrown jXHR contains XMLHttpRequest stuff like status
console.log(jXHR);
// You will see on an alert the real error thrown
alert(errorThrown);
}
});
});
FINALLY! It seems the sql needed a var ($entry) instead of using $_POST['entrynum']... Not sure why.
Then if no records found the ajax would not return anything (not even NULL). So I had to add some if statements and return '0' if no records found.
Further, it helped to add datatype "json' so object was parsed.
Javascript:
function entry_check() {
var entrynum = $("#entrynum").val();
$.post(
'entrysearch.php',
{entrynum: entrynum},
function(data) {
if (!data) {
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}, "json"
);
}
entrysearch.php
<?php
if (isset($_POST['entrynum'])) {
$entry = $_POST['entrynum'];
include("connect.php");
$sql = ("SELECT * FROM HeatWaveData WHERE entrynum = $entry");
if ($results=mysqli_query($db,$sql)) {
if ($rowcount=mysqli_num_rows($results)) {
$result = $results->fetch_object();
echo json_encode($result);
} else {
echo $rowcount;
}
}
}
?>
It works! Took me all night of research reading examples and docs.

Form action statement in PHP

I've got following problem with my PHP code:
my form is divided into two divs: first div shows up when the page is opened, second div displays after clicking a button (and this first one, thanks to Ajax, hides). My plan is to check a few statements, if true then create POST, get from it data and then dynamically create table, switching the content using Ajax again. BUT. I cannot use the 'action' thing because of the statements. When I've got 'submit' type - it creates POST, but reloads the page. If I replace it with 'button' type - Ajax works, but POST is empty.
Here's my code:
function formu ($w="1", $sr="on", $comma="",
$space ="", $other =""){?>
<form id="options" action="" method="POST" >
<div id = "first">
<h1 id = "title"> Choose a file </h1>
<input type = "radio" name="radio" id ="radio" value="op1" class ="radio"> ONE
<br>
<input type ="radio" name="radio" id="radio" value ="op2" class = "radio"> TWO
<br>
<input type ="radio" name="radio" id="radio" value="op3" class = "radio"> THREE
<br>
<input type = "button" id="Submit" Value = "Show">
</div>
<div id = "sec">
<h1 id = "title2"> Choose options </h1>
<p id="odwiersza"> Cut: </p>
<input type="text" name="w" value=""> <br>
<p id="Separators"> Separator: </p>
<input type = "checkBox" name="sr"> sr
<input type= "checkBox" name="comma"> comma
<input type = "checkBox" name = "space"> space
<input type = "checkBox" name ="other"> other (which?) <input type="text" name="such">
<br>
<input type="submit" id="choose" value = "Enter">
</div>
</form>
<?php }
formu();
?>
<div id= "here"> </div>
And then my ideas:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$w = $_POST['w'];
$sr = $_POST['sr'];
$comma = $_POST['comma'];
$space = $_POST['space'];
$other = $_POST['other'];
if (empty($w) || !($sr || $comma || $space || $other)){
echo "You have to enter the number and choose at least one separator!";
} else {
**/* here I've tried:
?> <script>
window.location = 'third.php'; //but it doesn't create POST table
</script>
<?php
require_once("third.php"); //but it attaches value with reloading the page, so first div shows up above my table
include "third.php"; //same as above
*/**
}
}
I've also tried Ajax script but it doesn't work as well:
<script>
var SubmitBtn2 = document.getElementById('choose');
SubmitBtn2.onclick = function(){
var formularz = document.getElementById('sec');
formularz.style.display = 'none';
var formularz1 = document.getElementById('first');
formularz1.style.display = 'none';
var title2 = document.getElementById('title2');
$(title2).hide();
var FormData = {plik: "<?php echo $_POST['radio']; ?>",
wiersz: "<?php echo $_POST['w']; ?>",
średnik: "<?php echo $_POST['sr']; ?>",
przecinek: "<?php echo $_POST['comma']; ?>",
spacja: "<?php echo $_POST['space']; ?>",
inne: "<?php echo $_POST['other']; ?>",
jakie: "<?php echo $_POST['such']; ?>"};
$(document.getElementById('back')).hide();
$.ajax({
type: 'POST',
url: "third.php",
data: FormData,
complete: function (reply) {
$.ajax({
type: 'POST',
url: "third.php",
complete: function (reply) {
$('here').append(reply);
}
});
}
});
}
</script>
EDIT:
I've tried to use event.preventDefault(); and now my code looks as below:
$(document.getElementById('choose')).click(function()
{ event.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$.get("test5new.csv", function(data) {
var build = '<table border="1" cellpadding="2" cellspacing="0" width="100%">\n';
var rows = data.split("\n");
var cut = rows.slice(<?php echo $w; ?>); //ponieważ tablice liczy się od 0
cut.forEach( function getvalues(thisRow) {
build += "<tr>";
var columns = thisRow.split("<?php echo $pattern; ?>");
for(var i=0;i<columns.length;i++){ build += "<td>" + columns[i] + "</td>"; }
build += "</tr>";
})
build += "</table>";
$(document.getElementById('wrap')).append(build);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
but, although it does not refresh, it doesn't create POST neither. Please please help.

How to get response from PHP file as an array using Ajax?

I am trying to get a full address by entering the postal code in a textbox in HTML form by press a button, I have two files the first one has the ajax function and the second one has the PHP code. I am not sure if my ajax code sending a request to PHP or not, Can anyone help me please?
here is the ajax file:
<script type="text/javascript">
$(document).ready(function(){
$('.addressbutton').click(function(){
ss= document.getElementById("address").value;
alert(ss);
$.ajax({
url: 'findaddress.php',
type: 'post',
data: ss,
success: function(response){
var replay = response.postal_code;
alert(replay);
document.getElementById('address').innerHTML = response.postal_code;
document.getElementById('address2').innerHTML = response.route;
document.getElementById('address3').innerHTML = response.locality;
document.getElementById('address4').innerHTML = response.postal_town;
document.getElementById('address5').innerHTML = response.administrative_area_level_2;
}
});
return false;
});
});
</script>
and here is the PHP code (findaddress.php)
<?php
header('Content-Type: application/json');
$ss=$_POST['address'];
$postcode = urlencode($ss);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?
address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);
if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}
$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if (is_array($component->type)) {
$type = (string)$component->type[0];
} else {
$type = (string)$component->type;
}
$myAddress[$type] = (string)$component->long_name;
}
$f1 = $myAddress['postal_code'];
$f2 = $myAddress['route'];
$f3 = $myAddress['locality'] ;
$f4 = $myAddress['postal_town'] ;
$f5 = $myAddress['administrative_area_level_2'] ;
$f6 = $myAddress['country'];
//print_r($myAddress);
$ORegisertation = array(
'postal_code' => $f1,
'route' => $f2,
'locality' => $f3,
'postal_town' => $f4,
'administrative_area_level_2' => $f5,
'country' => $f6
);
$account_json = json_encode($ORegisertation);
echo $account_json;
?>
HTML
<form name="frmRegistration" id="signup-form" method="post">
<div>
<input type="text" name="address" id="address" class="findaddress" placeholder="Postal code"/>
<input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" />
<input type="text" name="address2" id="address2" class="findaddress" placeholder="Line 1"/>
<input type="text" name="address3" id="address3" class="findaddress" placeholder="Line 2"/>
<input type="text" name="address4" id="address4" class="findaddress" placeholder="Line 3"/>
<input type="text" name="address5" id="address5" class="findaddress" placeholder="Line 4"/>
</div>
</form>
Javascript
$(document).ready(function(){
$('.addressbutton').click(function(){
ss = document.getElementById("address").value;
$.ajax({
url: 'findaddress.php',
type: 'post',
data: {address:ss}, //added an index address here
success: function(response){
var replay = response.postal_code;
//innerHTML is not an attribute of text boxes, so changed it to value
document.getElementById('address').value = response.postal_code;
document.getElementById('address2').value = response.route;
document.getElementById('address3').value = response.locality;
document.getElementById('address4').value = response.postal_town;
document.getElementById('address5').value = response.administrative_area_level_2;
},
error: function(response) {
alert("Error: "+response);
}
});
return false;
}); //added closing brace and bracket
});
added comments in script about changes made.
PHP FILE (findaddress.php)
<?php
header('Content-Type: application/json');
$ss = $_POST['address'];
$postcode = urlencode($ss);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);
if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}
$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if(is_array($component->type)) $type = (string)$component->type[0];
else $type = (string)$component->type;
$myAddress[$type] = (string)$component->long_name;
}
echo json_encode($myAddress);
die();
?>
taken out irrelevant indexing again, and irrelevant statements.
There is the ajax code with the html form just to have a better idea
<form name="frmRegistration" id="signup-form" method="post">
<div><input type="text" name="address" id="address" class="findaddress" placeholder="Postal code"/>
<input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" onclick="javascript:hello()"/>
<input type="text" name="address2" id="address2" class="findaddress" placeholder="Line 1"/>
<input type="text" name="address3" id="address3" class="findaddress" placeholder="Line 2"/>
<input type="text" name="address4" id="address4" class="findaddress" placeholder="Line 3"/>
<input type="text" name="address5" id="address5" class="findaddress" placeholder="Line 4"/>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.addressbutton').click(function(){
ss = document.getElementById("address").value;
//alert(ss);
$.ajax({
url: 'findaddress.php',
type: 'post',
data: {address:ss},
success: function(response){
var replay = response.postal_code;
alert(replay);
document.getElementById('address').innerHTML = response.postal_code;
document.getElementById('address2').innerHTML = response.route;
document.getElementById('address3').innerHTML = response.locality;
document.getElementById('address4').innerHTML = response.postal_town;
document.getElementById('address5').innerHTML = response.administrative_area_level_2;
}
});
return false;
}); //added closing brace and bracket
});
</script>
</form>
You are not sending data correctly ..
if you want to get value of address in php which is post from ajax do this
data: { address: ss}, //
And Either add dataType:'json' there in your ajax or use jsonParse(response)
you get a string there at your response you cannot directly use response.postal_code;
In this case, you want to make sure to define the type of response from the server. I like to place dataType:'json' in my $.ajax calls. Then in your PHP code, make sure to add a header of type application/json. This will make a difference with some browsers. I like to read the Response Preview with Google Chrome. It will automatically parse the response; especially helpful with debugging.
header('Content-type: application/json');
echo json_encode($account_json);
exit;

Upload file in iFrame

I'm trying to upload a file in an iFrame, so far everything seems to work fine, but I can't process the image in the PHP end as it doesn't seem to receive it...
It does seem to upload though as my progress bar does work and show progress and completes. The responseText says: No image selected?
Here is my aJax:
function submitFile() {
//The file location
var theFile = document.getElementById("image").files[0];
var xhr = new XMLHttpRequest();
//Disable submit button whilst upload is active
doc("submit").disabled = true;
//Completed
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById("imageUpload").innerHTML = xhr.responseText;
doc("submit").disabled = false; //Unlock submit button
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100);
document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%";
}
};
//Send data
xhr.open("POST", "php/uploadImage.php", true);
xhr.send(theFile);
}
This is the form where I am submitting the image from, it uploads when I select the file however and not when I click submit see the onchange function.
<form action="php/submitMessage.php" onsubmit="validation(this)" method="post" id="submitMessage" enctype="multipart/form-data">
<div class="left half">
<input class="text" type="text" name="name" placeholder="First and Second Name"
rules="[A-Za-z]*\s[A-Za-z]*" />
<input class="text" type="text" name="email" placeholder="Email Address"
rules="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" />
<textarea name="message" placeholder="Enter your message here..." rows="5"></textarea>
</div>
<div class="right half">
<input class="text" type="text" name="reg" placeholder="Car Registration"/>
<input type="file" onchange="submitFile();" name="image" id="image" style="display:none;" />
<input type="hidden" name="image_location" id="image_location"/>
<label for="image" id="imageUpload" class="uploadBtn">Upload Image</label>
<p>Message will be regarded as a quote request if you provide an image.</p>
</div>
<input type="submit" id="submit" style="background-color:#fff;color:#000;" value="Submit Message/Quote" />
</form>
This is my PHP, I want to receive the file, resize it, and then set a session variable to its location which will be used when the rest of the form is submitted as the file location will need to be added to the database row.
<?php
session_start();
//Image was selected
if($_FILES['image']['tmp_name']) {
//any errors?
if(!$_FILES['image']['error']) {
//validate the file and setup future filename
$new_file = date("Ymdhisa");
//Can't be larger than 5MB
if ($_FILES['image']['size'] > 5000000) {
//Resize the file
$width = 500;
//Keep aspect ratio
$size = getimagesize($_FILES['image']['tmp_name']);
$height = round($width*$size[1]/$size[0]);
//Create object
if ($size[2] == 1) {
$images_orig = imagecreatefromgif($_FILES['image']['tmp_name']);
} else if ($size[2] == 2) {
$images_orig = imagecreatefromjpeg($_FILES['image']['tmp_name']);
} else if ($size[2] == 3) {
$images_orig = imagecreatefrompng($_FILES['image']['tmp_name']);
}
//Get image size to create object
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
//Create resized object
$images_fin = imagecreatetruecolor($width, $height);
imagecopyresampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); //Resize the image
imagejpeg($images_fin,"images/".$new_images); //Save image to file
//Remove image from memory
imagedestroy($images_orig);
imagedestroy($images_fin);
//Set session key for file location
$_SESSION['tmp_image'] = "uploads/".$new_file; //Should be unset when message has been sent
$message = "File successfully uploaded!";
echo $message;
}
}
else
{
$message = "There was an error: ".$_FILES['image']['error'];
echo $message;
}
} else {
echo "No image selected?";
}
?>
This is my code and its work fine too me , Hope work for you too
function submitVisualMedia()
{
$(document).ready(function (e) {
var fd = new FormData($("#fileinfo")[0]);
$.ajax({
url:, //YOUR DESTINATION PAGE
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function ()
{
//some code if you want
}
});
});
return false;
}
<form method="post" id="fileinfo" onsubmit='return submitVisualMedia()' >
<input class="form-control" type="text" id="title" >
<input class="form-control" type="file" name="visualMedia" id="visualMedia" accept="image/*">
<button class="btn btn-success" type="submit">Upload</button>
</form>
and php side
public function uploadVisualMedia() {
ini_set('upload_max_filesize', '25M');
ini_set('post_max_size', '25M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
$fname = date('l-j-m-Y').'-'.rand(1,1000000);
$size = $_FILES['visualMedia']['size'];
$ftype = $_FILES['visualMedia']['type'];
$temp = $_FILES['visualMedia']['tmp_name'];
$type = array();
$type = explode("/", $ftype);
$filename = "galleries/" . $type[0] . "_gallery/" . $fname . "." . $type[1];
$index = 0;
while (file_exists($filename)) {
$filename = "galleries/" . $type[0] . "_gallery/" . $fname . "($index)" . "." . $type[1];
$index++;
}
move_uploaded_file($temp, $filename);
}
You most change little in this code and it should work for you fine . with this you can upload video an audio too.
change $filename to some folder name you want..

Upload image and text by same form

When I upload image and text by separate form, its work well. But Its not work when I add together.
My form text upload by js and image upload by a php file.
And I think my problem in my form.
If I upload together with js, What change in my js and submit.php, which also add below.
Here is my form code that not work together
<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>
<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>
<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>
js
$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
error.fadeOut();
function updateCommentbox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
complete: function(data){
commentList.prepend(data.responseText);
commentList.fadeIn(2000);
}
});
}
function updateCommentnum(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
complete: function(data){
commentCountList.html(data.responseText);
commentList.fadeIn(2000);
}
});
}
function error_message(){
error.fadeIn();
}
function checkForm(){
if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
return true;
else
return false;
}
//on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
//we deactivate submit button while sending
$("#submit").attr({ disabled:true, value:"Sending..." });
$("#submit").blur();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
commentList.prepend(data.responseText);
updateCommentbox();
updateCommentnum();
//reactivate the send button
$("#submit").attr({ disabled:false, value:"Submit Comment!" });
$( '#cmntfrm' ).each(function(){
this.reset();
});
}
});
}
else //alert("Please fill all fields!");
error_message();
//we prevent the refresh of the page after submitting the form
return false;
});
});
Submit.php
<?php header('Content-Type: charset=utf-8'); ?>
<?php
include("db.php");
include_once("include/session.php");
switch($_POST['action']){
case "update":
echo updateComment($_POST['tutid']);
break;
case "updatenum":
echo updateNumComment($_POST['tutid']);
break;
case "insert":
date_default_timezone_set('Asia/Dhaka');
echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
break;
}
function updateNumComment($tutid) {
//Detail here
}
function updateComment($tutid) {
//Detail here
}
function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;
//Upload image script that not work here when i try together so i took it at separate file and then tried with above form
$output_dir = "comimage/";
$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = #end(explode(".", $_FILES["url"]["name"]));
if(isset($_FILES["url"]["name"]))
{
//Filter the file types , if you want.
if ((($_FILES["url"]["type"] == "image/gif")
|| ($_FILES["url"]["type"] == "image/jpeg")
|| ($_FILES["url"]["type"] == "image/JPG")
|| ($_FILES["url"]["type"] == "image/png")
|| ($_FILES["url"]["type"] == "image/pjpeg"))
&& ($_FILES["url"]["size"] < 504800)
&& in_array($extension, $allowedExts))
{
if ($_FILES["url"]["error"] > 0)
{
echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
}
if (file_exists($output_dir. $_FILES["url"]["name"]))
{
unlink($output_dir. $_FILES["url"]["name"]);
}
else
{
$pic=$_FILES["url"]["name"];
$conv=explode(".",$pic);
$ext=$conv['1'];
$user = $_SESSION['username'];
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
$pic=$output_dir.$user.".".$ext;
$u_imgurl=$user.".".$ext;
}
}
else{echo '<strong>Warning !</strong> File not Uploaded, Check image' ;}
}
//Submit main comment
if ($parent_id == 0){
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub = "Comment to";
$query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
} else {
if ($parent_id >= 1){
global $dbh;
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub2 = "Reply to";
$query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
}
}
}
?>
on click of submit you can put the code in js you have to make change in the js file
$.post('phpapgename.php',data:jquerydata,function(){
})
in the .php page you can put your query to submit your data.
You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.
Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.

Categories