How to display axios response in Vue - javascript

I'm new in Vue.js and don't quite understand how it works. So, my function send data to server and get a response, using axios. When response has been got, I want to display it, using a variable, but something goes wrong at this point.
HTML template
<p v-if="text"> {{ text }} </p>
Vue:
const text = ref(undefined);
axios.post('api', anotherVar).then(
function (response) {
response.data.error ? (text.value = response.data.error, console.log(text.value)) : (console.log('Everything is OK'));
});

it will work like this.
const text = ref(undefined);
axios.post('api', anotherVar).then(
function (response) {
text.value = response.data.error ? response.data.error : 'Everything is OK';
if(text.value != undefined ) console.log(text.value)
});

Related

I Am Encountering An 400 Bad request Error In Wordpress While Making Call With wp_ajax

I am working in a Wordpress project where I want to load something via ajax in my site. I am loading many sections via ajax, but I have never encountered an error before. Here, also, I am doing everything how it should be done, but I don't know why I am getting a 400 bad request error. Here is the code:
if(!function_exists('enque_this')){
function enque_this(){
wp_enqueue_style( 'style-name', MY_PLUGIN_LOCATION.'css/style.css');
wp_enqueue_script('my_script_file',MY_PLUGIN_LOCATION.'js/md-referral.js','jQuery','',true);
wp_localize_script('my_script_file','ajax_object',array('ajax_url' => admin_url('admin-ajax.php'),'we_value'=>1234));
}}
add_action('wp_enqueue_scripts','enque_this');
if(!function_exists('enque_single_prod_page')){
function enque_single_prod_page(){
wp_enqueue_script('my_script_file_2nd',MY_PLUGIN_LOCATION.'js/md-single.js','jQuery','',true);
}}
add_action('wp_enqueue_scripts','enque_single_prod_page');
function how_much_dis(){
echo 'really .. . .!!! i Got SomeTHing ??';
};
add_action('wp_ajax_how_much_dis','how_much_dis');
jquery code
jQuery(document).on("click","#submit_reff_code",function(){
var codes = jQuery("#input_reff_code").val();
var button_text = jQuery("#submit_reff_code").val("Please Wait . . .");
var is_disabled = jQuery('[name="add-to-cart"]').prop('disabled');
var product_id = jQuery('[name="add-to-cart"]').val();
var variation_id = jQuery('[name="variation_id"]').val();
if( codes != "" && codes.length > 2 && is_disabled == false && jQuery.isNumeric(product_id)){
var data = {
'action' : 'how_much_dis',
'product_id_from_prod' : product_id,
'variation_id_from_prod': variation_id,
'code' : codes
};
jQuery.post(ajax_object.ajax_url, data , function(response){
console.log(response);
});
}else{
alert("please enter valid code");
};
});
Your help would be appreciated, thanxx
400 means that action is wrong. The code in the question should work when user is logged in. To make it working when user is not logged in, you have to add the line
add_action('wp_ajax_nopriv_how_much_dis','how_much_dis');
Maybe this is the reason.

Fetching metadata from url

I have used Jsoup library to fetch the metadata from url.
Document doc = Jsoup.connect("http://www.google.com").get();
String keywords = doc.select("meta[name=keywords]").first().attr("content");
System.out.println("Meta keyword : " + keywords);
String description = doc.select("meta[name=description]").get(0).attr("content");
Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
String src = images.get(0).attr("src");
System.out.println("Meta description : " + description);
System.out.println("Meta image URl : " + src);
But I want to do it in client side using javascript
You can't do it client only because of the cross-origin issue. You need a server side script to get the content of the page.
OR You can use YQL. In this way, the YQL will used as proxy.
https://policies.yahoo.com/us/en/yahoo/terms/product-atos/yql/index.htm
Or you can use https://cors-anywhere.herokuapp.com. In this way, cors-anywhere will used as proxy:
For example:
$('button').click(function() {
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/' + $('input').val()
}).then(function(data) {
var html = $(data);
$('#kw').html(getMetaContent(html, 'description') || 'no keywords found');
$('#des').html(getMetaContent(html, 'keywords') || 'no description found');
$('#img').html(html.find('img').attr('src') || 'no image found');
});
});
function getMetaContent(html, name) {
return html.filter(
(index, tag) => tag && tag.name && tag.name == name).attr('content');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Type URL here" value="http://www.html5rocks.com/en/tutorials/cors/" />
<button>Get Meta Data</button>
<pre>
<div>Meta Keyword: <div id="kw"></div></div>
<div>Description: <div id="des"></div></div>
<div>image: <div id="img"></div></div>
</pre>
Pure Javascript function
From node.js backend (Next.js) I use that:
export const fetchMetadata = async (url) => {
const html = await (await fetch(url, {
timeout: 5000,
headers: {
'User-Agent': 'request'
}
})).text()
var metadata = {};
html.replace(/<meta.+(property|name)="(.*?)".+content="(.*?)".*\/>/igm, (m,p0, p1, p2)=>{ metadata[p1] = decode(p2) } );
return metadata
}
export const decode = (str) => str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
})
You could use it on the client with https://cors-anywhere.herokuapp.com/corsdemo
You can use open-graph-scraper for this, for more info see this answer.

POST method and after submission GET method for a form without refreshing page (ajax)

Below is the required task :
Make an Ajax post to server (eg. "http://192.168.1.107:80" )
On response, make a get request to server asking for values
Update input box with returned values.
Note : Page should not refresh during the process
Below CodePen can help you get started:
Your query should also be resolved with this.
<html>
<input id='inp1' type='text'/>
</html>
<script>
var xhrObject = new XMLHttpRequest();
xhrObject.onreadystatechange = function() {
if (xhrObject.readyState === 4) {
if (xhrObject.status === 200 || xhrObject.status === 304) {
console.log(xhrObject.responseText);
var inp = document.getElementById('inp1');
inp.value = xhrObject.responseText;
}
}
};
xhrObject.open(
"GET",
"http://codepen.io/chriscoyier/pen/difoC.html",
true
);
xhrObject.send();
</script>
CodePen : http://codepen.io/anon/pen/LVKMOX

How do I receive and use a JSON object on the client-side from the server (Node JS and Express)?

I am trying to do something seemingly very simple but I'm having trouble working it out. Users can submit some text using a HTML form with POST method. This is then sent off to an API for processing, and returns with a JSON object. I then just want the app.js file to send this JSON object back so I can play around with it using JQuery.
Here is the .post method in my app.js
app.post('/', function(req, res){
console.log("starting app.post");
// See User Modeling API docs. Path to profile analysis is /api/v2/profile
// remove the last / from service_url if exist
var parts = url.parse(service_url.replace(/\/$/,''));
var profile_options = { host: parts.hostname,
port: parts.port,
path: parts.pathname + "/api/v2/profile",
method: 'POST',
headers: {
'Content-Type' :'application/json',
'Authorization' : auth }
};
// create a profile request with the text and the https options and call it
create_profile_request(profile_options,req.body.content)(function(error,profile_string) {
if (error) {res.render('home.html',{'error': error.message});
console.log("errormessage: "+error.message);
}
else {
// parse the profile and format it
var profile_json = JSON.parse(profile_string);
var flat_traits = flatten.flat(profile_json.tree);
// Extend the profile options and change the request path to get the visualization
var fileName="file 1"; //this will eventually be imported automatically
//console.log(flat_traits);
var scoreObject={"title":fileName, "percentage":functions.matchPercentage(flat_traits)}
res.send(scoreObject); //this is what I assume should send this back client-side
});
}
});
});
// creates a request function using the https options and the text in content
// the function that return receives a callback
var create_profile_request = function(options,content) {
return function (/*function*/ callback) {
// create the post data to send to the User Modeling service
var post_data = {
'contentItems' : [{
'userid' : 'dummy',
'id' : 'dummyUuid',
'sourceid' : 'freetext',
'contenttype' : 'text/plain',
'language' : 'en',
'content': content
}]
};
// Create a request to POST to the User Modeling service
var profile_req = https.request(options, function(result) {
result.setEncoding('utf-8');
var response_string = '';
result.on('data', function(chunk) {
response_string += chunk;
});
result.on('end', function() {
if (result.statusCode != 200) {
var error = JSON.parse(response_string);
console.log("status: "+result.statusCode);
callback({'message': error.user_message}, null);
console.log(error.user_message);
} else
callback(null,response_string);
});
});
profile_req.on('error', function(e) {
callback(e,null);
});
profile_req.write(JSON.stringify(post_data));
profile_req.end();
}
};
So I presume res.send is what passes the data across to the client-side, but then how do I receive the data on the client-side? This is my attempt at the JScript:
$.getJSON('/').done(function(data){
$('#resultsList').append('<li data-icon="arrow-r" data-iconpos="right" id="'+
data.title+'"> <a href="#breakdownDialog"> <div id="cvResults"><h3>'+
data.title+'</h3> <span>'+data.percentage+
'%</span></div></a><div id="output"></div></li>');
console.log(data.title+data.percentage);
}
});
I want to take some of the values from the JSON object and put them in a list on the existing HTML page. At the moment this just takes me to a different blank page that says Undefined.
How should I grab the JSON data from the server?
EDIT: Here's the HTML form I am submitting the data with:
<form method="POST" id="submitForm">
<fieldset>
<textarea id="textArea" required="true" rows="5" name="content"></textarea>
<button class="btn btn-block" type="submit">
Analyse
</button>
</fieldset>
</form>
Are you sure that you are sending json with res.send()? Try to set header
res.set('Content-Type', 'application/json') or use this res.json() instead of res.send()

alert part of AJAX response

I am using JS to submit data without loading the page and it is working fine, on response i am trying to send JSON which looks like this
{"mes":"<div class=\"alert alert-success\">Your goal has been updated.<\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"}
There are two items in the JSON response mes and graph_data. Now how can i make use of graph_data and mes seperately?
If I do this alert(data); this shows the above JSON response
But if I do the following I cant get them to alert seperately.
alert(data.graph_data);
alert(data.mes);
I will really appreciate if anyone can guide me on how to separate the two.
Update
This is the JS i am using to send and retrieve data on click of a button
$('#goalgraphdatasubmit').click(function () {
$('#goalgraphupdateform').submit();
});
$('#goalgraphupdateform').submit(function (e) {
"use strict";
e.preventDefault();
document.getElementById("goalgraphdatasubmit").innerHTML = "saving..";
var post = $('#goalgraphupdateform').serialize();
var action = $('#goalgraphupdateform').attr('action');
$("#holiday_goal_message").slideUp(350, function () {
$('#holiday_goal_message').hide();
$.post(action, post, function (data) {
$('#holiday_goal_message').html(data);
document.getElementById('holiday_goal_message').innerHTML = data;
$('#holiday_goal_message').slideDown('slow');
document.getElementById("goalgraphdatasubmit").innerHTML = "Submit";
alert(data);
if (data == '<div class="alert alert-success">Your goal has been updated.</div>') {
//$('#divGoal').load('dashboard-goals.php');
$("#holiday_goal_message").hide(2000);
updatetestGraph();
}
});
});
});
Use Like
var data = JSON.parse('{"event1":{"title":"My birthday","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "},"event2":{"title":"My birthday again","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "}}');
arr = []
for(var event in data){
var dataCopy = data[event]
for(key in dataCopy){
if(key == "start" || key == "end"){
// needs more specific method to manipulate date to your needs
dataCopy[key] = new Date(dataCopy[key])
}
}
arr.push(dataCopy)
}
alert( JSON.stringify(arr) )
Demo1
Demo2
Sorry cannot comment so have to answer
I have taken your JSON string in a variable here and it gives me proper result
See here
var d = {"mes":"<div class=\"alert alert-success\">Your goal has been updated. <\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"};
alert(d.graph_data);
alert(d.mes);

Categories