I'm trying to use mcrypt and encrypt and decrypt json data crossing domain. Actually, this worked when I use the encryption in the same domain, but did not work in ajax.
Here is function all:
function all($contentType = 'page') {
$secret_key = "12345678911234567892123456789312";
$this->load->database();
$query = $this->db->query(
"SELECT * FROM category"
);
$buffer = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, json_encode($result), MCRYPT_MODE_ECB);
$this->output->set_output(base64_encode($buffer));
Here is file of view:
$(function(){
try {
$.ajax({
type: "GET",
url: "http://localhost:8888/DIY/index.php/user/all/json",
crossDomain: true,
contentType: "application/x-www-form-urlencoded",
async: false,
dataType: 'text',
processData: false,
cache: false,
success: function (response) {
var a = mcrypt.Decrypt($.base64('decode', response ));
console.log( JSON.parse(a) );
},
error: function (ErrorResponse) {
console.log('error');
}
});
}
catch (error) {
}
});
The output in Chrome is:
[{"id":"1","EMAIL":"sda#q.com","PHONE":"sdsng","USERNAME":"12das","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null},{"id":"2","EMAIL":"adas","PHONE":"dsada","USERNAME":"asdasd","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null}]
And if I add JSON.parse(a) in the view file, it will display nothing. However, after I get console.log(a) in Chrome, I directly copy the output data as the parameters, and use it in Chrome console
JSON.parse('[{"id":"1","EMAIL":"139520519#qq.com","PHONE":"yang_zhang","USERNAME":"122545929","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null},{"id":"2","EMAIL":"adas","PHONE":"dsada","USERNAME":"asdasd","FIRST_NAME":null,"LAST_NAME":null,"PASSWORD":"","TYPE":null}]')
[Object, Object]
The output is what I am looking for!!! Can anyone help me to solve this problem?
Now it is solved. I change the mode of mcrypt from ecb to cfb, and pass the IV to different domain. Then using passed IV to decrypt data will get the string which can use JSON.parse() to get expected json object
Related
So, I've been working on a project that citizens can report problems on public places for the municipal government by filling a little form after selecting the place on Google Maps.
We need to implement reCAPTCHA for validation and stop/slow people from spamming our servers.
The data inputted in the form is sent through AJAX to an API that redirects it to add-problem.php but when I add 'g-recaptcha-response' and recaptcha.getResponse(); on my formData, the code stops working.
var formData = new FormData();
formData.append("description", description);
formData.append("pic", picture[0]);
formData.append("cpf", cpf);
formData.append("status", 1);
formData.append("keyword", keyword);
formData.append("type", "add-problem");
formData.append("place_id", $("#name").attr('data-id'));
formData.append("g-recaptcha-response", recaptcha.getResponse());
$.ajax({
type: 'POST',
url: '../../back/api/api.php',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
$("#loader").show();
},
success: function (data) {
$("#loader").hide();
console.log("success");
data = JSON.parse(data);
if (data.error) {
swal('Error', data.msg, 'error');
} else {
swal({
title: 'Sucess',
text: data.msg,
type: 'success',
onClose: () => {
location.reload();
}
The error on my console log is
Uncaught SyntaxError: Unexpected token O in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (municipe.php:467)
at u (jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
I also tried to send the code statically creating a var and attributing the secret key into it, but I had the exact same error. What could it be?
EDIT: So... I realized what was the problem. Basically, I was sending a var called "g-recaptcha-response" throught the AJAX but my PHP was trying to receive one named as "recaptcha-response". That fixed the problem with my SweetAlert Modal!
I am using Ext.Ajax.request() to make an API call which produces MediaType.MULTIPART_FORM_DATA. This is being handled in the php layer which returns the object in
header("Content-Type: application/pdf");
echo $response;
The problem is, I am not able to handle the received object in the Ext.Ajax.request() since it always handles only Json objects by default.
I tried giving Headers, AcceptType in the request, but it always goes to the failure block.
Here is the code:
Ext.Ajax.useDefaultXhrHeader = false;
var responseText;
Ext.Ajax.request({
url: '/index.php/abc/xyz?value=' + value,
method: 'GET',
waitMsg: 'Printing Label',
contentType: 'application/octet-stream' //not sure,
responseType: 'blob' //not sure,
xhr2: false //not sure,
success: function (response) {
console.log("Success!!");
return "";
},
failure: function (response) {
//Always comes here. The API returns 200
console.log("Hi here in the error");
//Raw pdf gets printed
console.log(response.responseText);
}
});
but it always goes to the failure
For this you need to check in php side because may be something you have missed. I think may be this will help you readfile
Try with this code. Hope this will help/guide you to get required result.
Ext.Ajax.request({
url: '/index.php/abc/xyz?value=' + value,
method: 'GET',
waitMsg: 'Printing Label',
cors: true,
useDefaultXhrHeader: false,
withCredentials: true,
defaultHeaders: {
'Content-Type': 'application/octet-stream;'
},
timeout:0,//If don't know how time will take server to get the file then you can put 0. if you need
success: function(response) {
//In response you will directly get the octet-stream
//For showing pdf in front end side using blob url
var byteCharacters = atob(response.responseText),
len = byteCharacters.length,
byteNumbers = new Array(len),
key = 0,
byteArray,
blob,
contentType = 'application/pdf';
//insert charcter code in {byteNumbers}
for (; key < len; key++) {
byteNumbers[key] = byteCharacters.charCodeAt(key);
}
//convert {byteNumbers} into Uint8Array
byteArray = new Uint8Array(byteNumbers);
//create blob using {byteArray}
blob = new Blob([byteArray], {
type: contentType
});
// set {src} to {iframe}
window.open(window.URL.createObjectURL(blob), '_blank');
},
failure: function(response) {
//if somthing wrong in serverside then it will come in failure.
}
});
Hope this will also help you for this question as well.
Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
and when I perform a dd($request->all()); in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
Things I've tried:
Set the HTTP verb to POST. Same result.
Set the AJAX contentType: false, contentType: application/json. Empty response.
Remove enctype: 'multipart/form-data'. Same response.
Any help is appreciated.
This fixed it for me
data: form_data,
contentType: false,
processData: false,
processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).
contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.
setting both to false made it work for me.
I hope this helps.
$('#my-form').submit(function(e) {
e.preventDefault();
var api_token = $('meta[name="api-token"]').attr('content');
form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/api/v1/item/add',
headers: {
Authorization: 'Bearer ' + api_token
},
data: form_data,
contentType: false,
processData: false,
success: function(result,status,xhr) {
console.log(result);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
also remember to use $request->all(); $request->input() excludes the files
I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.
Try changing
type : "PUT"
into
method : "POST"
Then change your method on your backend from put to post and you'll see the difference.
I used below codes to test it
$("#menu-form").submit(function (){
var fd = new FormData();
fd.append('section', 'general');
fd.append('action', 'previewImg');
fd.append('new_image', $('.new_image')[0].files[0]);
$.ajax({
method : 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token()}}'
},
url: "{{url('upload-now')}}",
data : fd,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
});
return false;
});
And in my controller
public function test(Request $request){
dd($request->all());
}
Ill try to research more about this issue.
Laravel 7,
if use method PUT in ajax, you can follow
1. change method method: 'PUT' to method: 'POST'
2. add formdata.append with _method PUT like this example :
$('#updateBtn').click(function(e){
e.preventDefault();
var frm = $('#tambahForm');
frm.trigger("reset");
$('.edit_errorNama_kategori').hide();
$('.edit_errorGambar').hide();
var url = "/pengurus/category/"+$('#edit_id').val();
var formdata = new FormData($("#editForm")[0]);
formdata.append('_method', 'PUT'); //*** here
$.ajax({
method :'POST', //*** here
url : url,
data : formdata,
dataType : 'json',
processData: false,
contentType: false,
success:function(data){
if (data.errors) {
if (data.errors.nama_kategori) {
$('.edit_errorNama_kategori').show();
$('.edit_errorNama_kategori').text(data.errors.nama_kategori);
}
if (data.errors.gambar){
$('.edit_errorGambar').show();
$('.edit_errorGambar').text(data.errors.gambar);
}
}else {
frm.trigger('reset');
$('#editModal').modal('hide');
swal('Success!','Data Updated Successfully','success');
table.ajax.reload(null,false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
});
});
its works for me
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
if (request.status == 200) {
toastr.success('Yai! Saved successfully!');
} else {
toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
};
}
Bit late, but;
This will solve your problem;
var formData = new FormData(document.getElementById('form'));
console.log(...formData);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
Then you can send this object to the server. This is much more readable and works great.
OR
You can simply send this directly;
JSON.stringify(Object.fromEntries(formData));
This is the newer approach.
And don't give up :-)
Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.
i want to assign new location but somehow i cant. i got an error while doing this.
Here is my code
jQuery.ajax({
type: "POST",
data: 'name='+ countryname,
url: "master/ValidationCountry.jsp",
// cache: false,
async: false,
success: function(response){
window.location.assign(request.getContextPath() +"/jsp/admin/AdminMaster.jsp?a=1");
// window.location.reload();
// window.location.replace(request.getContextPath() +"/jsp/admin/AdminMaster.jsp?a=1");
check = true;
},
error: function() {
check=false;
}
});
The error i got is:
ReferenceError: request is not defined
plz help me.
It looks like you are trying to access a http servlet requst object using javascript.
request.getContextPath() is a server side object, it is not available in client side.
One possible solution here is to use a global variable like _context = <context-path-from-request> and use it in your script
This need to be done in your view file like jsp/velocity/freemarker/tiles
jQuery.ajax({
type: "POST",
data: 'name='+ countryname,
url: "master/ValidationCountry.jsp",
// cache: false,
async: false,
success: function(response){
window.location.assign(response.d +"/jsp/admin/AdminMaster.jsp?a=1");
// window.location.reload();
// window.location.replace(response.d +"/jsp/admin/AdminMaster.jsp?a=1");
check = true;
},
error: function() {
check=false;
}
});
....................
and from server side web service function ,
[webMethod]
public static string fun()
{
return httpcontext.current.request.getContextPath();
}