I want to upload a file and send to server without refreshing page.
I have following line in my HTML file
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
upload.php file
if ($_FILES["mfile"]["error"] >0 )
{
echo "Error: " ;
}
else
{
if (file_exists("upload_email_files/" . $_FILES["mfile"]["name"]))
{
echo $_POST["file"]. " already exists. ";
}
else
{
$otp= move_uploaded_file('$_FILES["mfile"]"name"]','/../upload_templates/');
}
}
It's not working .Can anybody help me on this ?
It is not coming in upload.php and giving me error Illegal Invocation.
Thanks,
Shirish
in the case of "without refreshing page", you can use hidden iframe.
For reference,
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ ,
http://joekuan.wordpress.com/2009/06/12/ajax-a-simplified-version-of-file-upload-form-using-iframe/
Check this out I haven't tested it hope this will work http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader'));//remove [0]
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
//async: true,//Remove this line
//dataType: "JSONP",//Remove this line
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
Try this one :)
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
$(document).ready(function() {
$("#form-geninfo").submit(function(e)
{
e.preventDefault();
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
});
Related
My ajax successfully return the value but my problem is I can't use the value to my function. How do I convert this div to a value?
<?php
echo $ajax_user_id = '<div id="result"></div>'; //value can display here
getName($ajax_user_id); //value wont work here
?>
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});
</script>
You can't use it that way.because jQuery is a scripting language which runs in browser when DOM is fully loaded and elements are available to make selectors.While php is server side language which runs on server way before page load.anyway to fulfill your need you can try something like this.
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result);
getNameAjax(Result);
}
})
});
});
function getNameAjax(val)
{
$.ajax({
type: "POST",
url: GetNameAjax.php,
data:{'user_id':val},
success: function(res){
$('#name').html(res);
}
});
}
</script>
GetNameAjax.php file you can write like this
$ajax_user_id=$_POST['user_id'];
function getName($ajax_user_id)
{
return "name on the basis of id";
}
I have been trying to upload an image with AJAX but somehow it's not working. CodeIgniter always throwing 'You have not selected any file'.
Thanks in advance.
Here's my Controller -
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index() {
$this->load->view('upload/upload');
}
public function upload_file() {
$config['upload_path'] = './uploads/Ajax/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
$title=$this->input->post('title');
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors()."<br>".$title;
}
else {
$data = $this->upload->data();
echo $data['file_name']." uploaded successfully";
}
}
}
/* end of file */
And here's the view
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX File Upload</title>
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js"> </script>
<script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js"> </script>
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" autocomplete="off">
</p>
<p>
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile">
</p>
<input type="submit" name="submit" id="submit">
</form>
<h2>Result</h2>
<span id="result"></span>
</body>
I have tested in Firefox 43, IE11 & Chrome 43
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
secureuri :false,
fileElementId :'userfile',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
You need to add xhr function in ajax request
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
url: $(this).attr('action'),
data:formData,
cache:false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
you can use
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
no plugin required for this, for easiness you can use ajaxForm jquery plugin and just use
$('#form-id').ajaxSubmit({
// same config as ajax call but dont use data option right here
});
have a look on http://malsup.com/jquery/form/ to for more information about plugin
Use this
$("#upload-form").on('submit' ,function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: new FormData(form[0]),
dataType: 'json',
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function(data){
}
});
});
Use $.ajaxFileUpload instead $.ajax, this should work, if not please let me see your AjaxFileUpload.js
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajaxFileUpload({
url :'./upload/upload_file/',
fileElementId : 'userfile', // your input file ID
dataType : 'json',
//
data : {
'title' : $('#title').val() // parse title input data
},
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
I have done the code like this in view page and controller done in codeigniter
While pressing enter key multiple times data saving to the table. Can anybody help to solve this problem
View Page
<form>
<div class="cmt-box">
<textarea class="form-control" name="txtArea" id="txtArea<?php echo $row->id;?>" onkeypress="onTestChange(1)" rows="1"></textarea>
</div></form>
script
function onTestChange(id) {
$("#txtArea"+id).keypress(function(e) {
if(e.which == 13) {
dataString=document.getElementById("txtArea"+id).value;
$.ajax({
type: "POST",
url: "<?php echo site_url('show/insertcomment'); ?>",
data: { comment :dataString, id:id},
success: function(data){
location.reload();
}
});
}
});
}
$(".class_txtarea").keypress(function(e) {
if(e.which == 13) {
dataString=document.getElementById(this).value;
$.ajax({
type: "POST",
url: "<?php echo site_url('show/insertcomment'); ?>",
data: { comment :dataString, id:id},
success: function(data){
location.reload();
}
});
}
});
HTML:
<div class="cmt-box">
<textarea class="form-control mytext" name="txtArea" id="txtArea<?php echo $row->id;?>" rows="1"></textarea>
</div>
Jquery:
$(document).ready(function(){
$('.mytext').keyup(function (evt) {
evt = evt || window.event;
if (evt.keyCode == 13) { /* pressed enter key */
$.ajax({
type: "POST",
url: "<?php echo site_url('show/insertcomment'); ?>",
data: { comment :dataString, id:id},
success: function(data){
location.reload();
}
});
}
});
});
I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
You need to use data: {title: title} to POST it correctly.
In the PHP code you need to echo the value instead of returning it.
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
function signIn()
{
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: "auth_loginCode.jsp",
data: {Username: Username, Password: Password},
success: function (data) {
alert(data.trim());
window.location.reload();
}
});
}
contentType: 'application/x-www-form-urlencoded'
I am using an ajax call which is as follows
var ID=$(this).attr('id');
var input=$("#input_"+ID).val();
var dataString = {id: ID, value: input};
$("#span_"+ID).html(input);
if(input.length>0)
{
$.ajax({
type: "POST",
url: "/apps/worker_app.php",
data: dataString,
cache: false,
success: function(html)
{
$("#span_"+ID).html(span);
}
});
}
How can I get the data in my php function edit_ajax() which is inside worker_app
I use post but the array come to be empty
Thanks
Add dataType: 'json',
var ID=$(this).attr('id');
var input=$("#input_"+ID).val();
var dataString = {id: ID, value: input};
$("#span_"+ID).html(input);
if(input.length>0)
{
$.ajax({
type: "POST",
url: "/apps/worker_app.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(msg)
{
$("#span_"+ID).html(span);
}
});
}
and in worker_app.php get id and value by
$id=$_POST['id'];
$value=$_POST['value'];
edit_ajax($id,$value);
function edit_ajax($id,$value){
$sql="update from ..........";
}
Is this what u want?
Have you tried setting the dataType in your ajax call, like this:
$.ajax({
type:"POST",
url: "/apps/worker_app.php",
data: dataString,
cache: false,
success:function(html) {
},
dataType:"json"
});
Also, you could use a tool like firebug to see so the data is passed correctly in your ajax request.
Here is an example:
file1.php:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javscript"></script>
<script type="text/javascript">
$(document).ready(function() {
// catch submit event for your form
$('#form1').submit(function() {
// serialize data from form
var data = $(this).serialize();
$.ajax({
type="POST",
url:"file2.php",
data:data,
success:function(resp) {
// output response
$('#output').html(resp);
}
});
return false;
});
]);
</script>
</head>
<body>
<div id="output"></div>
<form method="POST" id="form1">
<input type="text" name="name" />
<input type="submit" value="send" />
</form>
</body>
</html>
file2.php:
<?php
if(isset($_POST['name'])) {
header('Content-type: text/html');
echo '<p>Response From Server - Your name is: '.$_POST['name'].'</p>';
}
?>
in /apps/worker_app.php get those posted values
$id=$_POST['id'];
$value=$_POST['value'];
and now use the values with your php function
function edit_ajax($id,$value)
{
echo $id;
echo $value;
}
echo $return=edit_ajax($id,$value);
now you can get the values in the current page as
success: function(html)
{
$("#span_"+ID).html(span);
}
> $.ajax({
> type: "POST",
> url: "/apps/worker_app.php",
> data: dataString,
> cache: false,
> success: function(msg)
> {
> $("#span_"+ID).html(msg);
> }
> });
on success, the argument function is receiving should be same used with
$("#span_"+ID).html(msg);