jQuery:: AJAX is not return any callback - php

For some reason I'm not getting the callback from post.php
Here is my index.php:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload">
<button type="submit" name="upload">Upload</button>
</form>
<div id=callbackEcho></div>
<script src="js/jquery.js"></script>
<script>
$("button").on("click",uploading);
function uploading(e)
{
e.preventDefault();
var postData=new FormData($("form")[0]);
$.ajax
(
{
type:'POST',
url:"post.php",
data:postData,
contentType:false,
processData:false,
success:function(data)
{
$("#callbackEcho").html('success : '+data);
},
fail:function(data)
{
$("#callbackEcho").html('fail : '+data);
},
done:function(data)
{
$("#callbackEcho").html('done : '+data);
}
}
);
}
</script>
</body>
</html>
and for testing only this is my post.php:
<?php
echo 'I\'m a callback!';
exit;

Change your ajax call to the following
$.ajax({
type:'POST',
url:"post.php",
data:postData,
contentType:false,
processData:false,
success:function(data) {
$("#callbackEcho").html('success : '+data);
},
error:function(data) {
$("#callbackEcho").html('fail : '+data);
},
complete: function(data) {
$("#callbackEcho").html('done : '+data);
}
});

Related

Can't upload multiple files with different extension?

Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>

AJAX File upload with PHP-CodeIgniter not working

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!");
}
});
});

autocomplete with suggestions AJAX PHP PostgreSQL

I'm doing a autocomplete but when I write anything in the Input me appear all elements, I want items that contain the typed characters in the Input.
My code is:
var searchRequest = null;
$("#buscar").autocomplete({
maxLength: 5,
source: function (request, response) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: 'search.php',
method: 'post',
dataType: "json",
success: function (data) {
searchRequest = null;
response($.map(data.items, function (item) {
return {
value: item.name1,
label: item.name1
};
}));
}
}).fail(function () {
searchRequest = null;
});
}
});
Try this:
source: function(request, response) {
response($.map(data.items, function(item) {
var term = request.term.toLowerCase(),
name = item.name.toLowerCase();
if (name.search(term) == 0 || item.code.indexOf(term.toUpperCase()) == 0) {
return {
label: item.name,
value: item.name
};
}
}).slice(0, 15)
);
},
try this code*
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function(request,response) {
$.ajax({
url: "results.php",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { value:item.name, district:item.district , id: item.id
};
}))
}
})
},focus: function (event, ui) {
$("#txthid").val(ui.item.id);
$("#txtid").val(ui.item.district);
elements.autocompleteSearch.val(ui.item.name);
return false;
},
messages: {noResults: "", results: ""}
});
})
</script>
</head>
<body>
<form id="form1" runat="server" >
<div class="demo">
<div class="ui-widget">
<label for="txtSearch">Enter UserName: </label>
<input type="search" id="txtSearch" />
<label for="txtid">ID is: </label>
<input type="id" id="txtid" />
</div>
</form>
<form action="file2.html" method="LINK">
<input type="hidden" id="txthid" name="id">
<input type="submit" value="Home page" >
</form>
</body>
</html>

jquery auto complete is not showing result

I am using jquery auto complete to get current data from database in php. But, I am not getting result.
Here is the code sample:
<label class="col-md-4">Referrer</label>
<div class="col-md-6">
<input type="text" name="referrer" id='referrer' placeholder="Type keyword..." autocomplete="off" value="" class="form-control" />
</div>
<script>
var path = $( "#referrer" ).data('path');
$("#referrer").autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/ir_populate_referrer",
dataType: "json",
type: "POST",
data: {
keyword: request.term,
path: path
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label
}
}));
}
})
}
});
</script>
As in my search.php file:
<?php
echo json_encode(array('label'=> $link, 'value' => $keyword));
?>
html
<html>
<head>
<title>test jquery autocomplete</title>
<script type="text/javascript" src="jquery/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#zipsearch").autocomplete({
source: function(req,res) {
$.ajax({
url: "json.php",
dataType: "json",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.label,
value: item.value
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
}
});
});
</script>
<link rel="stylesheet" href="jquery/css/smoothness/jquery-ui-1.8.2.custom.css" />
<style type="text/css">
</style>
</head>
<body>
<form onsubmit="return false;">
Ejemplo<br/>
Enter a Zipcode:
<input id="zipsearch" type="text" />
</form>
</body>
</html>
PHP
<?php
$response = array();
$response[0]=array('label'=>'test','value'=>'test');
$response[1]=array('label'=>'test2','value'=>'test2');
echo json_encode($response);
?>

Using jQuery's .get() to retrieve PHP data

I'm using jQuery's .ajax() to post to a PHP file called process.php. Process.php has a lot of code in it, but for simplicity's sake, let's just say it contains <?php echo 'hello'; ?>.
Is this the proper jQuery to insert process.php's results into div.results? :
$.get('process.php', function(data) {
$('.results').html(data);
});
So far it doesn't seem to be working.
Here's the HTML/Javascript file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#form").submit(function() {
var username = $('#username').attr('value');
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
return false;
});
});
</script>
</head>
<body id="body">
<form id="form" method="post">
<p>Your username: <input type="text" value="" name="username" id="username" /></p>
<input type="submit" id="submit" value="Submit" />
</form>
<div class="results"></div>
</body>
</html>
Here's process.php (greatly simplified):
<?php
/* get info from ajax post */
$username = htmlspecialchars(trim($_POST['username']));
echo $username;
?>
If you simply want to place the resulting string back into an element, use load().
$('.results').load('process.php');
However, looking at your code...
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
...shows you have misunderstood something. The correct anonymous function to assign to the success callback would be...
function(data) {
$('form#form').hide()
$('.results').html(data);
}
You could try something like this.
function ajax_login() {
if ($("#username").val()) {
$.post("/process.php", { username : $("#username").val() }, function(data) {
if (data.length) {
$("#login_form").hide();
$("#login_result").html(data);
}
})
} else {
$("#login_result").hide();
}
Then in process.php just echo out some text if the post sucesses.
process.php =>
if (isset($_POST['username'])
{
echo 'hello '.$_POST['username'];
}

Categories