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.
Related
I have a table of recipes created by a particular user, and when the pencil mark on each row of the table is clicked, a modal is displayed, showing the details of this particular recipe and it should allow the user to edit the recipe and save the updated version to the database. However, although the details are correctly being passed to the modal, the recipe id doesn't seem to be passed to the modal, since I have tried to output the recipe id into the console and it says the recipe id is undefined. I have tried to debug this error but to no avail. Can anyone provide any insight into why this might be?
//Recipe.js
$('.editThis').on('click', function() {
var recipe_id = $(this).attr('data-id');
var request = $.ajax({
url: "ajax/displayRecipe.php",
type: "post",
dataType: 'json',
data: {recipe_id : recipe_id}
});
request.done(function (response, textStatus, jqXHR){
console.log("response " + JSON.stringify(response));
$('#name').val(response.name);
$('#date').val(response.date);
});
});
$('#editRecipe').click(function() {
var recipe_id = $(this).attr('data-id');
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
});
//Recipe.php
<?php
$recipeObject = new recipeList($database); //Lets pass through our DB connection
$recipe = $recipeObject->getUserRecipes($_SESSION['userData']['user_id']);
foreach ($recipe as $key => $recipes) {
echo '<tr><td>'. $value['name'].'</td><td>'. $value['date'].'</td><td>'.'<a data-id = '.$value['recip_id'].' data-toggle="modal" class="edit editThis" data-target="#editRecipe"><i class="fa fa-pencil"></i></a>'.'</td></tr>';
}
?>
// editRecipe Modal
<div id="recipe" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header recipe">
<h1 class="modal-title">Edit Recipe</h4>
</div>
<div class="modal-body">
<form method="post" id="updateRecipeForm">
<?php
require_once('classes/recipes.classes.php');
$recipeObject = new recipeList($database);
$recipe = $recipeObject->getRecipeDetails(recipe_id);
if(isset($_POST['submit'])) {
$updateRecipe = $recipeObject ->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
if($updateRecipe) {
echo ("Your recipe has been updated!";
}
}
?>
<div class="form-group">
<input type="text" class="control-form" id="name" value = "<?php echo $recipe['name']; ?>">
</div>
<div class="form-group">
<input type="date" class="control-form" id="date" value = "<?php echo $recipe['date']; ?>">
</div>
</div>
<div class="form-group">
<input type="hidden" class="form-control" data-id=".$recipe['recipe_id']." id="recipe_id" name="recipe_id" value = "<?php echo $recipe['recipe_id']; ?>">
</div>
<button type="submit" class="btn recipe" id="editRecipe" data-dismiss="modal">Save</button>
</form>
</div>
</div>
</div>
</div>
//ajax - updateRecipe.php
<?php
require_once('../includes/database.php');
require_once('../classes/recipes.classes.php');
if($_POST['name'] && $_POST['date'] && $_POST['trans_id']){
$recipeObject = new recipeList($database);
echo $recipeObject->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
}
?>
//recipes.classes.php
...
public function getRecipeDetails($recipeid){
$query = "SELECT * FROM recipe WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':recipe_id', $recipeid);
$pdo->execute();
return $pdo->fetch(PDO::FETCH_ASSOC);
}
public function updateRecipe($name, $date, $recipe_id){
$query = "UPDATE recipe SET name = :name, date = :date WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':name', $name);
$pdo->bindParam(':date', $date);
$pdo->bindParam(':recipe_id', $recipe_id);
$pdo->execute();
}
Try the following:
$(document).on('click', '.editThis',function() {...});
$(document).on('click','#editRecipe',function() {...});
Try this onclik function
Some time you cant get the apt value from this So Try this method.
we can use id but in your case you foreach the a tag so we cant repeat id. Hope Its Works
<a data-toggle="modal" class="recipe_<?php echo $value['recipe_id']; ?> edit editThis" onclick="editRecipe('<?php echo $value['recipe_id']; ?>')" ><i class="fa fa-pencil"></i></a>
function editRecipe(txt) {
var recipe_id = $('.recipe_'+txt).val();
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
};
I have a dropdown list, via <select>, that is being generated by a javascript code, which is also coming from my database:
function dirfunc(){
var dirdiv = document.getElementById("dirdiv");
var ahref = document.getElementById("href");
var directidarr = new Array();
var directorarr = new Array();
<?php
include("../conn.php");
if($stmt = $con->prepare("SELECT directorid,directorname FROM directortb")){
$stmt->execute();
$stmt->bind_result($directorid,$directorname);
$counter = 0;
while($stmt->fetch()){
?>
directidarr[<?php echo $counter; ?>] = "<?php echo $directorid; ?>";
directorarr[<?php echo $counter; ?>] = "<?php echo $directorname; ?>";
<?php
$counter = $counter + 1;
}
$stmt->close();
}
?>
var div = document.createElement("div");
div.setAttribute("class","form-group");
var label = document.createElement("label");
label.setAttribute("class","col-sm-2 control-label");
label.appendChild(document.createTextNode("Director"));
var div2 = document.createElement("div");
div2.setAttribute("class","col-sm-9");
var sel = document.createElement("select");
sel.setAttribute("name","director");
sel.setAttribute("class","form-control");
for (var x = 0; x < directidarr.length; x++){
var opt = document.createElement("option");
opt.appendChild(document.createTextNode(directorarr[x]));
opt.setAttribute("value", directidarr[x]);
sel.appendChild(opt);
}
var div3 = document.createElement("div");
div3.setAttribute("class","col-sm-1");
var div4 = document.createElement("div");
div4.setAttribute("class","input-group");
div2.appendChild(sel);
div3.appendChild(ahref);
div.appendChild(label);
div.appendChild(div2);
div.appendChild(div3);
dirdiv.appendChild(div);
}
In my HTML code, where it generates the dropdown, on its right side is a button that would show a modal. In this modal is a form that would allow users to add more option for the select dropdown.
Here is the script I am using to add data without refreshing the page:
$(function() {
$("#adddirector").click(function(e) {
e.preventDefault();
var directorname = $("#directorname").val();
var dataString = 'directorname=' + directorname;
if(directorname == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeIn(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../action.php",
data: dataString,
success:{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
With this form:
<form class="form-horizontal" action="../action.php" method="POST">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Director's Name</label>
<div class="col-sm-10" id="ccdiv">
<input type="text" class="form-control" name="directorname" id="directorname" value="" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="adddirector" id="adddirector">Add Director <span class="glyphicon glyphicon-plus"></span></button>
</div>
</div>
</form>
But after adding a new data, through the form or the back-end/phpmyadmin, the dropdown is not updating. User has to still refresh the page in order for the dropdown to be updated. What am I missing or should do with my script?
I'm assuming the form to create a new Director sends an ajax request on submit, that is handled by some PHP code which will update the database with this new entry.
I suggest that, in this PHP code, you return the id of the newly inserted entry. You can then add a "success" function to your ajax call, which will receive that new id once it is inserted, so you can use it to add a new row to your select box.
EDIT:
$(function() {
$("#adddirector").click(function(e) {
e.preventDefault();
var directorname = $("#directorname").val();
//in jQuery you can pass an object, directorname will now show up as $_POST['directorname'] in your PHP handler.
var dataObj = {'directorname': directorname}
if(directorname == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeIn(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../action.php",
data: dataObj,
//success function should receive the id back as result
success: function(result){
var newId = result;
// create and append the new option here with the new id and the given name.
var newOption = $('<option></option>');
newOption.val(result);
newOption.html(directorname);
$('.form-control[name="director"]').append(newOption)
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
And make sure that your php file action.php echoes the new id at the end of file! If you want me to take a look at that please post the code in that file also.
Here's a question from stackoverflow might help you with php. Getting insert id with insert PDO MySQL
As you can see I want to create in a while multiple forms and buttons. The problem is when I want to submit one row from my array I want to execute this specific form and not another.
Even I put button tag inside the form I have problem. I think to set a unique id to form tag such as id="form_submit_change_status<?php echo $row['id_user']; ?>". But then the problem is what changes I have to do to the javascript code.
sorry for my English and I hope to understand my problem...
while($row = $result->fetch_array() ){
<form name="form_submit_change_status" id="form_submit_change_status" action="">
<input type="text" class="user_id" id="user_id" name="user_id" value="<?php echo $row['id_user']; ?>" />
<input type="text" name="is_enabled" value="<?php echo $row['is_enabled']; ?>" />
</form>
<button type="submit" id="submit_change_status" class="btn btn-warning btn-xs" value="<?php echo $row['is_enabled']; ?>">Change status</button>
}
$(document).ready(function(){
$('#submit_change_status').click(function(){
var formData = $("#form_submit_change_status").serializeArray();
var userId = $("#user_id").val();
alert(userId);
var URL = $("#form_submit_change_status").attr("action");
var URL = "change_status_user.php";
$.post(URL,
formData,
function(data, textStatus, jqXHR)
{
// alert("Data: " + data + "\nStatus: " + textStatus);
}).fail(function(jqXHR, textStatus, errorThrown)
{
});
var varChangeStatus = $('#is_enabled'+userId).val();
if(varChangeStatus=="true"){
$('#is_enabled'+userId).html('false');
}else{
$('#is_enabled'+userId).html('true');
}
});
});
</script>
// change_status_user.php
$DBConnection = new DBConnection();
if (isset($_POST['is_enabled'])) {
$id = $_POST['user_id'];
$status = $_POST['is_enabled'];
if($status=="true")
$status = "false";
else
$status = "true";
$sql = "UPDATE users SET is_enabled = '$status' WHERE id_user = $id";
$res = $DBConnection->db_connection->query($sql);
echo $sql;
}
As suggested above by others, it's flexible to use classes as opposed to IDs as they need to be unique. Classes also help grouping elements for easier access later.
HTML(PHP):
while($row = $result->fetch_array() ){
<form name="form_submit_change_status" class="form_submit_change_status" action="">
<input type="text" class="user_id" name="user_id" value="<?php echo $row['id_user']; ?>" />
<input type="text" class="is_enabled" name="is_enabled" value="<?php echo $row['is_enabled']; ?>" />
<button type="button" class="btn btn-warning btn-xs" value="<?php echo $row['is_enabled']; ?>">Change status</button>
</form>
}
jQuery:
$(function(){
$('.btn.btn-warning').click(function(e) {
e.preventDefault();
var $form = $(this).closest(".form_submit_change_status");
var formData = $form.serializeArray();
var userId = $form.find(".user_id").val();
alert(userId);
//var URL = $form.attr("action");
var URL = "change_status_user.php";
$.post(URL, formData)
.done(function(data) {
//success
}).
fail(function(jqXHR, textStatus, errorThrown) {
//failure
});
var $isStatus = $form.find(".is_enabled");
var varChangeStatus = $isStatus.val();
$isStatus.val(varChangeStatus=="true" ? "false" : "true");
});
});
You're using a while loop to create HTML elements, but using the same ID attribute each time. IDs need to be unique; classes, however, do not.
Try this instead:
PHP/HTML:
while($row = $result->fetch_array() ){
<form name="form_submit_change_status" class="form_submit_change_status" action="">
<input type="text" class="user_id" name="user_id" value="<?php echo $row['id_user']; ?>" />
<input type="text" class="is_enabled" name="is_enabled" value="<?php echo $row['is_enabled']; ?>" />
<button type="submit" class="btn btn-warning btn-xs" value="<?php echo $row['is_enabled']; ?>">Change status</button>
</form>
}
JS:
$(document).ready(function() {
$('.submit_change_status').click(function(e) {
e.preventDefault();
var $form = $(this).closest(".form_submit_change_status");
var formData = $form.serializeArray();
var userId = $form.find(".user_id").val();
alert(userId);
// var URL = $form.attr("action");
var URL = "change_status_user.php";
$.post(URL,
formData,
function(data, textStatus, jqXHR) {
// alert("Data: " + data + "\nStatus: " + textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) {});
var $isEnabled = $form.find('.is_enabled');
var varChangeStatus = $isEnabled.val();
if (varChangeStatus == "true") {
$isEnabled.html('false');
} else {
$isEnabled.html('true');
}
});
});
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.
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>