$.ajax(
{ type : "POST"
, url : "my url link"
, data : fd
, dataType : 'json'
, contentType : false // The content type used when sending data to the server.
, cache : false // To unable request pages to be cached
, processData : false // To send DOMDocument or non processed data file it is set to false
, success: function(data, textStatus, jqXHR)
{
reset_info(true);
msg = "<strong>SUCCESS: </strong>";
if (!(data.sa === null))
{
//add and update case forceDelete=> !(data.notice===null)
msg = "<strong>Submitted Successfully</strong><br/>Your Application ID is: " + data.sa;
}
$("#name").val('');
}
How to console log all the data that i sent through this form?
multiple user fill this form and submit. and get a registration id.
Related
i'm calling a ajax function in html file in which i have integrated python django URL in which i have to pass token for get something so the problem which i am facing is my token is showing while i do inspect page source in html page. i want to hide it using java-script or ajax how can i do that please look at my code below.
$.ajax({
url : url,
headers: {'Authorization': 'Token {{token}}'},
data : card_data,
enctype : 'multipart/form-data',
cache : false,
contentType : false,
processData : false,
type : type,
success : function(data, textStatus, jqXHR){
console.log(data);
// Callback code
if(data['status'] == 'error') {
$("#lightbox").css({ 'display': "none" });
alert('error : ' + data['msg']);
} else {
$('#lightbox').find('h1').text('Saved, redirecting you to products page');
setTimeout(function(){ window.location.href = 'https://'+window.location.hostname+'/dashboard/destination/cards';}, 100);
}
}
});
});
There is no way to hide such information with JavaScript. You can try minifying your code so that your secret tokens are not easily discernible to the client-side.
I'd like to display file upload error on an ajax alert error message.
This is my ajax:
$.ajax({
url : url,
type : 'POST',
cache : false,
contentType : false,
processData : false,
data : all_data,
dataType : 'JSON',
success : function(data)
{
if (data.result != 0) {
toastr.options = {
closeButton : false,
progressBar : false,
showMethod : 'slideDown',
timeOut : 3000
};
toastr.success('UPLOAD SUCCESS', 'Attention...');
if(activeid != 0){
if($("#tl_responder").val() != "" && $("#tl_dept").val() != "" && $("#tl_jawab").val() != ""){
toastr.success('MAIL IS SENT', 'ATTENTION...');
}
}
} else { window.location.href = "<?php print base_url(); ?>complaint/detail?id=" + data.result + "#reloadafteradd"; }
},
error: function (jqXHR, textStatus, errorThrown, data)
{
toastr.options = {
closeButton : false,
progressBar : false,
showMethod : 'slideDown',
timeOut : 3000
};
toastr.error(errorThrown, 'Error...'); //THIS IS THE AJAX ERROR ALERT
if(!errorThrown){ toastr.error(data.upl_error, 'Error...'); }//This is not working
}
});
The AJAX error alert only shows alert when AJAX is not working. I'd like to display the file upload error here.
This is my controller that handle file upload when not uploading:
if ( ! $this->upload->do_upload('file')){
$response_array = array ('upl_error' => $this->upload->display_errors());
echo json_encode($response_array);
//return false;
}
You need to send a flag to specify if file uploaded successfully or not to do this send a success flag from your php code like this:
PHP CODE
if ( ! $this->upload->do_upload('file')){
// file not uploaded
$response_array = array ('success'=0,'upl_error' => $this->upload->display_errors('', ''));
echo json_encode($response_array);
}
else
{
// file uploaded
echo json_encode(array("success"=>1));
}
And then in your ajax success callback function you need to check that success flag like this
jQuery CODE
$.ajax({
url : url,
type : 'POST',
cache : false,
contentType : false,
processData : false,
data : all_data,
dataType : 'JSON',
success : function(data)
{
// if file upload success
if (data.success == 1) {
alert("File uploaed success");
}
// file not uploaded
else {
alert(data.upl_error);
}
}
});
I hope it will help you.
In success function to check response content, or use http_response_code(500) in php script to trigger ajax error function.
The AJAX error alert only shows alert when AJAX is not working. This is working fine because, the case your file is not uploading is not an ajax error, its a normal code flow.
To handle it, you have to return some status to manage it in success of ajax like:
success: function(response)
{
if(response == 1)
{
// do some thing
}
else
{
// do some thing
}
}
PHP:
if( check here file uploads or not )
{
echo 1;
}
else
{
echo 0;
}
I am working on form updation with ajax. It works fine when i use GET method in ajax but it throws error 405 method not allowed when i use Post method. I am testing this on Localhost. I have done this before in localhost and it worked fine. And by the way i am using Laravel 5.2 for this.
here is my ajax code.
$('#update-modal').on('click',function(){
$.ajax({
method : "POST",
url : updateURL,
data : { client_id : $('#client_id').val(),
client_name : $('#client_name').val(),
client_business : $('#client_business').val(),
client_ref : $('#client_ref').val(),
gmail_mail : $('#gmail_mail').val(),
gmail_pass : $('#gmail_pass').val(),
client_dob : $('#client_dob').val(),
client_addr : $('#client_addr').val(),
client_no1 : $('#client_no1').val(),
client_no2 : $('#client_no2').val(),
domain_name : $('#domain_name').val(),
domain_p_date : $('#domain_p_date').val(),
domain_reg : $('#domain_reg').val(),
domain_ex_date : $('#domain_ex_date').val(),
domain_acc_email : $('#domain_acc_email').val(),
domain_acc_pass : $('#domain_acc_pass').val()},
_token : token
})
.done(function(msg){
console.log(msg['message']);
});
});
Here is my script used inside the view
<script>
var updateURL = '{{ route('updateDomain') }}';
var token = '{{Session::token()}}';
</script>
here is my route
Route::post('/updateDomainModal' ,function(\Illuminate\Http\Request $request){
return response()->json(['message'=> $request['client_name']]);
})->name('updateDomain');
When the method inside ajax function and Route is changed to GET, It print the client's name passed in the console But when the same is done with POST method it throws the error This is the error details
jquery.min.js:2 GET http://localhost:8000/updateDomainModal?client_id=4&client_name=ABCD&client…2+15%3A01%3A40&domain_acc_email=abc123%40gmail.com&domain_acc_pass=123456 405 (Method Not Allowed)
You are wrongly using an } in the line starting with domain_acc_pass. You should use that '}' after assigning the token value. Now, the token won't send to the target, which is required.
Use type "POST'
$.ajax({
type : 'POST',
url : updateURL,
data : { client_id : $('#client_id').val(),
client_name : $('#client_name').val(),
client_business : $('#client_business').val(),
client_ref : $('#client_ref').val(),
gmail_mail : $('#gmail_mail').val(),
gmail_pass : $('#gmail_pass').val(),
client_dob : $('#client_dob').val(),
client_addr : $('#client_addr').val(),
client_no1 : $('#client_no1').val(),
client_no2 : $('#client_no2').val(),
domain_name : $('#domain_name').val(),
domain_p_date : $('#domain_p_date').val(),
domain_reg : $('#domain_reg').val(),
domain_ex_date : $('#domain_ex_date').val(),
domain_acc_email : $('#domain_acc_email').val(),
domain_acc_pass : $('#domain_acc_pass').val()},
_token : token
});
If you submit form
$("#form-name" ).submit(function(ev) {
ev.preventDefault();
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR)
{
location.reload();
},
error: function(jqXHR, textStatus, errorThrown)
{
consonle.log("error");
}
});
});
I'm trying to update a file in Alfresco... And I make this code:
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
function getResponse(pdfbase64) {
var fd = new FormData();
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
fd.append(csrf_header, csrf_token);
}
fd.append("username", "admin");
fd.append("updatenoderef", nodeRef);
fd.append("filedata", pdfbase64);
fd.append("majorversion", "true");
fd.append("overwrite", "true");
alert(fileUpdateURL);
$.ajax({
url: fileUpdateURL,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
}
The variable pdfbase64 is the content to put on the file (the changes that I made on the file to update the file in base64), but maybe this isn't the right format?, nodeRef is the reference of the file like: "workspace://SpacesStore/4fb1b7e7-2502-4011-8870-17e8d626b93b" and fileUpdateURL is the URL to POST: http://localhost:8080/share/proxy/alfresco/api/upload
Source of params
I got the error:
POST http://localhost:8080/share/proxy/alfresco/api/upload 500
Internal Server Error
javax.servlet.ServletException: Possible CSRF attack noted when
comparing token in session and request parameter. Request: POST
/share/proxy/alfresco/api/upload at
org.alfresco.web.site.servlet.CSRFFilter$AssertTokenAction.run(CSRFFilter.java:845)
at
org.alfresco.web.site.servlet.CSRFFilter.doFilter(CSRFFilter.java:312)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:447)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
EDIT:
If I use
http://localhost:8080/alfresco/service/api/upload
instead of
http://localhost:8080/share/proxy/alfresco/api/upload
I get the error:
{
"status" :
{
"code" : 400,
"name" : "Bad Request",
"description" : "Request sent by the client was syntactically incorrect."
},
"message" : "Required parameters are missing",
"exception" : "",
"callstack" :
[
],
"server" : "Community v5.0.0 (d r99759-b2) schema 8,022",
"time" : "Jan 24, 2016 1:14:41 PM"
}
Can anyone help me?
EDIT2:
I try to make the request with http://localhost:8080/share/proxy/alfresco/api/upload with this:
function getResponse(pdfbase64) {
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
var fd = new FormData();
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
fd.append(csrf_header, csrf_token);
fileUpdateURL += "?" + Alfresco.util.CSRFPolicy.getParameter() + "=" + encodeURIComponent(Alfresco.util.CSRFPolicy.getToken());
}
fd.append("username", "admin");
fd.append("updatenoderef", nodeRef);
fd.append("filedata", pdfbase64);
fd.append("majorversion", "true");
fd.append("overwrite", "true");
alert(fileUpdateURL);
$.ajax({
url: fileUpdateURL,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
}
But I obtain the error:
{
"status" :
{
"code" : 400,
"name" : "Bad Request",
"description" : "Request sent by the client was syntactically incorrect."
},
"message" : "Required parameters are missing",
"exception" : "",
"callstack" :
[
],
"server" : "Community v5.0.0 (d r99759-b2) schema 8,022",
"time" : "Jan 24, 2016 1:14:41 PM"
}
Try moving these lines inside your function:
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
And if that does not solve your problem and the issue turn out to be not a matter of variable scope for csrf_* vars, then you should try hint (2) from here
UPDATE :
As I explained in our chat you should replace :
fd.append("filedata", pdfbase64);
with :
fd.append("filedata", new Blob([pdfbase64], {type: 'application/pdf'}););
Instead of setting the header, pass the token on the url:
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
url += "?" + Alfresco.util.CSRFPolicy.getParameter() + "=" + encodeURIComponent(Alfresco.util.CSRFPolicy.getToken());
}
As described in CSRF Policy
When uploading a file by submitting a form with enctype
multipart/form-data it is not possible to set a header on the request,
the reason is not because of the enctype specifically but due to the
fact that its not possible to set a header on any form submission in
the browser.
The other solution is to use Alfresco.forms.Form that takes care of everything.
I have created this jQuery AJAX script for submitting a form:
$(document).ready(function() {
// process the form
$('#reviewForm').submit(function(e) {
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
Sadly the form submits though the normal way and not though the AJAX. Im at a loss to what the issue can be. I have tried the return false and such but that didn't work at all.
I think you are missing e.preventDefault(); at the begining of the submit(); and to use e.
$(document).ready(function(e) {
// process the form
$('#reviewForm').submit(function(e) {
e.preventDefault();
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
});
});
Hope this Helps.
$(document).ready(function() {
// process the form
$('#reviewForm').click(function(e) {
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
Use 'Click' event instead of 'Submit' will work definatly