PHP is not recieving JSON data from jQuery - php

I am trying to use ajaxFIleUpload in my website. I am not recieving JSON data send by JavaScript to PHP. I am stuck at this point. File Uploading is ok but i am not able to recieve any post values. My jQuery function is
$(function() {
$(document).on("submit", "#upload_file", function(e) {
e.preventDefault();
$.ajaxFileUpload({
url :base_url + 'payments/uploadPaymentSlip/',
secureuri :false,
fileElementId :'userfile',
type : 'POST',
data: { paymentFormInputAmount: 'asdasd' },
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
//refresh_files();
$('#files').val('');
}
alert(data.msg);
},
dataType: 'json'
});
});
});
My PHP Function is
function uploadPaymentSlip() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
$status = "error";
// checking whether json value shows in php or not
// $_POST['paymentFormInputAmount'] is also not working
$msg = $_POST['paymentFormInputAmount'];
if ($status != "error") {
$config['upload_path'] = realpath( APPPATH . '../uploads/paymentSlip' );
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name)) {
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else {
$data = $this->upload->data();
// $file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
if($file_id) {
$status = "success";
$msg = "File successfully uploaded";
}
else {
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}

type: 'json' must be type: 'POST'
and you should add:
contentType: 'json',
dataType: 'json'
as parameter to $.ajaxFileUpload
contentType means you are sending your data as json.
dataType means you are expecting result as type of json.

Related

How to upload image in codeigniter using ajax with server validation

I have a form which data is inserting into data base through ajax. Along with when input fields has error then showing error under neath to the every fields.
But when i select the image and trying to upload the name of image into database, then nothing goes on, neither image uploading to the upload path nor inserting the name of the image into database.
In Case of image upload error i can not even display image upload error.
Controller:-
In my Controller as you can see that i have an array named result which has two keys status and message and default status is false.
In the else part a loop is running which has only form error not any type of image error may be this is reason for not showing any error for image.
No Problem if error is not showing But at least file name should be inserting.
function infoValidation() {
$result = array('status' => false, 'message' => array());
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
$config['upload_path'] = 'assets/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
//$result['message'] = $this->upload->display_errors();
//$result['status'] = false;
}
else
{
$image_name = '';
}
$data = array(
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'pincode' => $this->input->post('pincode'),
'state' => $this->input->post('state'),
'landmark' => $this->input->post('landmark'),
'address' => $this->input->post('address'),
'state' => $this->input->post('state'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
}else {
foreach ($_POST as $key => $value) {
$result['message'][$key] = form_error($key);
}
}
echo json_encode($result);
}
Ajax:
$("#form").submit(function(e){
e.preventDefault();
var me = $(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
type : 'POST',
data : me.serialize(),
success: function(resp) {
console.log(resp);
if (resp.status == true) {
$('#myModal').modal('show');
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
}else {
$('#msg').html('<div class="alert alert-danger"><h5>Please Check Your Details</h5></div>');
$.each(resp.message, function(key, value) {
var element = $("#"+key);
element.closest('.form-group')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
if(element.parent('.input-group').length) {
element.parent().after(value);
} else {
element.after(value);
}
// element.after(value);
});
}
}
});
});
How can i Upload an image into database, If this is not the right way then please Suggest the right way for doing this
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.
View
<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">
<div>
username : <input type="text" name="name">
<span class="error name"></span>
</div>
<div>
password : <input type="text" name="password">
<span class="error password"></span>
</div>
<div>
file : <input type="file" name="image">
<span class="error image"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
Jquery 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'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
});
</script>
controller
function test_image() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run() == TRUE) {
if($_FILES['image']['error'] != 0) {
$result['status'] = false;
$result['message'] = array("image"=>"Select image to upload");
} else {
$config['upload_path'] = 'images';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
}
else
{
$image_name = '';
}
$data = array(
'name' => $this->input->post('name'),
'password' => $this->input->post('password'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
$result['message'] = "Data inserted successfully.";
}
}else {
$result['status'] = false;
// $result['message'] = validation_errors();
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Try this flow for upload image using ajax
Files cannot be uploaded with serialize() function, as it does not serialize files. Please try this approach:
var data = new FormData(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
contentType : false,
processData : false,
type : 'POST',
data : data,
success: function(resp) { ... etc.
try this codein view
$('#formElement').submit(function () {
var formData = new
FormData(document.getElementById("formElement"));
formData.append('image-file', $('#image-file')[0].files[0]);
$.ajax({
url: "<?php echo base_url('home/add')?>",
data: formData,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function() {
$('.loder_img').show();
},
success: function ( data ) {
$('.loder_img').hide();
var val = JSON.parse(data);
//you can apply alerts or anything to show validation on
view and in val all mesg of validation yon can see here in console.
console.log(val);
},
error: function (request, status, error) {
$('.loder_img').hide();
alert(request.responseText);
}
});
});
and in your controller
public function addPackage()
{
$this->load->library("form_validation");
//left side form
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');
$this->form_validation->set_rules('txt_store', 'Store', 'required|trim');
//upto so on according to your values
if( $this->form_validation->run() == false){
$error = array(
"check_1" => form_error('check_1'),
"txt_desc" => form_error('txt_desc'),
"txt_store" => form_error('txt_store'),
"txt_couple_name" => form_error('txt_couple_name'),
"txt_couple_case" => form_error('txt_couple_case'),
"txt_phone" => form_error('txt_phone'),
"txt_date" => form_error('txt_date'),
"txt_location" => form_error('txt_location'),
"txt_address" => form_error('txt_address'),
"txt_email" => form_error('txt_email'),
);
$msg = array('status' => 'invalid', 'msg'
=>$error,'allerror'=>validation_errors());
echo json_encode($msg);
}else{
//insert it into database all file and values
if($_FILES["image-file"]["size"] != 0){
$path= './uploads/image';
$img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");
}
$data = array(
"basket" => $this->filter($this->input->post("check_1",true))........
);
//your insert query
}
}
and in your model to upload image and it will return the uploaded image if it is not upload hen it will return false or you can print the display errors and dont forget to change the path of storing image
model code
public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)
{
$config['upload_path'] = $upload_path;
$config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);
$config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";
$config['overwrite'] = FALSE;
$config['max_size'] = '0';
$config['max_width'] = $max_width;
$config['max_height'] = $max_height;
$config['min_width'] = $min_width;
$config['min_height'] = $min_height;
$config['max_filename'] = '0';
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename))
{
/*$data['upload_data']['file_name'] = '';
$msg = $this->upload->display_errors('');
$this->session->set_flashdata('msg',$msg);
$url = $_SERVER['HTTP_REFERER'];
redirect($url); */
return false;
//return $error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
return $data['upload_data']['file_name'];
}
unset($config);
$this->image_lib->clear();
}
Jquery serialize() method not able to post file data.
Please used jquery plugin for post file data using ajax. which are given below.
dmuploader.js
dmuploader.min.js
for simple example click here

AJAX not receiving PHP response

My ajax request puts files into the directory.
However I receive no response from the PHP file.
I'm using alerts to determine if a response has been received.
Any help would be greatly appreciated.
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
exit('unable to upload'); // Prints success and exit the script
} else {
exit($file); // Prints success and exit the script
}
?>
UPDATE:
I success and error to ajax and it comes up as an error.:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
}
Use json_encode to send data back with AJAX.
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
echo json_encode(['filename' => false]);
exit(); // Prints success and exit the script
} else {
echo json_encode(['filename' => $file]);
exit();
}
?>
In your AJAX do this
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
}else {
alert('unable to upload');
}
},
error: function(){
alert('failure');
}
});
}
You can also use $.post() which is a shorthand for $.ajax() for POST request.
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.post('test.php', {data: canvasData}, function (response) {
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
} else {
alert('unable to upload');
}
})
}
You need to replace all spaces with plus sign (+).
Your code with a fix:
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$img = str_replace(' ', '+', $img); // Here is a fix
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
exit('unable to upload'); // Prints success and exit the script
} else {
exit($file); // Prints success and exit the script
}
?>

Cannot get data from json_encode in jQuery AJAX with php

I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}

CodeIgniter + jQuery Ajax runs error but successfully callback is called

My Codeigniter: (Do you think there is an error?)
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
My jQuery Code: (Do you think there is an error?)
$(".submit").on("click", function(){
var kuladi = $("#kullaniciadi").val();
var email = $("#email").val();
var sifre = $("#sifre").val();
var confirm = $("#sifreonay").val();
var hata = $("#hata").val();
var checkbox = $("#checkbox").is(":checked");
var link = "http://tantunisiparis:8080/main/anasayfa/KayitOl";
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
if (!kuladi || !email || !sifre) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Boş bırakılan alanlar var!");
}
else if (!pattern.test(email)) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Lütfen geçerli bir e-mail giriniz!");
}
else if (!checkbox) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Kullanıcı Sözleşmesini Kabul Etmediniz.");
}
else if (sifre != confirm) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Şifreler eşleşmiyor!");
}
else{
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
console.log(data.status);
alert("Success döndü");
},
error: function (data){
console.log(data.status);
alert("Error döndü");
}
});
}
});
Why I am having a problem like this?
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
You need to set HTTP status code. So in case of error call this code in the controller $this->output->set_status_header(500);.
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
$this->output->set_status_header(500); // or any other code
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
You can read more about output class in the docs http://www.codeigniter.com/userguide3/libraries/output.html
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
if(data.status == 'success'){
console.log(data.status);
alert("Success döndü");
}
if(data.status == 'error'){
console.log(data.status);
alert("Error döndü");
}
}
});
I thing, This code will work for you...

$.ajax datatype:json throws error

I'm trying to retrieve a json object through a ajax request from a php file. My ajax request looks like the following:
function validateForm() {
var name = $('#usernameLogIn').val();
var password = $('#passwordLogIn').val();
$.ajax({
type: 'GET',
url: '../webroot/login/validateForm/',
data: {name: name, password: password},
dataType: 'json',
success: function(result) {
var data = JSON.stringify(result);
var b = $.parseJSON(data);
alert(b);
},
error: function(a,b,c) { console.log(a,b,c); }
});
}
and my php file looks like this:
$form = $this->form;
$status = false;
$name = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['name']);
$formPassword = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['password']);
$now = date(DATE_RFC2822);
$user = $this->user->findName($name);
if(isset($user->name))
{
$password = $user->password;
$status = password_verify($formPassword, $password);
}
if ($status === true)
{
$this->session->set('loggedIn', $this->user->name);
}
else if ($status === false) {
$this->session->clearSession('loggedIn');
}
$sessionLog = $this->session->get('loggedIn');
$advert = array(
'session' => $sessionLog,
'name' => $name,
'password' => $formPassword,
);
echo json_encode($advert);
exit;
Finally when it passes the values back to my Ajax request it goes straight into the error function and prints the following into the console:
Object "parsererror" SyntaxError
message: Unexpected Token <"
Is it any way to tell where this goes wrong and why?
thankfull for answers, cheers.
I think you have verbose set to true in you config file.

Categories