I am trying to build a WebApp which consumes REST API's with Flask.
I am getting my JSON object back successfully from my API but I am unable to display it in the HTML UI.
Consider I am trying to print userid from the JSON file, I am getting the error part only.
Can someone please point me out what is going wrong :
Here is my JSON Object which returns:
Here is my JS file:
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid[0])
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid)
$('#result').html('result.userid')
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
My JSON DATA:
[{"case": 2005608875,
"filepath": "/x/eng/cs-data/latx/dev/20150510_uploads/wilp/perfstat_20150415_001256/node/10.95.172.19/output.data",
"datatype": "perf8",
"perfdateend": "2015-04-15T02:15:37-04:00",
"userid": "wilp",
"filename": "perfstat_20150415_001256.zip",
"version": "v8.1 ",
"perfdate": "2015-04-15T01:14:24-04:00"}]
There are a couple of issues here, and none of them have anything to do with Flask.
You check the length of the returned JSON object. However, in JS objects do not have a length property, so result.length returns undefined which is not greater than 0.
Since you are using jQuery, you can use its isEmptyObject function to check that your object is not empty.
Also, inside that if statement you are inserting the literal string 'result.userid' into your HTML, instead of the actual userid value of the returned JSON.
if (!$.isEmptyObject(result)) {
...
$('#result').html(result.userid)
}
Related
I'm trying to sketch as in the image below the mistakes made by mis-inserting data into the form.
However, it only works when the data is entered correctly. It should show "Invalid CPF", for example.
JavaScript code:
$("#formCadastro").on("submit", function (event) {
event.preventDefault();
var dados = $(this).serialize();
$.ajax({
url: getRoot() + 'controllers/controllerCadastro',
type: "POST",
dataType: "json",
data: dados,
success: function (xhr) {
$(".retornoCad").empty();
$(".retornoCad").append("Dados inseridos com sucesso!");
},
error: function (xhr) {
$(".retornoCad").empty();
getCaptcha();
$.each(xhr.response, function(key,value){
$(".retornoCad").append(value + '<br>');
});
}
});
});
And the .php file for validation is:
public function validateFinalCad($arrVar)
{
if (count($this->getErro()) > 0) {
$arrResponse = [
// print_r($this->getErro())
"retorno" => "erro",
"erros" => print_r($this->getErro())
];
} else {
$arrResponse = [
// print_r($this->getErro())
"retorno" => "success",
"erros" => null
];
/*$this->cadastro->insertCad($arrVar);*/
}
return json_encode($arrResponse);
}
The error callback will only run if the entire HTTP request fails (i.e. it returns a status code which is not 200 (or related such as 201 etc)). It won't go to error just because you returned some JSON which contains messages which you consider to indicate validation errors. It's not a HTTP error.
Either
a) make the PHP return a 400 Bad Request response when there are validation errors, or
b) write code in the "success" to check the contents of the JSON and act accordingly.
e.g. this would do the job for option (b) :
success: function (xhr) {
$(".retornoCad").empty();
if (xhr.retorno == 'erro') {
getCaptcha();
$.each(xhr.erros, function (key, value) {
$(".retornoCad").append(value + '<br>');
});
} else {
$('.retornoCad').append('Dados inseridos com sucesso!');
}
}
Also, $.each(xhr.erros isn't going to do much, because in your PHP, erros is either null or a string (because you used print_r, which is supposed to only be a debugging tool). "erros" => $this->getErro() would be better (assuming getErro() returns an array of strings).
i.e.
$arrResponse = [
"retorno" => "erro",
"erros" => $this->getErro()
];
I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
I have basically the same problem as the one described in the link below, but I dont find the solution to be very clear. I want my ajax success function to wait until the window function is finished executing, THEN modify the divs. Instead, it modifies the divs of the current page, then redirects. AJAX: on success redirect then modify new page
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
I Will Suggest you Javascript Local Storage .
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
// Store
localStorage.setItem("count", "we analyzed...");
localStorage.setItem("result1", data.county);
localStorage.setItem("totals", "with a score of..");
localStorage.setItem("result2", data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
On Ready on same page:
jQuery(document).ready(function(){
if (localStorage.count) {
$("#count").text(localStorage.count);
}
if (localStorage.result1) {
$("#result1").text(localStorage.result1);
}
if (localStorage.totals) {
$("#totals").text(localStorage.totals);
}
if (localStorage.result2) {
$("#result2").text(localStorage.result2);
}
});
Local Storage Store Data in Browser Storage. You Also Can Remove Data From Local Storage.
setting the value of location.href will cause a full page refresh.
Therefore all your scripts will be wiped out.
If you REALLY wants to use the result of a ajax call to a redirected page, you should store this response data somewhere, then reuse it on your new page.
//save "data" in localSotorage
localStorage.myAjaxResponse = data; //if data is JSON then use: JSON.stringify(data) instead.
Then on your "/test" page, create a script to check for the value on the localStorage then display it.
data = JSON.parse(localStorage.myAjaxResponse);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
Although, there are other better ways to accomplish what you want.
You can do something like this:
On your ajax success:
data = JSON.parse(data);
console.log(data);
window.location.href = '/test?county='+data.county+'&sentiment='+totalSentiments;
Then on your test page write in javascript block:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
if (params.length > 0) {
$("#count").text("we analyzed...");
$("#result1").text(params['county']);
$("#totals").text("with a score of..");
$("#result2").text(params['sentiments']);
}
I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id
In following example of code, I want to traverse the responseText object which consist the html code came from request_page.php file. In onSuccess event, i want to check whether < Div > with id 'ersDiv' has any errors posted in it.
new Request.HTML({
url: 'request_page.php',
onSuccess: function(responseText, responseXML) {
// My expected code to handle responseText object
alert(errorMessage);
},
onFailure: function() { }
});
request_page.php file is like this :
<div align='center'><div id='ersDiv'>Page loaded with insufficient data</div></div>
try this for 1.2.x (example tweaked for the jsfiddle api):
new Request.HTML({
url: '/echo/html/',
method: "post",
data: {
html: "<div align='center'><div id='ersDiv'>Page loaded with insufficient data</div></div>",
delay: 1
},
onComplete: function(responseText, responseXML) {
var error, errors = responseXML.getElements("div").filter(function(el) {
return el.get("id") == "ersDiv";
});
if (errors.length) {
error = errors[0].get("text");
alert(error);
}
}
}).send();
working example:
http://www.jsfiddle.net/dimitar/vLgqB/
in 1.3 this can work as oskar suggested:
console.log($$(this.response.tree).getElement("#ersDiv")[0].get("text"));
http://www.jsfiddle.net/dimitar/vLgqB/2/
have fun.
function(responseText, responseXML) {
if (responseText.getElement('#ersDiv').get('text') === 'Page loaded with insufficient data'){
console.log('There was an error');
}
}
Btw. 1990 called, they want their align='center''s back :-)