I tired to solve this.
my form cant upload file using ajax, but it's work without ajax.
this's my code
insertpage.php
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$('document').ready(function(){
$('#btn').click(function(event){
event.preventDefault();
var x=$('#form1').serializeArray();
$.post(
$('#form1').attr('action'),
x,
function(){
$('.hasil').html('Berhasil Insert');
$('.hasil').fadeOut(5000);
$('input').val("");
$('textarea').val("");
})
})
})
</script>
</head>
<?php
$tanggal = date("Y-m-d");
echo"
<body>
<form id='form1' enctype='multipart/form-data' action='simpanpage.php' method='post'>
<table>
<tr>
<td> Foto </td> <td> : </td> <td> <input type=file name=fotoh id=fotoh> </td>
</tr>
<tr>
<td> Judul </td> <td> : </td> <td> <input type=text name=judul id=judul maxlength='50' size='50' required placeholder='Masukan Judul'> </td>
</tr>
<tr>
<td> Deskripsi </td> <td> : </td> <td> <textarea required id=deskripsi name='deskripsi' > </textarea> </td>
</tr>
<tr>
<td> Isi </td> <td> : </td> <td> <textarea required id=isi name='isi'> </textarea> </td>
</tr>
<tr>
<td> Label </td> <td> : </td> <td> <input type=text id=label name=label placeholder='Masukan Label'><input type=hidden name=tgl_dibuat id=tgl_dibuat value=".$tanggal."> </td>
</tr>
</table>
<br>
<button id='btn'>Save</button>
<br> <div class='hasil'> </div>
</form>
</body>
";
?>
koneks.php
<?php
class database{
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "oop_blog";
function connectMySQL(){
mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
mysql_select_db($this->dbName) or die("Database tidak ada!");
}
function manageinsertPage($judul, $isi, $tgl_dibuat, $deskripsi, $label){
$lokasi = $_FILES["fotoh"]["tmp_name"];
$namafoto = $_FILES["fotoh"]["name"];
$direktori = "gambar/$namafoto";
if (move_uploaded_file($lokasi, $direktori))
{
$qry = mysql_query("INSERT INTO pages(judul,isi,foto,tgl_dibuat,deskripsi,label) VALUES('$judul','$isi','$namafoto','$tgl_dibuat','$deskripsi','$label')");
echo"berhasil Insert Bersama Foto";
}
else{
$qry1 = mysql_query("INSERT INTO pages(judul,isi,tgl_dibuat,deskripsi,label) VALUES('$judul','$isi','$tgl_dibuat','$deskripsi','$label')");
echo"Berhasil";
}
}
?>
simpanpage.php
<?php
include "koneks.php";
$dbi = new database;
$dbi->connectMYSQL();
$dbi->manageinsertPage($_POST["judul"],$_POST["isi"],$_POST["tgl_dibuat"],$_POST["deskripsi"],$_POST["label"]);
?>
im just confused because, my form cant read $_FILES['fotoh']['name']; with ajax, that's made me fail when uploading..
the answer allways null in database.
i need help here, thank you so much
check here, tested
$('document').ready(function(){
$('#btn').click(function(event){
event.preventDefault();
$.ajax({
url : $('#form1').attr('action'),
type: "POST",
data : new FormData($('#form1')[0]),
processData: false,
contentType: false,
success:function(data){
}
});
})
})
If you are using a compatible browser, you can use the $.ajax function and FormData to do the file upload with something like this:
$('document').ready(function(){
$('#btn').click(function(event){
event.preventDefault();
$.ajax({
url: $('#form1').attr('action'), // simpanpage.php
type: 'POST',
contentType: 'multipart/form-data', // Same as your form enctype.
data: new FormData($('#form1')), // Your form with the file inputs.
processData: false // No need to process data.
}).done(function(){
console.log("Success: File uploaded!");
}).fail(function(){
console.log("Error: Failed to upload file!");
});
});
});
For more examples, please refer the doc.
Related
I design a simple page were user can put name, password and image using html.
I try to sent those data using ajax to specific php page, but I cannot implement this.
how I do this thing
Html code
<?php include('connection.php'); ?>
<form id="form" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="pass"></td>
</tr>
<tr>
<td>Photos:</td>
<td><input type="file" id="photos"></td>
</tr>
<tr>
<td><input type="submit" id="go"></td>
</tr>
</table>
</form>
Jquery and ajax
<script>
$(document).ready(function(){
$('#go').click(function(){
var img_name = $('#img_name').val();
var name = $('#name').val();
var pass = $('#pass').val();
$.ajax({
type : "POST",
url : "singup_submit.php",
data : { img_name:img_name, name:name, pass:pass},
success : function(done){
alert(done);
}
});
});
});
</script>
Php code
<?php
include('connection.php');
if(isset($_POST)){
$name = $_POST['name'];
$pass = $_POST['pass'];
$img_name=$_FILES['img_name']['name'];
$qr="INSERT INTO data (name,pass,img_name) VALUES ('$name','$pass','$img_name')";
$ex=mysqli_query($con,$qr) or die(mysqli_error($con));
if($ex==1)
echo 'done';
else
echo 'not done';
}
Follow this code ..It may help you
<script>
$(document).ready(function(){
$("#go").click(function(){
var name = $("#name").val();
var pasword = $("#password").val();
var photos = $("#photos").val();
if(name==''||pass==''||photos==''){
alert("Please Fill All Fields");
}
else{
$.ajax({
type : "POST",
url : "singup_submit.php",
data : formData,
cache : false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
</script>
you are not sending any file in your ajax request.
$(document).ready(function(){
$("#go").on('submit',function(e){
e.preventDefault()
$.ajax({
url: 'singup_submit.php',
type: 'POST',
data: new FormData(this),
contentType: false,
processData: false,
success: function(response){
alert(done);
},
error: function(data){
console.log("error");
console.log(data);
}
},
});
});
});
and then take data from global variables in php as you are doing now.
and please assign name to your form fields like so
<form id="form" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="name" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="pass"></td>
</tr>
<tr>
<td>Photos:</td>
<td><input type="file" name="img" id="photos"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="go"></td>
</tr>
</table>
</form>
and it should work.
A part on my page is responsible for multiple picture uploads, it worked for a while but it is not working anymore.
I'm using a WampServer Version 3.1.7 64bit and testing on localhost.
I have tried accepting and sending datas via ajax instead of html submit, but i didn't get datas on php side either, but on client side i had all datas before sending ( FormData() ).
HTML part:
<div class="div_shadow_here">
<form id="gallery_data" method="post" enctype="multipart/form-data">
<input type="hidden" name="formid" value="<?php echo $_SESSION[" formid "]; ?>" />
<table class="news_table">
<tr>
<td>
<p class="name_col">Gallery name:</p>
</td>
<td>
<input class="input_news" id="gallery_title" type="text" name="gallery_title" />
</td>
</tr>
<tr>
<td>
<p class="name_col">Picture(s):</p>
</td>
<td>
<input class="input_news" id="news_picture_path" type="file" name="picture_path[]" multiple />
<label id="label_for_input" for="picture_path">Select picture(s)</label><span id="uploadState"></span>
</td>
</tr>
<tr>
<td></td>
<td>
<div id="img_container"></div>
</td>
</tr>
</table>
<button class="print_button hidden_a" type="submit" name="login" id="save_news" form="gallery_data">Save</button>
</form>
</div>
PHP part for testing:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<script>console.log("Not empty")</script>';
if (isset($_POST['formid'])) {
echo '<script>console.log("'.$_POST['formid'].
'")</script>';
}
if (isset($_POST['gallery_title'])) {
echo '<script>console.log("'.$_POST['gallery_title'].
'")</script>';
}
if (isset($_FILES['picture_path']['name'])) {
echo '<script>console.log("'.count($_FILES['picture_path']['name']).
'")</script>';
}
} else {
echo '<script>console.log("Empty")</script>';
}
I get Notice: Undefined index: gallery_title.. errors without isset($_POST['gallery_title']) testing (same for all other input fields).
Ajax for testing:
$('body').on('click', '#save_news', function(e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
for (var key of formData.keys()) {
console.log(key);
}
for (var value of formData.values()) {
console.log(value);
}
$.ajax({
url: 'galleryupload.php',
type: 'POST',
success: function(data) {
alert("Data Uploaded: " + data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display
I am new in PHP and I made simple login page where I applied a ajax script to check "user already exist or not".
but script always returns me "user already taken" message whether I inserted new value. I checked whole code I cannot get the clue where I did mistake.
admin.php
==========
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src ="usernameavail.js"></script>
</head>
<form action="admin.php" method="post" name="loginfrm">
<table width="600" border="0">
<tr>
<td>User Name</td>
<td><input name="txtusername" type="text" maxlength="15" id="txtusername" /></td>
<span id="message"></span>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Password</td>
<td><input name="txtpass" type="password" maxlength="7" />
<span style="color:#FF0000">*</span> Minimum 5 alphanumeric
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit"/></td>
</tr>
<tr>
<td>Forget password?</td>
<td>New Register</td>
</tr>
</table>
</form>
=========
check.php
=========
<?php
include ("includes/dbConfig.php");
$username=$_POST["txtusername"];
$query=mysql_query("SELECT * from logininfo where username='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
===================
usernameavail.js
===================
$(document).ready(function()
{
$("#txtusername").change(function()
{
$("#message").html("<img src='images/ajax-loading.gif' /> checking...");
var username= $("#txtusername").val();
$.ajax(
{
type:"post",
url:"check.php",
data:"username="+username,success:function(data)
{
if(data==0)
{
$("#message").html("<img src='images/accept.png' /> Username available");
}
else
{
$("#message").html("<img src='images/error.png' /> Username already taken");
}
}
});
});
});
in javascript file, put quotes for zero
if(data == '0')
Change this to
$.ajax(
{
type:"post",
url:"check.php",
data:"username="+username
this
$.ajax(
{
type:"post",
url:"check.php",
data: username:username
It's better if in check.php you replace
echo $find;
with
if($find>0)
{
echo 'something';
}
And in your ajax call check if data has value.
Change this line
'data:"username="+username,success:function(data)'
to
data:{"txtusername":username},success:function(data)
And this will work
at the first , excuse me for my bad english
i working in ubuntu for a jquery/ajax system
my codes in below:
index.html
...
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<form name="stuSelForm" id="stuSelForm">
<table id="inputTable">
<tr><td colspan="3" align="center">Stu From</td></tr>
<tr>
<td> </td>
<td>St No : </td>
<td><input type="text" name="StNo" id="StNo" /></td>
</tr>
<tr>
<td></td>
<td>name : <br/> family : </td>
<td><input type="text" name="Fname" id="Fname" /><br/><input type="text" name="Lname" id="Lname" /></td>
</tr>
<tr>
<td colspan="3" align="right"><input type="submit" id="send" name="send" value="show" /></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript" src="js/jscodes.js"></script>
...
js file :
$(document).ready(function()
{
$('#stuSelForm').submit(function(event)
{
var form = $(this);
inputs = form.find("input");
serializedData = form.serialize();
inputs.attr("disabled","disabled");
$.ajax({
url:'process.php',
type:'POST',
data: serializedData,
dataType:'text',
cache: false,
success : function(data,textStatus,jqXHR){ alert(data); },
error : function(jqXHR,textStatus,errorThrown) { alert(textStatus+jqXHR.status+jqXHR.responseText+"..."); },
complete : function(jqXHR,textStatus)
{
inputs.removeattr("disabled");
}
});
event.preventDefault();
});
});
and process.php :
<?php
header("Content-Type: text/html");
$StNo = $_POST['StNo'];
echo $_POST['StNo'];
?>
now all things are ok but the return value isn't StNo
it is whole content of process.php
it's mean
please help me why this happen
are this for php extensions or a mistake from me or ...
tanx for ur help
It sounds like the php is not running. Are you running your HTML file which calls the php file through localhost / a server or directly from the directory? You need the php server to evaluate your php script.
problem in your header:
you write in jquery dataType: text but you write in php header("Content-Type: text/html");
change it for get success:
like this:
$.ajax({
url:'process.php',
type:'POST',
data: serializedData,
cache: false,
success : function(data,textStatus,jqXHR){ alert(data); },
error : function(jqXHR,textStatus,errorThrown) { alert(textStatus+jqXHR.status+jqXHR.responseText+"..."); },
complete : function(jqXHR,textStatus){inputs.removeattr("disabled");}
});
I remove dataType:, because jquery default settings is dataType:'html'
and you don't need write dataType in this case