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.
Related
https://github.com/simpleblog-project/Simple-Blog/issues/1
$.ajax({
method: "POST",
url: "http://localhost:5000/auth/login",
data: JSON.stringify({
"name" : id,
"password" : password
}),
contentType: 'application/json'
})
.done(function(msg) {
if (msg.access_token) {
createCookie(msg.access_token);
window.location.href = './Main.html';
}
else {
if(msg.message)
{
console.log(msg.message);
alert(msg.message);
}
}
});
this
else{
if(msg.message)
{
console.log(msg.message);
alert(msg.message);
}
}
that is not working.
log was jquery-3.3.1.min.js:2 POST http://localhost:5000/auth/login 400 (BAD REQUEST)
this problem is related by app.py this part ▼
#app.route('/auth/login', methods=['POST'])
def login():
data = request.json
name = data['name']
password = data['password']
user = User.query.filter_by(name=name).first()
if user is None or not User.verify_password(user, password):
return {"message": "invalid username or password"}, 400
return {
'access_token': create_access_token(user.id, expires_delta=access_token_exdelta),
'refresh_token': create_refresh_token(user.id, expires_delta=refresh_otken_exdelta)
}
Open the browser to your page and put a breakpoint in the browser on the code, you can click on F12 to open the developer window click on console and navigate to the line. click on the line to add a breakpoint.(red bullet) For ex.
The if statement would be a nice spot to put a breakpoint on. (javascript side) when in a breakpoint ( you see a blue line / redline) hovering on that spot when you hit it, and you can see which variables you have. and in console you can type "msg" and it would show you the current state of the msg object.
also might want to add a error part to the ajax call, just to check if the ajax call itself went ok.
$.ajax({
method: "POST",
url: "http://localhost:5000/auth/login",
data: JSON.stringify({
"name" : id,
"password" : password
}),
contentType: 'application/json',
success: function (data, status, xhr) {
console.log("Succes!" + data);
},
error: function (xhr) {
console.log("Error happened" +xhr.status);
}
});
Look at the documentation how the ajax call works:
https://api.jquery.com/jQuery.ajax/
and check if you get the object "msg" back from the server.
Good luck :).
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
I have this function in my UsersController. I created this JSON response by using the _serialize key:
public function test() {
$arrEmail = $this->User->find('first');
$this->set('foo', $arrEmail);
$this->set('_serialize', array('foo') );
}
Now in the client side, in my phonegap application, I am trying to access this data. So I put the following:
<script>
$( document ).ready(function() {
alert(1);
$.ajax({
url : "http://localhost/database/users/" + 'test.json',
async : false,
cache : false,
crossDomain: true,
dataType : 'json',
type : 'post',
success : function(result) {
alert('success');
alert(JSON.stringify(result));
},
error : function(xhr, status, err) {
//con failed
alert(err+' '+xhr+' '+status);
}
});
});
</script>
The alert gives me the following .
Now I need to access to the username and the other attributes. I tried result.attributename but i always get undefined as a response.
EDIT:
`result.foo.User.id` solved the issue.
I used this function
jQuery.ajax({
type: 'POST',
url: urlSubmit,
timeout: 5000,
dataType: 'text',
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
"success": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX success :) - statut " + textStatus);
$timeout(successMailZR_alerte, 3000);
},
"error": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX fail :/ - statut " + textStatus);
$timeout(errorMailZR_alerte, 3000);
}
});
Whats the code is doing : code POST to a php script who send an email.
but, since i rewrited my code in a complete angularjs app, i do it like this :
$http({
method: 'POST',
url: urlSubmit,
timeout: 5000,
cache: false,
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
responseType: 'text',
}).
success(function(data, status, headers, config) {
console.log("AJAX success :) - statut " + status);
$timeout(successMailZR_alerte, 3000);
}).
error(function(data, status, headers, config) {
console.log("AJAX fail :/ - statut " + status);
$timeout(errorMailZR_alerte, 3000);
});
Problem is : with $http, i have a success 200 but nothing is posted and i have no return in my email. What's the problem ?
The problem is that jQuery's POST does send your data as form data (e.g. key-value pairs) (https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) whereas AngularJS sends your data in the request payload. For a difference between the two see the following SO question: What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
In order to make your angular script works with your server you have to convert your data to a URL encoded string as described here: How can I post data as form data instead of a request payload?. Simply setting headers: {'Content-Type': 'application/x-www-form-urlencoded'} is not enough.
A different approach would be to adapt the back-end of your application to parse the message payload instead of the form data parameters.
To understand this one need to understand the request headers set by angular and jquery, There are differences with the headers like when request is post by jQuery then header might look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded // default header set by jQuery
foo=bar&name=John
You can see this in form data in the request made in the browser, if you use chrome then you can see this in chrome inspector at network tab, if you click the request then you can see the form data and content headers set by the jQuery.
On the other side with angular js $http service, when a request is made then you can find these:
POST /some-path HTTP/1.1
Content-Type: application/json // default header set by angular
{ "foo" : "bar", "name" : "John" }
The real difference is this you have a request payload not usual form data which is used by jQuery. so you need to do something extra at the server side like below.
Use this:
$data = json_decode(file_get_contents("php://input"));
echo $data->date;
// and all other params you have sent
This is due to its default headers
Accept: application/json, text/plain, * / *
Content-Type: application/json
and jQuery unlikely have something else:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)