How to pass yii2 search params through javascript api call - javascript

my search params is
$params=Yii::$app->request->queryParams;
And my api call is like
function doInBackground(){
var params=<?=json_encode($params)?>;
$.get('car/get-map-data',
{
"params":params
},
function(data){
if(data)
{
console.log(data);
}
});
}
But i am getting an error like
PHP Notice – yii\base\ErrorException
Array to string conversion
on the line
var params=<?=json_encode($params)?>;
How to solve this.I want to pass the search params to another api.

you can use getQueryString()
function doInBackground(){
var params=<?=Yii::$app->request->getQueryString();?>;
$.get('car/get-map-data',
{
"params":params
},
function(data){
if(data)
{
console.log(data);
}
});
}

I think that handling the query params via URLSearchParams would be more non-hacky and clearer solution than obtaining them via PHP.
By URLSearchParams you can collect them into JS object and properly pass it as POST data to your AJAX request.

Related

Reading to JSON URLs with jQuery

I need to read two JSON URLs with jQuery, mangle them together and then proceed updating my UI from the JSON data.
With the two URLs in URLA and URLB and a global variable globalDataA I tried:
function useBothData(dataB) {
// use dataB and globalDataA
};
function useDataA (data) {
globalDataA = data
$.getJSON (URLB, useBothData);
};
$.getJSON (URLA, useDataA);
The idea is that after loading the 1st URL I load the 2nd and then work with them. However this does never seem to return. (I get the Brwoser warning "Script takes too long".)
How can I arrange jQuery's getJSON calls for the two URLs (and their success functions), so that I can then use their data in finally one function?
You can use the callback function of getJSON
$.getJSON(URLA, useDataA, function(dataB) {
//useBothData = globalDataA + dataB
$.getJSON(URLB, useBothData, function(result) {
//do more stuff
})
});

getting json data jquery with .get

<script>
$.get("url", function(data, textStatus, jqXHR) {
var json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
Hey,
I would like to get data from url. I can get the JSON file and stringify it to json variable. But I have some struggles when I 'm trying to use json variable. Because, it is local variable.
Also,
<script>
var json = "";
$.get("url", function(data, textStatus, jqXHR) {
json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
when I am trying to use json as a global variable, even I can not stringify data to it.
Question : How can I solve my problem?
It would be better to use your JSON data when it is available by putting the dependent code in a callback or a promise:
$.getJSON("url").then(function(data) {
// json is already parsed here
// put json dependent code here
});
You could also put your application logic in a function (assuming it's depending on the JSON data) and use that as your callback:
function initialize(data) {
// all of your data dependent logic here
}
$.getJSON("url").then(initialize);

Assigning JSON object to variable from google sheets URL?

I want to be able to pull data from a google spreadsheet doc every 24hrs and use the values in my html page.
I have managed to get the JSON url for the cell I want to track, but I do not know how to get this JSON object into a javascript variable using the url.
I have searched around and tried using Jquery $.get() and $.getJSON() but I cant seem to get anything to work.
The url for the google spreadsheet data cell JSON is
https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS
I know this is probably simple but I am very new to working with JSON/ Javascript and have been struggling to work this out.
Thanks for any help :)
The data being returned is jsonp so you need to specify that in your Ajax request.
function getData() {
return $.ajax({
url: 'https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS',
dataType: 'jsonp',
jsonpCallback: 'importGSS'
})
}
And while you can assign the data to, say, a global variable this will only get you so far - the Ajax process is asynchronous and you won't be able to access the data until the process has finished:
var obj;
getData().done(function (data) {
obj = data;
});
// console.log(obj) here will return undefined as the process
// has not yet finished
Much better to grab the data and do something with it:
function doSomethingWithData(data) {
console.log(data);
}
getData().done(function (data) {
doSomethingWithData(data);
});
Or even simpler:
getData().done(doSomethingWithData);

Fetch backbone collection from remote url error

I'm trying to set up a model using backbone that loads from a remote url: https://api.github.com/legacy/repos/search/javascript. Here is what I have so far.
var Repo= Backbone.Model.extend({});
var RepoCollection = Backbone.Collection.extend({
url : "https://api.github.com/legacy/repos/search/javascript",
model : Repo
});
var repos = new RepoCollection();
repos.fetch({success: function(){
console.log(repos.models);
}});
This just gives me an empty array. Why does this not work? This url just contains a non-empty JSON array. I've also tried the parse function without any success.
parse : function(data) {
return data.results;
}
If the github api does not support this kind of call, does anyone have an example of a remote url where I can use backbone to fetch data?
Edit: I should add that I looked at the network console on Chrome and I am getting a 200 OK response with correct JSON response from github. I guess I'm just having trouble figuring out how to access that data and populate my RepoCollection with it.
Your data is wrapped in a repositories key, not in results and looks like this
{
"repositories": [
...
]
}
Try
var RepoCollection = Backbone.Collection.extend({
url : "https://api.github.com/legacy/repos/search/javascript",
model : Repo,
parse : function(data) {
return data.repositories;
}
});
and a demo http://jsfiddle.net/nikoshr/vHX7C/
You can try:
repos.fetch({success: function(data){
console.log(data);
}});

Rendering mongodb database results from POST request in .ajax jquery wrapper in node js

I am creating a basic piece of functionality to allow users to send their location to a server which then queries a database and returns locations near to them. I am using the below jQuery .ajax wrapper to POST data to the server. This takes the form of a latlon point which is then used as the basis for a geosearch in MongoDB using nodejs and express on the backend. The results of the search are then intended to be returned to the client and rendered by the createMapListings function.
The /find page is initially rendered through a GET request to the database via mongodb separate from the below code. However subsequent to initial rendering, I then want to return results dependent on the location provided.
The POST method works fine and the location is posted to the server, with the search results being returned as I can print contents out through the console log.
However, I then want to render the results on the client-side. As mentioned, the results of the search render in the console, but when I attempt to pass through to the client, I can render the data itself (in the form of an array of objects) in the #output div, but the createMapListings function does not seem to catch the data.
In fact, the below function appears to be called but prints out over a thousand rows with the data that should be caught described as 'undefined'. I have tried to use res.render and res.redirect, but in the first case, the view renders in the div (which I suppose is expected) and the redirect fails.
The createMapListings function works fine when a simple GET request is made to the server, for example, for all objects in a collection, using ejs template. However, I think the issue here may be a combination of a POST request and then wanting to pass the results back to the AJAX request using the complete callback.
I apologise if the below code is somewhat obtuse. I’m definitely what you would call a beginner. I appreciate the above functionality may not possible so if there is a better way, I would of course be open to it (res.direct perhaps).
Here is the relevant client side script:
$(document).ready(function(){
$("#geolocate").click(function(){
navigator.geolocation.getCurrentPosition(geolocate, function(){
});
});
});
function geolocate(pos){
var latlonpt = [];
var x = pos.coords.latitude;
var y = pos.coords.longitude;
latlonpt.push(x);
latlonpt.push(y);
var obj = {
userlocation: latitudelongitudept
};
$.ajax({
url: "/find",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(obj),
complete: function (data) {
$('#output').html(data.responseText);
$('#infooutput').children().remove();
createMapListings(data.responseText);
}
});
};
function createMapListings(maps) {
for (var i = 0; i < maps.length; i++) {
var url = maps[i]._id;
var fullurl = "<a href='/show?id=" + url + "'>Route</a></div>";
var title = "<div>" + maps[i].title + " - " + fullurl +"";
$('#infooutput').append(title);
};
};
</script>
Here is the relevant route used in a basic express app to handle the post request made by the above .ajax wrapper.
exports.findbylocation = function(req, res) {
console.log(req.body.userlocation);
var userlocation = req.body.userlocation;
Map.ensureIndexes;
Map.find({loc :{ $near : userlocation }}, function(err, maps) {
if (err) {
console.log(err)
}
else {
var jmaps = JSON.stringify(maps);
console.log(jmaps);
res.send(jmaps);
}
});
};
By convention, the data variable name in an $.ajax callback signature refers to the parsed HTTP response body. Since your callback is on complete, we're actually passed the XMLHttpRequest used, by convention called xhr. You rightly grab the responseText property, but this needs parsing to be useful. So long as we take care over our Content-Type's and don't explicitly disable processData, jQuery will do the encoding/unencoding for us - we just deal with objects. This is a good thing, since the transport format isn't usually of any particular importance to the application logic. If we use res.json(maps) in place of res.send(jmaps), we can write our call more simply:
$.ajax({
url: '/find',
type: 'POST',
data: obj,
success: function(data) {},
error: function(xhr, text, err) {}
});
Here data is a Javascript object already parsed and ready to use. We also use a default application/x-www-form-urlencoded request rather than explicitly setting a contentType. This is the same as far as express is concerned: it will just be parsed by urlencoded instead of json.
Assuming you solved your client-sie problem.
As you are using express there is no need for JSON.stringfy,
you can use res.json(maps).

Categories

Resources