Django: problem with format when using ajax query (string/Json) - javascript

I try to send data with ajax but the format is a string and I need JSON (or formated data)
Data to be sent are displayed in an HTML table.
I loop in all my rows to collect all data to be send using ajax.
But I have an error when I try to make a JSON object when using JSON.Parse(new_parameters).
If use new_parameters in my ajax query, I get False in my ajax view...
If I "stringify" new_parameters to use it in my ajax query, I get data in my ajax view but in string format...
That's mean the way I construct new_parameters is not a good way...
var parameters = {};
var current_parameters = [];
var new_parameters = [];
// Collect data from html data when user click on "Modify settings" button
$(document).on('click', '#modifier', function(event)
{
event.preventDefault();
$('#table_parametrage tr').each(function() {
var parameter = {};
$(this).find('td div').each (function() {
parameter[$(this).attr("col_name")] = $(this).eq(0).html();
});
new_parameters.push(parameter);
});
new_parameters.shift();
// requête ajax > start
// parameters = JSON.parse(new_parameters, null, 2);
console.log(new_parameters);
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: $(this).data("ajax-url"),
data: {
csrfmiddlewaretoken: csrftoken,
'data' : new_parameters,
},
dataType: 'json',
success: function (data) {
// alert(data);
},
error : function(resultat, statut, erreur){
//
}
});
// requête ajax > end
// Remise à zéro de la liste
new_parameters = [];
parameters = {};
});

for those interested, even if I am not ure it is the best code, I resolve my problem like this:
JS:
...
parameters = JSON.stringify(new_parameters, null, 2);
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: $('#modifier').data("ajax-url"),
data: {
csrfmiddlewaretoken: csrftoken,
'data' : parameters,
},
dataType: 'json',
success: function (data) {
// alert(data);
},
error : function(resultat, statut, erreur){
//
}
});
# requete ajax
def ajax(request):
if request.method == "POST":
data = request.POST.get('data',False)
# https://www.programiz.com/python-programming/json
data_dict = json.loads(data)
print(data_dict)
print(data_dict[0]['ran_st1'])
else:
datas = ''
print('echec')
return render(request, 'randomization_settings/ajax.html', {})

Related

How to abort ajax request

In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.

Iterate over array items and check property value

function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */

403 (FORBIDDEN)

I'm trying to send $ajax, and I have got it, but I have to send file with my form, in the same or not, doesn't matter. csrf token has not been found and I'm getting error.
My javascript
$(document).ready(function() {
var csrf_token = $('input[name="_token"]').val();
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
// $("body").bind("ajaxSend", function(elm, xhr, s) {
// if (s.type == "POST") {
// xhr.setRequestHeader('X-CSRF-Token', csrf_token);
// }
// });
window.getCookie = function(cname) { //window for testing in console
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
};
function sendPost() {
var data = $('form').serialize();
var file = $(document.getElementById('files').files[0]);
$.ajax({
type: 'POST',
url: '/delling_data_objects/document/',
//data: $('form').serialize(), it's working
data: file, // its don't
enctype: 'multipart/form-data',
headers: window.getCookie('csrftoken')
});
};
$('#submit').on('click', function() {
sendPost();
});
});
my view.py
def load_files(request):
form = ApartForm(request.POST)
import pdb
pdb.set_trace()
if form.is_valid():
form.save()
file_form = request.POST['file']
for f in file_form:
with open(f) as dest:
for chunk in f.chunks():
dest.write(chunk)
else:
return HttpResponse('form is not valid')
return HttpResponse('ok')
You are not doing it correctly. It feels like you are sending the requestHeader twice.(edit: nevermind didn't see a part of the code was commented)
Based on your code, try something like this :
function sendPost() {
var data = $('form').serialize();
var file = $(document.getElementById('files').files[0]);
var csrftoken = getCookie("csrftoken");
$.ajax({
method: "POST",
url: '/delling_data_objects/document/',
data: data,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(data) {
// whatever you want to do
}
});
}
$('#submit').on('click', function() {
sendPost();
});
var getCookie = function(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== "") {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + "=")) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
var csrfSafeMethod = function (method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};

post data using ajax and js

Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});

Phonegap:Login Through LinkedIn Error While Getting Access Token

I'm trying to implement Login through LinkedIn using the following link Login through LinkedIn
.
Below is my code`
var oauth_info = {};
var consumer_key = "";
var shared_secret = "";
var oauth = OAuthSimple(consumer_key, shared_secret);
function parse_response(response) {
response.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { oauth_info[$1] = $3; });
console.log("oauth_token1="+oauth_info.oauth_token);
}
function linkedInLogin()
{
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {oauth_callback: "http://www.example.com/"}}).signed_url;
console.log("url==="+url);
$.ajax(
{
url:url,
data: {},
success: function(data){
console.log("inside success");
console.log("response==="+data);
parse_response(data);
console.log("oauth_token2="+oauth_info.oauth_token);
var params = data;
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_token') {
localStorage.oauth_token = y[1];
console.log("oauth_token=="+localStorage.oauth_token);
}
if(y[0]==='oauth_token_secret')
{
localStorage.oauth_token_secret=y[1];
console.log("oauth_token_secret=="+localStorage.oauth_token_secret);
}
}
step2();
},
error: function(error) {
console.log("error");
client_browser.close();
},
dataType: 'text',
type: 'GET'
});
}
function step2()
{
var authoriseurl='https://www.linkedin.com/uas/oauth/authenticate?oauth_token='+oauth_info.oauth_token+'';
window.plugins.childBrowser.showWebPage(authoriseurl);
window.plugins.childBrowser.onLocationChange = function(loc){
console.log("on loc changed");
linkedInChanged(loc);
};
}
function linkedInChanged(loc)
{
console.log("inside loc changed");
if (loc.indexOf("http://www.example.com/") > -1) {
window.plugins.childBrowser.close();
console.log("oauth_token3="+oauth_info.oauth_token);
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
console.log("verifier===="+verifier);
}
}
var acces_url= access_token_url(verifier);
oauth.reset();
console.log("oauth_token4="+oauth_info.oauth_token);
//console.log("oauth_info"+oauth_info[0][0]+"===="+oauth_info[0][1]);
//var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: verifier}, signatures: oauth_info}).signed_url;
console.log("access _url="+acces_url);
$.ajax(
{
url:acces_url,
data: {},
success: function(data){
console.log("inside access token success");
console.log("response==="+data);
var params = data;
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_token') {
localStorage.linkedIn_access_Token = y[1];
console.log("linkedIn_access_Token=="+localStorage.linkedIn_access_Token);
}
if(y[0]==='oauth_token_secret')
{
localStorage.linkedIn_access_secret=y[1];
console.log("linkedIn_access_secret=="+localStorage.linkedIn_access_secret);
}
}
},
error: function(error){
console.log("error=="+error.responseText);
},
dataType: 'text',
type: 'GET'
});
}
}
function get_url_vars_from_string(url) {
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function access_token_url(pin) {
oauth.reset();
//alert(oauth_info.oauth_token);
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: pin}, signatures: oauth_info}).signed_url;
// alert("url="+url);
return url;
}
`
On click of a button the linkedInLogin method is called.
I'm not able to get the access token from this code.The ajax call for access token results in Error oauth_problem=token_rejected
Please help
I had the same problem, and found out where the issue comes from.
So, I've come to the request for the accessToken, and have to generate the signature. When I call OAuth.completeRequest() - this is where the signature gets generated - I pass two parameters, and the second one is an object that contains four things (the first two are application settings and next two are from my first request, for the request token):
The api key.
The api secret.
The request token.
The request token secret.
The fourth one was missing on my end. That was the problem.
Also - I'm using this OAuth library - http://oauth.googlecode.com/svn/code/javascript/oauth.js, so the methods/functions on your end could have completely different name. But you've got the idea.
Hope this helps ;)

Categories

Resources