M having problem with getting resposnse from the server.M using Jquery Ajax
I want to upload a file using ajax.But the follwing lines of codes are not working
page1:
<script language="javascript" src="jquery-1.7.1.js"/></script>
<script language="javascript" src="jquery.form.js"/></script>
<script language="javascript">
$(document).ready(function(){
$('#photoimg').change(function(){
var fd=new FormData();
$.ajax({
type:'POST',
url:'NewuploadScript.php',
data:fd,
contentType: 'application/x-www-form-urlencoded',
async:true,
cache:false,
processData: true,
success:function Result(data2) {
document.write(data2);
}
});
});
});
</script>
<form>
<input type="file" id="photoimg" name="file" multiple>
<input type="submit" id="BtnSbmt" value="Upload"/>
</form>
Pag2:
<?php
echo $name= basename($_FILES['photoimg']['name']);
echo $size= basename($_FILES['photoimg']['size']);
?>
when I run the codes jquery display the following error:
Uncaught TypeError: Illegal invocation
jQuery.extend.param.addjquery-1.7.1.js:7601
buildParamsjquery-1.7.1.js:7658
jQuery.extend.paramjquery-1.7.1.js:7621
jQuery.extend.ajaxjquery-1.7.1.js:7467
(anonymous function)ImageUploader.php:18
jQuery.event.dispatchjquery-1.7.1.js:3256
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2875
It's hard to tell what the error message means exactly without seeing what comes back in your Ajax exchange. Your PHP code should not read
echo $var_name = ...
because that is an assignment. Try the following...
<?php
echo basename($_FILES['photoimg']['name']);
echo basename($_FILES['photoimg']['size']);
?>
Or just
print_r($_FILES);
for starters edit :
success:function (data2) {
document.write(data2);
}
Maybe the problem is related with FormData see this
Related
For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});
I have a simply AJAX call as a part of an image upload form. The page calls a PHP form which is supposed to then process the file upload and return a "successful" comment to the same page.
Currently, the script is working perfectly but when it returns the AJAX success string, it takes you to a new page and shows the AJAX output rather than showing it within the DIV on the same page.
To make it simpler, I've just cut out all of the PHP upload script and changed it to a simple echo output script - so I think it's a problem with the submit form page rather than the page that's called. I have jQuery included in the submission page.
Here's the submit form:
<div id="uploadFormLayer">
<form id="uploadForm" action="../uploadtesties.sparkle" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Upload">
<input type="hidden" name="EID" value="<? echo $ElectionID; ?>">
</form>
</div>
<div id="targetLayer"></div>
Here's the AJAX request:
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploadtesties.sparkle",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
The PHP page just says <?php echo "Testing output"; ?> for the moment.
I'm attempting to call a PHP file from Jquery. My website shows "hi" once my button is clicked so I know the click() function is being called but I don't get a response from my test.php file. Furthermore, my php file loads without error when called independent from this script.
<html>
<head>
<script language="JavaScript" type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submitButton').click(function(){
//var theName = $( "#name" ).val();
//var theID = $( "#transaction" ).val();
alert("hi");
$.ajax({
url: "test.php?name=Charlie&transID=1234",
type:'get',
success: function(data){
alert(data);
}
});
}
)
});
</script>
</head>
<body>
<form action="" method="POST">
<input id="name" type="text" size="20" placeholder="Enter Your Name">
<input id="transaction" type="hidden" name="transactionID" value="12345">
<input id="submitButton" type="submit" name="submit" value="Call PHP">
</form>
</body>
</html>
PHP:
<?php
$name=$_GET['name'];
$id=$_GET['transID'];
echo("Thank you $name for transaction #:$id");
?>
Thanks,
Craig
It's possible that the ajax call to test.php page isn't working right. Change your ajax call code to:
$.ajax({
url: "test.php?name=Charlie&transID=1234",
type:'get',
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Status:' + textStatus + '\r\n\r\n' + errorThrown);
}
});
This will show any errors occurring during the ajax call.
The solution was to turn off my password protected directory on my webserver which hosted these files in order to successfully call the php file using jquery. With the password protected directory turned on the jquery threw a Error 401 which I was able to catch by viewing the Network tab within Chrome. Still unsure why I was able to provide username/password once and continually access the files via my browser while my script was denied access during the same session.
I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks
It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().
I do not understand, and google does not give me the answer. I want to upload a file and the results show in the div without page relode, but I can not get it!!!!
html:
<form method="post" action="process/pic2.php" enctype="multipart/form-data" id="userpic">
<p>Izvēlies bildi: <input type="file" name="img_to_upload" /><input type="submit" name="upload" value="Augšupielādēt" /></p>
</form>
jquery:
jQuery(function(){
jQuery('#userpic').submit(function(){
jQuery.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jQuery('#userpic').attr('action'),
data: jQuery('#userpic').serialize(),
success: function(data){
if(data){
jQuery('#picinfo').html(data);
}else{
jQuery('#uerpic').fadeOut(500);
jQuery('#picinfo').html('<center><img src="img/loader.gif" /></center>');
window.location = 'index.php';
}
}
});
return false;
});
});
and my php:
if(isset($_FILES['img_to_upload']['name']) && !empty($_FILES['img_to_upload']['name'])){
echo 'Done!';
}else{
echo 'Error!';
}
all the time showing the "error" text..
P.S. Sorry for bad English.
Normally, to do a form-submission, and stay on the same page, you'll have to prevent the default form action with Javascript, something like this:
$("#userpic").submit(function(event) {
event.preventDefault();
...
});
But, uploading an image via Ajax is pretty tricky--see:
uploading files with jquery $.ajax and php