Reading response text in Ajax using JQuery - javascript

function upload_file(){
var file =document.getElementById('computer_image').files[0];
if(file!==null){
if(file.type==='image/jpeg' ||
file.type==='image/png' ||file.type==='image/jpg'){
$('#progressbar').show();
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'file_upload/ImageUpload',
type: 'POST',
headers: {"abc": "aaaaaaaaa"},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandler, false);
}
return myXhr;
},
success: function( request,data, textstatus){
alert(textstatus.getResponseHeader('abc'));
},
error:errorHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
}
else {
alert('sorry we are not accepting file other than PNG , JPEG and JPG');
}
}
}
I am using CodeIgniter Framework .Below is my PHP code to Process a file .
function ImageUpload(){
$status="";
if (empty($_FILES["file1"]))
{
$status = "sorry Something went wrong";
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
if ($status !== "sorry Something went wrong")
{
//call a function to get path name
$path="./upload";
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size' ] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['remove_spaces']=TRUE;
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
/* If directory doesn't exist than create a new .*/
if (!file_exists($path) && !is_dir($path)) {
mkdir($path);
}
/* If there is any error during upload */
if ( ! $this->upload->do_upload('file1')){
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
/*Image has been successfully Uploaded */
else{
$var = $this->upload->data('','');
echo $path.'/'.$var["file_name"].'='.$var["image_width"].
'='.$var["image_height"];
}
}
I have tried multiple flavor to get Response text but didn't success . What should be after complete to read response text .
getting null as output .

In $.ajax()'s success method first parameter will give response
Example:
$.ajax({
success: function(response, textStatus, jqXHR ){
console.log(response);
alert(response.getResponseHeader('abc'));
},
});
Check this link. It will be useful to understand $.ajax() more clearly.

Related

if use ajax call for contact form submitting, header(location:/path) not working

The issue is if try to ajax call for submitting my contact form. then header("location: /path); starts not working.
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
// header("location: /contact/thankyou.html");
}
} else {
echo "Invalid captcha! Please enter again. ";
}
And yes, because header redirect is not working. I comment it out. And tried to redirect page inside ajax call like below.
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function(){
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data){
response.html(data).fadeIn();
window.location.href ="/contact/thankyou.html";
},
error: function(e){
console.log(e)
}
});
});
});
But this time, it's only redirecting inside the .status div! like in the image Normally I am displaying a error message in that div...
Hey This is wrong practice if you are using ajax req then php not able to redirect to your destination all you need to redirect in ajax success response simple us
$data = array();
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
$data['status'] = 1; // for true
$data['message'] = "your success message"; // for true
}
}
else {
$data['status'] = 0; // for false
$data['message'] = "your error message"; // for false
}
//define content type json if you never echo like echo 'ss' then no need to this
header('Content-Type: application/json');
echo json_encode($data);exit;
and get response in ajax request dataType Json to access json array obj
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'json',
data: form.serialize(),
beforeSend: function() {
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data) {
if (data.status == 1) {
response.html(data.message).fadeIn();
window.location.href = "/contact/thankyou.html";
}
else{
// for error
response.html(data.message).fadeIn();
}
},
error: function(e) {
console.log(e)
}
});
});
});
You have to send header as Base64 string then decode it in the service / Backend.

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.
You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

Php Upload File With JavaScript

I Try to upload with javascript I send ajax but I can't find problem my code not work where is problem ?
index.php
<input type="file" id="photoUploadFile"/>
script js
var full_photo_name = document.getElementById('photoUploadFile').value;
var photo_name = full_photo_name.substr(full_photo_name.lastIndexOf("\\")+1, full_photo_name.length);
$.ajax({
type: "POST",
url: "register_photo.php",
data: { photo_name : photo_name },
success: function(data) {
}
});
register_photo.php
upload_photo($_POST['photo_name']); // i upload with this function but show me error: Sorry!
function upload_photo($file_name) {
global $Root_Directory;
$target_dir = $Root_Directory. 'uploads/';
$target_file = $target_dir. $file_name;
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($file_name, $target_file)) {
echo 'File: '. $file_name. ' has been uploaded.';
} else {
echo 'Sorry !';
}
}
}
change your ajax like this
var formdata = new FormData();
formdata.append( 'file', input.files[0] );
$.ajax({
url: 'register_photo.php',
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
In register_photo.php Use move_uploaded_file to save
In your ajax request you can use something like this.
var file_data = $('#photoUploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file_name', file_data);
$.ajax({
url: "register_photo.php",
cache: false,
data: form_data,
type: 'post',
success: function(result){
alert(result);
}
});
In your PHP code
upload_photo($_FILES['file_name']); // i upload with this function but show me error: Sorry!
function upload_photo($file_name) {
global $Root_Directory;
$target_dir = $Root_Directory. 'uploads/';
$target_file = $target_dir. $file_name;
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($file_name['tmp_name'], $target_file)) {
echo 'File: '. $file_name. ' has been uploaded.';
} else {
echo 'Sorry !';
}
}
}
The best way to send the file is to submit it using a form and then receiving it on server and then processing it with php or what ever language you are using.
You have to understand that the client and the server are two different entities and sending the file name in ajax will not help.
put the input element in form.
<form id="frmsendfile" method="post" target="fileprocess.php">
<input type="file" id="photoUploadFile"/>
</form>
Now we write a javascript function that will submit the form to your server after you have browsed the file. you can add validation. I am just going to give you an idea how you can do this.
<script type="text/javascript">
var submitFile = function(){
var frm = document.forms[0];
if(frm)
{
frm.submit();
}
};
you need to call submitFile() function to send the file.

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

How to show alert when error comes from the PHP as response to ajax request in following case?

The jQuery AJAX function is as follows :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
The PHP code is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg;
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data = $objUserLogin->GetResponse();
echo json_encode($data);
die;
}
break;
Now I'm able to print the success when the response comes without any error but what about showing the alert message when some error happens. How to achieve it? What change needs to make to the above code? Please help me.
Use below condition in success:
success: function(result, success) {
if($.inArray( "error_message", result)) {
alert("Error message");
} else {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
}
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case echo "error";
and on ajax page check for result if its value is error then do what else u want
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}

Categories

Resources