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);
},
Related
Here is the form View From
<form class="form-horizontal" role="form" id="frm_bulletin_board" method="post">
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> Title <font style="color:red;">*</font></label>
<div class="col-sm-9">
<input type="text" class="col-xs-12" name="txt_title" id="txt_title" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> Description <font style="color:red;">*</font></label>
<div class="col-sm-9">
<textarea id="txt_description" class="col-xs-12" name="txt_description" ></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1">Upload Images </label>
<div class="col-sm-9">
<input type="file" class="col-xs-100" name="multiple_files" id="multiple_files" multiple />
<span id="error_multiple_files"></span>
</div>
</div>
</form>
function add_bulletin_board_with_images(){
var error_images = '';
var form_data = new FormData();
var files = $('#multiple_files')[0].files;
if(files.length > 10)
{
error_images += 'You can not select more than 10 files';
}
else
{
for(var i=0; i<files.length; i++)
{
var name = document.getElementById("multiple_files").files[i].name;
var ext = name.split('.').pop().toLowerCase();
//if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
// {
// error_images += '<p>Invalid '+i+' File</p>';
// }
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("multiple_files").files[i]);
var f = document.getElementById("multiple_files").files[i];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
error_images += '<p>' + i + ' File Size is very big</p>';
}
else
{
form_data.append("file[]", document.getElementById('multiple_files').files[i]);
}
}
}
if(error_images == '')
{
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#error_multiple_files').html('<br /><img style="width:5%;" src="../assets/images/loader-gif.gif">');
},
success:function(data)
{
$('#error_multiple_files').html('');
$.gritter.add({
text: '<i class="fa fa-check"></i> Files uploaded successfully!',
class_name: 'gritter-success'
});
//document.getElementById("frm_bulletin_board").reset();
$('#multiple_files').val('');
}
});
}
else
{
$('#multiple_files').val('');
$('#error_multiple_files').html("<span class='text-danger'>"+error_images+"</span>");
return false;
}
}
php file upload.php
<?php
//////////db connection
session_start();
$db_servername = "localhost";
$db_username = "cwsp_user";
$db_password = "0cu1Fz3h02yHENYZ";
$db_name = "cwsp";
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//////////////////////////////
date_default_timezone_set('America/New_York');
$date = date('Y-m-d');
$date_time = date("Y-m-d h:i:s");
if(count($_FILES["file"]["name"]) > 0)
{
//$output = '';
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$file_size =$_FILES['file']['size'][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $conn))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$query = "
INSERT INTO bulletin_images
VALUES ('','1','','".$file_name."','', '".$file_size."','$date_time','Active','$_SESSION[ORGID]')
";
$statement = $conn->prepare($query);
$statement->execute();
}
}
}
function file_already_uploaded($file_name, $conn)
{
$query = "SELECT * FROM bulletin_images WHERE file_name = '".$file_name."'";
$result=$conn->query($query);
$number_of_rows = $result->num_rows;
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
i want to save title and description in MYSQL table named 'bulletin_board' and want to fill the last inserted id of bulletin board in the separate 'images' table, i can do this but i am stuck on figuring out how to pass title and description to the function add_bulletin_board_with_images()
thanks for all of your help but i found the solution by using form_data.append("param", "value") to add extra parameters in form_data
I have used dropzone js inside a small form with couple of fields. I want to submit both images and form data all at once to the database. No errors can be seen in the logs and was searching all over the internet for a solution. I'm a newbie to PHP, so a bit of help would much appreciated.
Form
<form action="index.php" method="POST" class="form-horizontal" role="form">
<div class="form-group"></div>
<label for="name">Name :</label>
<input type="text" name="name" id="input-title" class="form-control">
<br><br>
<label for="description">Email:</label>
<input type="text" name="description" id="input-description" class="form-control">
<br><br>
<label for="File">File: </label>
<br><br>
<div class="dropzone dropzone-previews" name="File" id="my-awesome-dropzone"></div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PHP Query
<?php
if( isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['email']) && !empty($_FILES)){
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'mystore';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$name = $_POST['name'];
$email = $_POST['email'];
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
$conn->query("INSERT INTO products (product_name,details,category, date_added) VALUES('".$name."','".$email."','".$fileName."','".date("Y-m-d H:i:s")."')");
}
}
else{
$error = "Fill All Details First !!";
if ( isset($_POST['submit']) && isset($error)) { echo $error; }
}
?>
Dropzone JS
<script type="text/javascript">
Dropzone.autoDiscover = false;
jQuery(document).ready(function() {
$("div#my-awesome-dropzone").dropzone({
url: "/file/post"
});
});
</script>
You must use something like this
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#my-awesome-dropzone", {
maxFiles: <?php echo $upload_file_number; ?>,
url: "remote/upload-file.php",
addRemoveLinks: true,
autoProcessQueue: false,
init: function() {
this.on("maxfilesexceeded", function(file){
//handle error for max file size
});
var submitButton = document.querySelector("#submit-button");
var id_import_xls;
var myDropzone = this;
submitButton.addEventListener("click", function(e){
/* HERE PUT THE AJAX FOR SUBMIT FORM AFTER SUBMIT UPLOAD THE FILE */
if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
//handle the error for no file selected if needed
}else{
//with this start upload
myDropzone.processQueue();
};
});//fine addEventListener
this.on("error", function(file, response) {
//handle the error
});
this.on("complete", function (file, response) {
//here can handle the success of upload
});
},
success: function(file, response){
//here can handle the success of upload
},
});
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 have a code, in a file called service.php which does as follows:
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
// Code to add entry into database
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
And the file to send the data via POST method using AJAX is:
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
The action attribute of the form #addRunner is:
<form action="service.php" id="addRunner" name="addRunner" method="POST">
<!-- Form Elements -->
</form>
Note that the action attribute for the form element is simply service.php instead of service.php?action=addRunner. However, the form still works perfectly, and successfully adds new "runner" information into the database. How does this happen?
Shouldn't the condition ($_POST['action'] == 'addRunner') fail and prevent the code to enter data into the database from running?
For the sake of completeness, the entirity of my code is as below.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>2011 Race Finishers</title>
<link href="styles/my_style.css" rel="stylesheet">
</head>
<body>
<header>
<h2>2011 Race Finishers!</h2>
</header>
<div id="main">
<ul class="idTabs">
<li>Male Finishers</li>
<li>Female Finishers</li>
<li>All Finishers</li>
<li>Add New Finishers</li>
</ul>
<div id="male">
<h4>Male Finishers</h4>
<ul id="finishers_m"></ul>
</div>
<div id="female">
<h4>Female Finishers</h4>
<ul id="finishers_f"></ul>
</div>
<div id="all">
<h4>All Finishers</h4>
<ul id="finishers_all"></ul>
</div>
<div id="new">
<h4>Add New Finishers</h4>
<form action="service.php" id="addRunner" name="addRunner" method="POST">
First Name: <input type="text" name="txtFirstName" id="txtFirstName"> <br>
Last Name: <input type="text" name="txtLastName" id="txtLastName"> <br>
Gender: <select name="ddlGender" id="ddlGender">
<option value="">--Please Select--</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select> <br>
Finish Time:
<input type="text" id="txtMinutes" name="txtMinutes" size="10" maxlength="2">
<input type="text" id="txtSeconds" name="txtSeconds" size="10" maxlength="2">
<br><br>
<button id="btnSave" type="sumbit" name="btnSave">Add Runner</button>
<input type="hidden" id="action" name="action" value="addRunner">
</form>
</div>
</div>
<footer>
<h4>Congratulations to all our finishers!</h4>
<button id="btnStart">Start Page Updates</button>
<button id="btnStop">Stop Page Updates</button>
<br>
<span id="freq"></span><br><br>
Last Updated: <div id="updatedTime"></div>
</footer>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_scripts.js"></script>
<script src="scripts/jquery.idTabs.min.js"></script>
</body>
</html>
My jQuery is:
$(document).ready(function(){
var FREQ = 10000 ;
var repeat = true;
function showFrequency(){
$("#freq").html( "Page refreshes every " + FREQ/1000 + " second(s).");
}
function startAJAXcalls(){
if(repeat){
setTimeout( function() {
getDBRacers();
startAJAXcalls();
},
FREQ
);
}
}
function getXMLRacers(){
$.ajax({
url: "finishers.xml",
cache: false,
dataType: "xml",
success: function(xml){
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$(xml).find("runner").each(function() {
var info = '<li>Name: ' + $(this).find("fname").text() + ' ' + $(this).find("lname").text() + '. Time: ' + $(this).find("time").text() + '</li>';
if( $(this).find("gender").text() == "m" ){
$('#finishers_m').append( info );
}else if ( $(this).find("gender").text() == "f" ){
$('#finishers_f').append( info );
}else{ }
$('#finishers_all').append( info );
});
getTimeAjax();
}
});
}
function getDBRacers()
{
$.getJSON("service.php?action=getRunners", function(json)
{
if(json.runners.length > 0)
{
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$.each(json.runners, function()
{
var info = '<li>Name: ' + this['fname'] + ' ' + this['lname'] + '. Time: ' + this['time'] + '</li>';
if(this['gender'] == 'm')
{
$('#finishers_m').append(info);
}
else if(this['gender'] == 'f')
{
$('#finishers_f').append(info);
}
else {}
$('#finishers_all').append(info);
});
}
});
getTimeAjax();
}
function getTimeAjax(){
var time = "";
$.ajax({
url: "time.php",
cache: false,
success: function(data){
$('#updatedTime').html(data);
}
});
}
$("#btnStop").click(function(){
repeat = false;
$("#freq").html( "Updates paused." );
});
$("#btnStart").click(function(){
repeat = true;
startAJAXcalls();
showFrequency();
});
showFrequency();
getDBRacers();
startAJAXcalls();
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
function clearInputs()
{
$("#addRunner:input").each(function(){
$(this).val('');
});
}
$("#addRunner").submit(function() {
return false;
});
});
And finally the contents of Service.php is:
<?php
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname))
{
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) )
{
fail('Please enter a first and last name.');
}
if( empty($gender) )
{
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result)
{
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
}
else
{
fail('Insert failed.');
}
exit;
}
else if($_GET['action'] == 'getRunners')
{
$query = "SELECT first_name, last_name, gender, finish_time FROM runners ORDER BY finish_time ASC";
$result = db_connection($query);
$runners = array();
while($row = mysqli_fetch_array($result))
{
array_push($runners, array('fname' => $row['first_name'], 'lname' => $row['last_name'], 'gender' => $row['gender'], 'time' => $row['finish_time']));
}
echo json_encode(array("runners" => $runners));
exit;
}
function db_connection($query)
{
$dbc = mysqli_connect('127.0.0.1','runner_db_user','runner_db_password','race_info')
or die('Error connecting to Database');
return mysqli_query($dbc,$query);
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
It will work reason behind this is action is value of name attribute from hidden field. It is not the action of your form tag. If you want to make it fail for testing purpose you should change the value of hidden field to something else in your form and then check again.
This is your hidden field
<input type="hidden" id="action" name="action" value="addRunner">
You can do like this for testing only
<input type="hidden" id="action" name="action" value="addRunners">
It will not satisfy this if condition
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
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']) ;}