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>
Related
I have two blob file that recived from two recording method
window.recorderr = new MediaRecorder(stream, {
type:'video/mp4'
});
recorderr.start(99999999999999999);
window.recorder = new MediaRecorder(stream, {
type: 'video/mp4'
});
recorder.start(99999999999999999);
};
And i tried to save the file on a stop button click like this calling two events in a single click
btnStopRecording.onclick = function () {
stoprecordinguserstream();
stoprecordinglocalstream();
};
function stoprecordinguserstream()
{
if (!window.recorder) return;
recorder.ondataavailable = function (event) {
var blob = event.data;
var video = document.getElementById('recordedvideo');
video.src = URL.createObjectURL(event.data);
var formData = new FormData();
formData.append("MethodName", "saveuser");
formData.append("data", event.data);
$.ajax({
type: 'POST',
url: '/RecordSve.ashx',
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
console.log(data);
recordedsource = data;
});
console.log(blob.size, blob);
};
recorder.stop();
}
function stoprecordinglocalstream()
{
if (!window.recorderr) return;
recorder.ondataavailable = function (event) {
var blob = event.data;
var video = document.getElementById('recordedvideolocal');
video.src = URL.createObjectURL(event.data);
var formData = new FormData();
formData.append("MethodName", "saveclient");
formData.append("data", event.data);
$.ajax({
type: 'POST',
url: '/RecordSve.ashx',
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
console.log(data);
recordedsource = data;
});
console.log(blob.size, blob);
};
recorderr.stop();
}
but the above method only saving one file at a time how can i save two files in a single button click?
my handler function goes like this
public void ProcessRequest(HttpContext context)
{
MethodName = context.Request.Params["MethodName"];
switch (MethodName)
{
case"saveuser":
saveuservideo(context);
break;
case"saveclient":
saveclientvideo(context);
break;
default:
break;
}
}
The purpose of this is Iam trying to save video that recorded from a live session chat since i couldn't find any better way for saving it i tried to save it as two file as it is and merging the two files for a final output but Iam struggling to save multiple files at a time any help would be apreciated.
Here is how i over come the situvation using $.when()
$.when(stoprecordinguserstream(), stoprecordinglocalstream()).then(console.log('sucess'));
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,
I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});
I am submitting form data using Ajax and they are successfully saved in the database and I am able to alert the response data. I now want to use the returned data as response to call another function using Ajax and pass them as parameters so that to the called function they can be used to fetch data and and display them on the web page.
The problem is that when the data have been alerted, the function I call using Ajax is not responding even when I use some functions like window.location.href, window.location.replace, window.location.reload they are not executed
Here is the sample code
submitHandler: function(form) {
/*errorHandler.hide(); */
var el = $(div);
el.block({
overlayCSS: {
backgroundColor: '#fff'
},
message: '<i class="fa fa-refresh fa-spin"></i>',
css: {
border: 'none',
color: '#333',
background: 'none'
}
});
/*Set off for database validation */
$('#name1').removeClass('has-error');
$('#name1 .help-block').empty();
$('#date1').removeClass('has-error');
$('#date1 .help-block').empty();
/*end database validation */
/*ajax options */
var options = {
/*target: '#output2', target element(s) to be updated with server response */
success: function(data, textStatus, XMLHttpRequest) {
el.unblock();
if (!data.success) {
/*append error message on the form for each control and database validation*/
console.log(data);
if (data.errors.name1) {
$('#name1').addClass('has-error');
$('#name1 .help-block').html(data.errors.name1);
}
} else {
var business_id = data.business_id;
var bnm_app_id = data.bnm_app_id;
var name = data.name;
var doc = data.doc;
alert(business_id);
alert(bnm_app_id);
alert(name);
alert(doc);
if (window.XMLHttpRequest) {
myObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
myObject = new ActiveXObject('Micrsoft.XMLHTTP');
myObject.overrideMimeType('text/xml');
}
myObject.onreadystatechange = function() {
data = myObject.responseText;
if (myObject.readyState == 4) {
//document.getElementById('step-2').innerHTML = data;
window.location.reload(true);
}
}; //specify name of function that will handle server response........
myObject.open('GET', '<?php echo base_url()."bn_application/register";?>?bnm_app_id=' + bnm_app_id + '&doc=' + doc + '&business_id=' + business_id + '&name=' + name, true);
myObject.send();
}
},
error: function(xhr, textStatus, errorThrown) {
el.unblock();
if (xhr.responseText === undefined) {
$.gritter.add({
/* (string | mandatory) the heading of the notification */
title: 'Connection timed out',
class_name: 'gritter-black'
});
} else {
var myWindow = window.open("Error", "MsgWindow", "width=900, height=400");
myWindow.document.write(xhr.responseText);
}
/*clear controls that do not need to keep its previous info */
},
url: home + 'bn_application/save_clearance_name',
/* override for form's 'action' attribute*/
data: {
name1_percent: name1_percent
},
type: 'post',
/* 'get' or 'post', override for form's 'method' attribute*/
dataType: 'json',
/* 'xml', 'script', or 'json' (expected server response type)*/
beforeSend: function() {
},
uploadProgress: function(event, position, total, percentComplete) {
},
complete: function() {
}
};
/*submit form via ajax */
$('#bn_clearance').ajaxSubmit(options);
}
If i understand you right , you need something like this ?
$.ajax({
type: "GET",
url: baseUrl + 'api/cars',
success: function (firstResponse) {
$.ajax({
type: "GET",
url: baseUrl + 'api/cars/' + firstResponse[0].Id,
success: function (secondResponse) {
window.location.href = secondResponse[0].Make;
}
});
}
});
You can use window.open function
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
window.open("http://www.w3schools.com", "_self");
}});
});
You should put your redirecting url in success function of ajax. (if you are using jQuery). Because javascript runs codes asynchronously and probably your code tries to run before you get response from request.
I know this is a known issue but I'm having difficulty on fixing my problem. It seems that I don't receive anything from my UI5 Application when I sent an image via FileUploader to my server. I am new to HCP and this is my first time handling XSJS file. I hope you can help me.
UI5.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("sample.controller.View1", {
handleUploadPress : function(oEvent)
{
var fileLoader =this.getView().byId("FileLoader");//XML View
var fileName = fileLoader.getValue();
jQuery.sap.require("sap.ui.commons.MessageBox");
if (fileName === "" )
{
sap.ui.commons.MessageBox.show("Please choose File.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
else
{
var uploadUrl = "https://xxxxxx/services/Sample.xsjs?file_name="+fileName;
var formEle = jQuery.sap.domById("UpdateContact--FileLoader");
var form = $(formEle).find("form")[0] ;
var fd = new FormData(form);
$.ajax({
url: uploadUrl,
type: "GET",
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(data, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
$.ajax({
url: uploadUrl,
type: "POST",
processData :false ,
contentType: false,
data: fd,
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", token);
},
success: function(data, textStatus, XMLHttpRequest)
{
var resptext = XMLHttpRequest.responseText;
jQuery.sap.require("sap.ui.commons.MessageBox");
sap.ui.commons.MessageBox.show(resptext, sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
if(data === "Upload successful"){
sap.ui.commons.MessageBox.show("File uploaded.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
},
error: function(data, textStatus, XMLHttpRequest)
{
sap.ui.commons.MessageBox.show("File could not be uploaded.", sap.ui.commons.MessageBox.Icon.ERROR, "Error");
}
});
}} ) ;
}
}
});
XSJS Service:
$.response.contentType = "text/html";
try
{
var conn = $.hdb.getConnection();
var filename = $.request.parameters.get("file_name");
var headers = $.entity.headers.length;
var pstmt = conn.prepareStatement("INSERT INTO \"XXX_ASSETS\".\"XXX\" VALUES('1',?,'test',CURRENT_USER,CURRENT_TIMESTAMP)");
if($.request.entities.length > 0){
var file_body = $.request.entities[0].body.asArrayBuffer();
pstmt.setBlob(1,file_body);
pstmt.execute();
$.response.setBody("[200]:Upload successful!");
}
else
{
$.response.setBody("No Entries");
}
pstmt.close();
conn.commit();
conn.close();
}
catch(err)
{
if (pstmt !== null)
{
pstmt.close();
}
if (conn !== null)
{
conn.close();
}
$.response.setBody(err.message);
}
}
My code was built based on the tutorials I have found on the internet. Thank You.
A good way to save the image is converting(Base64) and save as blob in HANA table.
Regards