ajax passing two forms with codeigniter - javascript

I have a problem related with passing two forms in ajax to my controller code igniter. My first form is a file var formData = new FormData($('#form-upload')[0]);
and my second form consists of profile data $('#frm_patientreg').serialize()
now my problem is how can I pass these two forms in ajax?
I already tried this code:
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: $('#frm_patientreg').serialize()+formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
but it returns me an error.
When I tried to pass data:formData, only, my image file was successfully uploaded, but when I add the $('#frm_patientreg').serialize(), it outputs an error. How can I pass both forms?
Here is my controller:
public function addpatient() {
$config['upload_path'] = './asset/uploaded_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
$upload_data = $this->upload->data();
$file_name = base_url().'asset/uploaded_images/'.$upload_data['file_name'];
$mypatiendid = $this->genpatient_id();
$patient_bday = $this->input->post('pabdate');
$DB_date = date('Y-m-d', strtotime($patient_bday));
$patient_height = $this->input->post('paheight');
$DB_height = $patient_height . " cm";
$patient_weight = $this->input->post('paweight');
$DB_weight = $patient_weight . " kg";
$data = array (
'patient_id' => $mypatiendid,
'patient_fname' => $this->input->post('pafname'),
'patient_mname' => $this->input->post('pamname'),
'patient_lname' => $this->input->post('palname'),
'patient_address' => $this->input->post('paaddress'),
'patient_contact_info' => $this->input->post('pacontact'),
'patient_bday' => $DB_date,
'patient_age' => $this->input->post('paage'),
'patient_height' => $DB_height,
'patient_weight' => $DB_weight,
'patient_sex' => $this->input->post('psex'),
'patient_civil_status' => $this->input->post('pmartialstat'),
'patient_photo' => $file_name,
);
var_dump($data);
}
else {
echo "File cannot be uploaded";
$error = array('error' => $this->upload->display_errors()); var_dump($error);
}
}

Not tested..but try this:
var FormTwo = new FormData();
$('#frm_patientreg input, #frm_patientreg select').each(function(index){
FormTwo.append($(this).attr('name'),$(this).val());
});
FormTwo.append('file', $('#frm_patientreg input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: {formTwo: FormTwo, formOne: formData},
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});

change this
data: $('#frm_patientreg').serialize()+formData,
into this
data: $('#frm_patientreg').serialize()+'&'+formData,

Related

AJAX post receive strange text response

I have 2 inputs mkey and url.
I'd like to change key when url changed by the following code:
const url = document.getElementById('url');
url.addEventListener('input', (event) => {
let url = event.target;
let mkey = document.getElementById('mkey');
$.post({
url: "{{ route('contracts.regenerate') }}",
data: {
mkey: mkey.value,
url: url.value,
},
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: (data) => {
alert(data);
let mkey = document.getElementById('mkey');
mkey.value = data;
}
});
});
Laval route with name contracts.regenerate:
public function regenerateKey(Request $request) {
$parts = explode('#', $request->mkey);
$last = printf("%u", crc32($request->url));
return $parts[0] . '#' . $last;
}
The idea is to construct mkey as original-mkey-before-hash#crc-from-url.
Laravel back returns what I expect.
Example:
mkey.value = mkey_60501e2ae282a2.08095650
url.value = http://example.com
Laravel route returns string mkey_60501e2ae282a2.08095650#123 (123 - sample).
That's right.
But alert() show me returned value 2797586643mkey_60501e2ae282a2.08095650#123.
Digits 2797586643 before mkey are unexpected.
How to avoid these digits in response?
Use JSON for safe data transfers between back and frontend.
Change your controller\action to this:
public function regenerateKey(Request $request) {
$parts = explode('#', $request->mkey);
$last = printf("%u", crc32($request->url));
return response()->json([
"mkey" => $parts[0] . '#' . $last
]);
}
also change your Js to:
$.post({
url: "{{ route('contracts.regenerate') }}",
data: {
mkey: mkey.value,
url: url.value,
},
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json',
success: (data) => {
alert(data.mkey);
let mkey = document.getElementById('mkey');
mkey.value = data.mkey;
}
});
Problem was in usage of printf instead of required sprintf.

my data not update in the database in laravel 5.4

I am using laravel 5.4 in my app I update some record through ajax jquery I get the data from form values through ajax function and append it in array and pass that array (formData in my code) to ajax data then when I request my data in controller it updated as null message in my database.
This is my view jquery function
$('#updateProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var video = document.getElementById('videoToUpload').files[0];
// console.log(video);
var formData = new FormData();
formData.append('_method', 'patch');
formData.append('name', $(this).find("[name='name']").val());
formData.append('description', $(this).find("[name='description']").val());
formData.append('brand', $(this).find("[name='brand']").val());
formData.append('category', $(this).find("[name='category']").val());
formData.append('condition', $(this).find("[name='condition']").val());
formData.append('shipper', $(this).find("[name='shipper']").val());
formData.append('shipping_from', $(this).find("[name='shipping_from']").val());
formData.append('shipping_paid_by', $(this).find("[name='shipping_paid_by']").val());
formData.append('shipping_within', $(this).find("[name='shipping_within']").val());
formData.append('shipping_weight', $(this).find("[name='shipping_weight']").val());
formData.append('shipping_fee', $(this).find("[name='shipping_fee']").val());
formData.append('seller_get', $(this).find("[name='seller_get']").val());
formData.append('price_per_unit', $(this).find("[name='price_per_unit']").val());
formData.append('selling_fee', $(this).find("[name='selling_fee']").val());
formData.append('seller_id', $(this).find("[name='seller_id']").val());
formData.append('is_active', $(this).find("[name='is_active']:checked").val());
console.log(formData);
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert("Products updated successfullly");
console.log(data);
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
In my controller
public function update(Request $request, $id)
{
return Response::json([
'message' => $request['name']
], 200);
if(!$request){
return Response::json([
'error' => [
'message' => 'Kindly provide all the required details'
]
], 422);
}
$product = Product::find($id);
$product->name = $request['name'];
$product->sku = $request['sku'];
$product->slug = $request['slug'];
$product->description = $request['description'];
$product->brand = $request['brand'];
$product->condition = $request['condition'];
$product->shipper = $request['shipper'];
$product->shipping_from = $request['shipping_from'];
$product->shipping_fee = $request['shipping_fee'];
$product->shipping_paid_by = $request['shipping_paid_by'];
$product->shipping_within = $request['shipping_within'];
$product->shipping_weight = $request['shipping_weight'];
$product->selling_fee = $request['selling_fee'];
$product->seller_get = $request['seller_get'];
$product->price_per_unit = $request['price_per_unit'];
///$product->seller_id = $request['seller_id'];
$product->is_active = $request['is_active'];
$product->save();
$category = ProductCategory::where('product_id', '=', $id);
$category->update([
'category_id' => $request['category']
]);
return Response::json([
'message' => $product
], 200);
}

How to upload file using ajax/jQuery with Symfony2

Could anyone help me?
I'm trying to write a script that when the user clicks an image, that this triggers an image in the database to be updated.
For this I wrote the code which temporarily makes the Caller Line of the method in the controller, but when I send the form it is not validated because of Cross-Site-Request-Forgery.
$("#upload_picture").on('click', function (e) {
e.preventDefault();
$("#bundle_user_file").trigger('click');
});
$("#bundle_user_file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.active-img').attr('src', e.target.result);
};
reader.readAsDataURL(this.files[0]);
ajax_formData()
}
});
This is my Caller Line ajax, is do the treatment in the form with the FormData to post, caught the routes and the token. He calls route, but not sure if the image is going or not, even with the Inspector firefox.
function ajax_formData() {
var at = $("form[name=bundle_user]");
var formData = new FormData();
formData.append('file', $("input[type=file]")[0].files[0]);
var url = at.attr('action') + '?_token=' + $("#bundle_user__token").val();
$.ajax({
type: "PUT",
url: url,
data: formData,
success: function (data) {
alert("success: " + data.message);
},
fail: function (data) {
alert("error: " + data.message);
},
cache: false,
contentType: false,
processData: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Avalia se tem suporte a propriedade upload
myXhr.upload.addEventListener('progress', function () {
/* faz alguma coisa durante o progresso do upload */
}, false);
}
return myXhr;
}
});
}
This is the method in controlodor it with a common call with the click the button to submit change my image. But as I said before the ajax call, he replied that the Token not available
public function updateAction(Request $request, $id)
{
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$em = $this->getDoctrine()->getManager();
$entity = $this->getUser();
if ($entity->getId() != $id) {
$response = new JsonResponse(
array(
'message' => 'Não tem permissao'
), 400);
return $response;
}
$form_update = $this->updateForm($entity);
$form_update->handleRequest($request);
if ($form_update->isValid()) {
$entity->upload();
$em->persist($entity);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
$response = new JsonResponse(
array(
'message' => $form_update->getErrors()
), 400);
return $response;
}
Firstly, I notice that your click event for #upload_image fires a click trigger on #bundle_user_file, but below that you are asking it to look for a change event. Therefore, this would do nothing.
You can re-generate a CSRF token if you want by calling the csrf token_manager service by doing this:
/** #var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */
$csrf = $this->get('security.csrf.token_manager');
$token = $csrf->refreshToken($tokenId);
return new Response($token);
You can determine $tokenId in your form, if you want, or just use your picture ID, or whatever. Normally the CSRF token is generated automatically from your session, so you might want to check that too.
function upload_img(){
var file_data = $('.myform').find('.drawing').prop("files")[0];
var form_data = new FormData();
form_data.append("drawing", file_data);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
contentType: false,
dataType:'json',
cache: false,
processData:false,
success: function(data)
{
},
error: function()
{
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='myform'>
<input type='file' class='drawing' onchange='upload_img()' >
</form>

Ajax File Upload - Script Writes garbage in File

i have a Problem with my Ajax-Fileupload Script.
When I upload my Files, the Files are corrupt. When I open the File with Notepad++, i see that there are for example the following Lines:
-----------------------------22998260013704
Content-Disposition: form-data; name="0"; filename="myimage.png"
Content-Type: image/png
filecontent
-----------------------------22998260013704--
When I delete the 3 Lines bevor filecontent und the Line after filecontent, the File is ok.
I have no clue, why these 4 Lines are written to the Files.
I hope that somebody can help me.
Here is my Javascript-Code:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
data = new FormData(),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
console.log(key+" "+value);
file = value;
data.append(key, value);
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- http://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
And here my relevant PHP-Code:
private function copyPutFilesToTmp($directory = "") {
$temp = "xxx";
if (!is_dir($temp)) {
mkdir ($temp, 0777, true);
}
$tmpPath = $temp."/";
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$in = fopen('php://input', 'r');
$ziel = $tmpPath.$filename;
if (!file_exists($ziel)) {
$fileuploadok = true;
$out = fopen($ziel, 'w');
$data = fread($in, 1024);
while($data) {
if ($data != false) {
fwrite($out, $data);
} else {
$fileuploadok = false;
}
$data = fread($in, 1024);
}
fclose($in);
fclose($out);
if ($fileuploadok === FALSE) {
//...
} else {
//...
}
} else {
//...
}
return $answer;
}
I found the problem.
if I sent the file directly as data and not within a FormData it works!
So the right Code is:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
file = value;
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- https://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: file,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
found here: AJAX File Upload with XMLHttpRequest

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources