I tried to send post value to OrderController (I use ZF2). I have javascript code in view folder.These are the code:
function submitHandler(form) {
var urls = '<?php echo $this->baseurl; ?>/order/saveOrder';
var pack= $("#pack").val(),
name= $("#name").val(),
instit= $("#instit").val(),
telp= $("#telp").val(),
email= $("#email").val(),
address= $("#address").val(),
orderno = "test",
order_stat ="phone",
pack_type = "recurring",
rec_period ="monthly";
$.ajax({
type: 'POST',
url: urls,
data: {
pack: pack,
name: name,
instit:instit,
telp: telp,
email: email,
address: address,
orderno : orderno,
order_stat :order_stat,
pack_type : pack_type,
rec_period :rec_period
},
success: function(msg) {
var result = JSON.parse(msg);
if (result.success) {
alert("SUccESSSS");
} else {
alert(result.msg);
}
},
error: function(xhr, status, error){
alert("Failed");
}
});
}
And these are code from controller:
public function saveOrderAction() {
$post = $this->getRequest()->getPost();
$response = $this->getResponse();
/*
$storage = Order\Storage::factory($this->getDb());
$attd = new Order($storage);
$success = false;
$msg = '';
$attd->orderno = $post['orderno'];
$attd->order_stat = $post['order_stat'];
$attd->pack = $post['pack'];
$attd->pack_type = $post['pack_type'];
$attd->rec_period = $post['rec_period'];
$attd->name = $post['name'];
$attd->instit = $post['instit'];
$attd->telp = $post['telp'];
$attd->email = $post['email'];
$attd->address = $post['address'];
//$save = $attd->saveOrder();
if ($attd->saveOrder(true)) { */
$success = true;
$msg = 'Saved Success';
echo "<script type='text/javascript'>alert($msg);</script>";
print_r('test');
printf('test2');
$response->setContent(json_encode(array("success" => $success, "msg" => $msg)));
return $response;
}
But it doesn't show anything. So I have commented and just want to show alert, but it doesn't show. Help me,thanks.
Probably you need to change your URL to:
var urls = '<?php echo $this->baseurl; ?>/order/save-order';
URL's in zend are lowercase. Multiple words are seperated by dashes. When the request is processed the action is camelCased so your action methods are proper PSR-2.
Related
I'm having trouble figuring out the best approach to checking if a record exists while using an ajax. If the CNIC exists, I want to alert, "user already exists". If it doesn't exist, I want it to insert the form data into the database. I've got the jquery function that only submits data using ajax but I want to validate CNIC if it exists it gives an alert message. Any help would be appreciated. Thanks in advance.
**
jquery
**
$(document).ready(function() {
$("#save1").on('click', function(e) {
var cnic = $("#cnic").val();
if (cnic == '') {
alert("Kindly Enter CNIC");
return false;
}
var gender = $("#gender").val();
if (gender == '') {
alert("Kindly Enter Gender");
return false;
}
var contactno = $("#contactno").val();
if (contactno == '') {
alert("Kindly Enter Contact No");
return false;
}
var fname = $("#fname").val();
if (fname == '') {
alert("Kindly Enter Contact No");
return false;
}else{
$.ajax({
url: "/save",
type: "get",
data: $('#registrationform').serialize(),
dataType: 'json',
success: function(data) {
$("#patientid").val(data.patientid);
// console.log(data);
}
})
}
});
});
**
controller
**
<?php
namespace App\Http\Controllers;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;
class Helpercontroller extends Controller
{
function save(Request $request)
{
$temppatientId = IdGenerator::generate(['table' => 'patients', 'length' => 5, 'prefix' =>
'22']);
$patientid = $temppatientId + 1;
$query = new patient;
$query->patientid = $patientid;
$query->fname = $fname;
$query->lname = $lname;
$query->cnic = $cnic;
$query->contactno = $contactno;
$query->gender = $gender;
$query->age = $age;
$query->dob = $dob;
$query->city = $city;
$query->address = $address;
$query->husbandname = $husbandname;
$query->fathername = $fathername;
$query->bloodgroup = $bloodgroup;
$query->maritalstatus = $maritalstatus;
$query->save();
return $query;
}
Quick way to do it is to use Validation from Laravel.
public function save(Request $request)
{
$validator = \Validator::make($request->all(), [
// I suppose your table name is 'patients'
'cnic' => 'required|unique:patients',
]);
if ($validator->fails()) {
// you can return a custom message if needed
return response()->json(['success' => false, 'errors' => $validator->errors()->all()]);
}
// ... your actuel code to save data
return response()->json(['success' => true, 'patient' => $query]);
}
And in your Ajax call:
$.ajax({
url: "/save",
type: "get",
data: $('#registrationform').serialize(),
dataType: 'json',
success: function(data) {
if (data.success === false) {
alert('User already exist !');
} else {
$("#patientid").val(data.patient.patientid);
// console.log(data.patient);
}
}
})
Respect cases of variables and don't use a GET method to POST a resource.
I am using CodeIgniter, I have a three input field called as name, emp_id,crm_id. I am entering the id value and sending to the controller to get all the information related to that id using AJAX an JSON. Now the issue is, I am getting the correct output in the network tab but not able to display in the view page even alert is also not displaying in the JSON.
Sometimes I am getting below error because of JSON is empty
[Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I think there is some issue with JSON.
Ajax
$("form[name='search_addSalaryrecord']").validate({
// errorElement: 'div',
submitHandler: function(form) {
//alert(baseUrl);
var employee_name = $('#employee_name').val();
var crm_id = $('#crm_id').val();
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id},
success: function(response) {
//$('.search_record tbody').html(response);
// var data = JSON.parse(response);
//alert(data.status);
if (response.status === 'error')
{
alert(response.msg);
}
if (response.status === 'success') {
//alert('data avaliable');
alert(response.records);
console.log(response.records);
}
}
//error: function(error) { console.log(error); }
});
}
});
Controller
public function search_addSalaryrecord()
{
$employee_name=trim($this->input->post('employee_name'));
$emp_crmid=trim($this->input->post('crm_id'));
$employee_id=trim($this->input->post('employee_id'));
if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id);
if (!empty($arr_result)){
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
"employee_id" => $row->employee_id,
"month_year" => $row->month.' '.$row->year
);
}
//print_r($result);
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($arr_result);
exit;
}
Hope this will help you :
Use dataType: "json" in your ajax to avoid further parsing of response and return json_encode data with exit from your controller
Your ajax should be like this :
$("form[name='search_record']").validate({
submitHandler: function(form)
{
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_id:employee_id},
success: function(response) {
//alert(data.status);
if (response.status == 'error')
{
alert(response.msg);
$('.personel_info').empty();
}
if (response.status == 'success')
{
alert(response.records);
$('.personel_info').empty();
$('.personel_info').show();
var trHTML = '';
$.each(data.records, function (i, o){
$('#name_emp').text(o.name);
$('#mobileno_emp').text(o.mobileno);
$('#employee_email').text(o.employee_email);
});
}
}
});
}
});
Your controller's method search_addSalaryrecord should be like this :
public function search_addSalaryrecord()
{
$employee_id = trim($this->input->post('employee_id'));
if(!empty($employee_id))
{
$arr_result = $this->Employee_model->get_salary_search_emp_id($employee_id);
if (! empty($arr_result))
{
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
);
}
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($respnonse);
exit;
}
I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}
I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?
I am making a single registration form with all the data and input tags I need and pass that data to the next page via AJAX. But I do not get my image upload value to the next page. Please help me find a solution regarding ajaxfileupload.js and validation.js and tell me how to store image in a database using codeigniter.
<script src="<?php echo JS_PATH;?>jquery-validation.js"></script>
javascript:
$(document).ready(function() {
$("#registration_form").validate({
rules: {
name: {
required: true
},
surname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
messages: {
name: {
required: "Please enter your name"
},
surname: "Please enter your surname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
}
},
submitHandler: submitForm
});
function submitForm() {
var name = $('#name').val();
var surname = $('#surname').val();
var age = $('#age').val();
var dob = $('#datepicker').val();
var ph_no = $('#ph_no').val();
var gender = $('input[type="radio"]:checked').val();
var hobbies = new Array();
$('input[name="hobbies[]"]:checked').each(function() {
hobbies.push(this.value);
});
var city = $('#city').val();
var email = $('#email').val();
var pwd = $('#password').val();
var photo = $("#userfile").val();
$.ajax({
url: "<?php echo SITE_ROOT;?>Registration/insertdata",
type: "POST",
data: {
username: name,
user_surname: surname,
user_email: email,
password: pwd,
user_age: age,
user_dob: dob,
user_ph_no: ph_no,
user_gender: gender,
user_hobbies: hobbies,
user_city: city,
user_photo: photo
},
success: function(data) {
alert(data);
}
}
});
}
html:
<form method="post" enctype = "multipart/form-data" >
<label> File Input: </label>
<input type="file" name="userfile" id="userfile">
<input type="submit" name="submit" value="Submit" />
</form>
php controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Registration extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('menupages/registration_model');
}
public function index() {
$this->first();
}
function first() {
$data['title'] = "Registration Page";
$this->load->view('menupages/registration', $data);
}
function insertdata() {
$file = $_POST['user_photo'];
print_r($file);
exit();
$config['upload_path'] = '/var/www/html/upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['file_name'] = $file;
$this->load->library('upload'); //initialize
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
exit();
} else {
$data = array('upload_data' => $this->upload->data());
print_r($data);
exit();
}
}
}
First of all , there are many things that are not okay with your current code inside php codeginiter 's controller, let's first see a difference between $_POST vs $_FILES
$_POST contains all the data from forms (except files)
$_FILES contains all files sent to server via forms (only from <input type="file" />)
What you are doing is , you are using $_POST['user_photo'] to fetch the file details , which is not okay to fetch the file information for uploading it. And also another thing is :
$this->upload->do_upload('userfile');
You are wrong here. the parameter userfile does not even exist in your http request. While sending the data to the server , you have replaced the userfile with user_photo , so what you have to here is also you have to change these two things
$_POST['user_photo'];
$this->upload->do_upload('userfile');
to
$_FILES['user_photo'];
$this->upload->do_upload('user_photo');
change your :
$('#userfile').val();
to
$("#userfile").prop("files")[0];
and add these parameters into javascript parameters along with url , data and etc..
contentType: false,
processData: false,
cache: false,
change your submitForm function to this:
function submitForm() {
var name = $('#name').val();
var surname = $('#surname').val();
var age = $('#age').val();
var dob = $('#datepicker').val();
var ph_no = $('#ph_no').val();
var gender = $('input[type="radio"]:checked').val();
var hobbies = new Array();
$('input[name="hobbies[]"]:checked').each(function() {
hobbies.push(this.value);
});
var city = $('#city').val();
var email = $('#email').val();
var pwd = $('#password').val();
var photo = $("#userfile").prop("files")[0];
var form_data = new FormData();
form_data.append("user_photo", photo);
form_data.append("username",name);
form_data.append("user_surname",surname);
form_data.append("password",pwd);
form_data.append("user_age",age);
form_data.append("user_dob",dob);
form_data.append("user_ph_no",ph_no);
form_data.append("user_gender",gender);
form_data.append("user_hobbies",hobbies);
form_data.append("user_city",city);
$.ajax({
url: "<?php echo SITE_ROOT;?>Registration/insertdata",
type: "POST",
data: form_data,
success: function(data) {
alert(data);
}
}
});
}
Make use of FormData() on javascript.
data = new FormData();
data.append('name', $('#name').val());
data.append('surname', $('#surname').val());
data.append('age', $('#age').val());
data.append('dob', $('#datepicker').val());
data.append('ph_no', $('#ph_no').val());
data.append('gender', $('input[type="radio"]:checked').val());
//for Photo
data.append('photo', $('#userfile')[0].files[0]);
//AJAX
$.ajax({
url: "<?php echo SITE_ROOT;?>Registration/insertdata",
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data)
}
});
PHP CODE:
To test if you successfully passed file and post data on php:
print_r($_FILES);
print_r($_POST);
You can submit the form and send it by form.serialize in JQuery. It will send data with picture by Ajax.