Routers with Qurey Params - urlsearchparams

When I am trying to console Qurey Params I am getting empty object and my URL is http://localhost:3000/searchResult?Empid=220 .My code to set and get the query params is as below.Using params I need to filter my Emp object and need to display the filtered one.
Emp Page:
const handleClick =() => {
const params = new URLSearchParams(location.search)
params.append("Empid", EmployeeId)
history.push({pathname: `/searchResult`,
search:"?" + params})
}
Search Result page:
const params = useParams();
console.log("params", params)
When I tried to console log of Parmas I am getting empty object . I am expecting to get Empid=220 as a param.
empty object
Thanks in advance..

Related

MethodNotAllowedHttpException in compiled.php line 8518

Im sending request from salesforce to laravel then laravel return the result and display them on visual force page
Error Detail
Apex Method
public List<SelectOption> getItems()
{
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://clozer.3spire.net/public/goclozer/country');
req.setMethod('GET');
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/json');
try {
res = http.send(req);
} catch(System.CalloutException e) {
system.debug('Callout error: '+ e);
}
getAllCountry = (Map<String, String>)JSON.deserialize(res.getBody(),Map<String, String>.class);
List<SelectOption> option = new List<SelectOption>();
option.add(new SelectOption('0','--None--'));
for(String c : getAllCountry.values())
{
option.add(new SelectOption(c,c));
}
return option;
}
Expected Result
{"0":"Aruba","1":"Antigua and Barbuda","2":"United Arab Emirates","3":"Afghanistan","4":"Algeria","5":"Azerbaijan","6":"Albania","7":"Armenia","8":"Andorra","9":"Angola","10":"American Samoa","11":"Argentina","12":"Australia","13":"Ashmore and Cartier Islands"}
Laravel 5 Route
Route::get('/goclozer/country','GoClozerController#getCountry');
Laravel 5 Method
public function getCountry()
{
$country = \App\Country::all();
$names = array();
foreach($country as $c)
{
$names[] = $c->name;
}
echo json_encode($names,JSON_FORCE_OBJECT);
}
How can i get ride of this error
Thanks in advance
MethodNotAllowedHttpException means that you're using wrong HTTP verb ( Get, Post, Put, Delete ...). You've route defined for GET, but you may be posting data
The modification (as I assume you just want to retrieve the country names only) can be achieved by
$countries = Country::all(['name']);
this will only retrieve the names of the countries from the table, you can add more fields if you want to.
Controller gets a request, returns a response. You're not returning any response. just echoing the result. You can do the following,
return $countries;
This will simply return the JSON with country names.
You don't have to put an explicit slash at the front of route declaration. you can even write like the following and that will work too.
Route::get('goclozer/country','GoClozerController#getCountry');

Add row to Google Spreadhseet via API

I am building a Chrome extension which should write new rows into a Google Spreadsheet. I manage to read the sheet content but am not able to write an additional row. Currently my error is "400 (Bad Request)". Any idea what I am doing wrong here?
I have gone through the Google Sheets API documentation and other posted questions here but was not able to find any solution.
Here is the code which I use to GET the sheet content (this works):
function loadSpreadsheet(token) {
var y = new XMLHttpRequest();
y.open('GET', 'https://spreadsheets.google.com/feeds/list/spreadsheet_id/default/private/values?access_token=' + token);
y.onload = function() {
console.log(y.response);
};
y.send();
}
And this is the code I try to POST a new row (gives me "400 - Bad Request"):
function appendRow(token){
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">',//'--END_OF_PART\r\n',
'<gsx:name>',foo,'</gsx:name>',//'--END_OF_PART\r\n',
'</entry>'].join('');
return atom;
};
var params = {
'body': constructAtomXML("foo")
};
url = 'https://spreadsheets.google.com/feeds/list/spreadsheet_id/default/private/full?alt=json&access_token=' + token;
var z = new XMLHttpRequest();
z.open("POST", url, true);
z.setRequestHeader("Content-type", "application/atom+xml");
z.setRequestHeader("GData-Version", "3.0");
z.setRequestHeader("Authorization", 'Bearer '+ token);
z.onreadystatechange = function() {//Call a function when the state changes.
if(z.readyState == 4 && z.status == 200) {
alert(z.responseText);
}
}
z.send(params);
}
Note: spreadsheet_id is a placeholder for my actual sheet ID.
Follow the protocol and to make it work.
Assume spreadsheet ID is '1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8'
First use the spreadsheet ID to retrieve list of worksheets:
GET https://spreadsheets.google.com/feeds/worksheets/1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8/private/full?alt=json
There you can read list of worksheets and their IDs. Let use the first worksheet from the example. You'll find its id in feed > entry[0] > link array. Look for "rel" equal 'http://schemas.google.com/spreadsheets/2006#listfeed'.
In my example the URL for this worksheet is (Worksheet URL): https://spreadsheets.google.com/feeds/list/1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8/ofs6ake/private/full
Now, to read its content use:
GET [Worksheet URL]?alt=json
Besides list-row feed, you'll also find a "post" URL which should be used to alter spreadsheet using list-row feed. It's the one where "rel" equals "http://schemas.google.com/g/2005#post" under feed > link.
It happens that it is the same URL as for GET request. In my case: https://spreadsheets.google.com/feeds/list/1TCLgzG-AFsERoibIUOUUE8aNftoE7476TWYKqXQ0xb8/ofs6ake/private/full. Just be sure to not append alt=json.
Now, to insert a new row using list-row feed you need to send POST with payload which is specified in docs. You need to send a column name prefixed with "gsx:" as a tag name. However it may not be the same as the column name in the spreadsheet. You need to remove any white-spaces, make it all lowercase and without any national characters. So to make your example work you need to replace <gsx:Name> with <gsx:name>.
Before the change you probably had the following payload message:
Blank rows cannot be written; use delete instead.
It's because the API didn't understand what the "Name" is and it just dropped this part of entry from the request. Without it there were no more items and the row was blank.
Alternatively you can read column names from the GET response. Keys from objects in feed > entry array that begins with gsk$ are columns definitions (everything after $ sign is a column name).
=================================================================
EDIT
To answer a question from the comments.
I've changed two things from your example:
function appendRow(token){
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">',
'<gsx:name>',foo,'</gsx:name>',
'</entry>'].join('');
return atom;
};
/*
var params = {
'body': constructAtomXML("foo")
};
*/
var params = constructAtomXML("foo");
url = 'https://spreadsheets.google.com/feeds/list/'+spredsheetId+'/default/private/full?alt=json&access_token=' + token;
var z = new XMLHttpRequest();
z.open("POST", url, true);
z.setRequestHeader("Content-type", "application/atom+xml");
z.setRequestHeader("GData-Version", "3.0");
z.setRequestHeader("Authorization", 'Bearer '+ token);
z.onreadystatechange = function() {//Call a function when the state changes.
if(z.readyState == 4 && z.status == 200) {
alert(z.responseText);
}
}
z.send(params);
}
1) <gsx:Name> to <gsx:name>. Without it you'll receive an error.
2) params object should be a String! Not an object with some 'body' key. You just need to pass a value you want to send to the server.

Django AJAX call: Referencing Table in JS

Is there a way I can reference a list containing data from my database (item_list = inventory.objects.order_by('name')) in my jquery AJAX call?
This is my code:
/models.py:
class phonebook(models.Model):
name = models.Charfield(max_length=200)
phone_number = models.CharField(max_length=100)
/views.py:
def phonebook_home(request):
global phonebook
phonebook = phonebook.objects.order_by('name')
def get_next_3_contacts(request):
returnedContacts = phonebook[contactIndex:contactIndex+3]
return HttpResponse(phonebook)
/main.js:
var = ajax_call {
type: 'GET'
url: DEFINED_URL
data: {
index: contactIndex
},
dataType: 'html'
success: function (returned, textStatus_ignored, jqXHR_ignored) {
var contactIndex = 0
function phonebook_list(name, phone_number) {
"<li>" + name + " : " + phone_number + "</li>"
}
for(var index=0; index < 3; index++) {
var name = phonebook[index].name
var phone_number = phonebook[index].phone_number
$("ul").append(phonebook_list(name, phone_number))
}
contactIndex += 3
}
The phonebook[index].name / .phone_number returns "undefined" on my page. I want to keep my js file separate from my template file as it will be easier for me to debug, but unfortunately, this problem has stumped me. I also inputted an alert to test out if any data was being returned from the data base, which only returns a string containing the names of the contacts with no spacing in between contact names. Ex: "JaredSarahJohn".
All help and any bit of advice is appreciated!
A couple of things need to be cleaned up in order for this solution to work:
Your idea that global phonebook will be available from within get_next_3_contacts() is incorrect. When you make the AJAX call that will ultimately invoke get_next_3_contacts() the variable phonebook is no longer available. It went out of scope when the call to phonebook_home() completed.
What's the solution? Change phonebook_home() to accept an offset and count parameters. Have it hit the database and return the requested quantities. This is called pagination and is something you should get familiar with!
def phonebook_home(request, offset, count):
phonebook = phonebook.objects.all()[offset:offset+count]
But how do we get those results down to your AJAX handler? You can't just "return" a list of objects to the HTTPResponse() function - it's looking for text to render, not Model objects.
import json
from django.http import JsonResponse
def phonebook_home(request, offset, count):
status = "OK"
return_data = ""
try:
phonebook = phonebook.objects.all()[offset:offset+count]
return_data = json.dumps(phonebook)
exception:
status = "UH OH"
return JsonResponse({'data': return_data, 'status': status)

jqGrid GET and POST mtype in MVC

I just read that the mtype option in the jqGrid will determine how we will do the ajax call. GET will retrieve data and POST will send data.
When i load my jqGrid, i want to pass an extra parameter to my controller, in my js file:
url: 'Controller/Action1',
mtype: 'POST',
datatype: 'json',
postData: { ParentId: selectedParentId },
In my controller I have this:
public JsonResult Action1(ParentId)
{
// Retrieve child properties from db using ParentId
// Return json result
}
How will my jqGrid load the returned json data if my mtype is POST?
In my action, could i still get the other options of my jqGrid as a parameter like sort order, page size selected? Could i use something like this.Request.Param["sidx"] in my action?
In your controller you would take all the parameters the jqGrid would pass you:
public ActionResult GetGridData(string sidx, string sord, int page, int rows, bool _search, string filters, string ParentId)
{
....
int totalRecords = wholeList.Count();
var pagedQuery = wholeList.OrderBy(sidx + " " + sord).Skip((page - 1) * rows).Take(rows).ToList();
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from tempItem in pagedQuery
select new
{
cell = new string[] {
tempItem.ToString(),
...
}
}).ToArray()
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
You can use the extra parameter to change what you feed back to the jqGrid, and you will also see you are passing in and using the parameters to handle paging.
mtype option defines the type of the HTTP request:
if it's set to GET (by default): the request parameters are appended in the http query in the Addressbar like this .../Controller/Action1?ParentId=selectedParentId
if it's set to POST, the request parameters are hidden when sending http query
In fact, the two methods send the same parameters with diffrent ways. So there is any diffrent on loading returned JSON data with GET or POST method
Or course you can get the other options of your jqGrid as a parameter like sort order
Sorry for my bad english

How to get linq result as string array?

I would like to convert a list of User's properties into strings array (for json receiver) like:
List<User> users = <..list of users from db...>
var jsonData = (
from user in users
select new { user.Id, user.Person.Lastname, user.Person.Firstname });
return Json(jsonData)
The result is an array named fields
[{"Id":1,"Lastname":"Doe","Firstname":"John"},{"Id":2,"Lastname":"Smith","Firstname":"Adam"},...]
but I would like it to be the array of arrays of plain strings like:
[["1","Doe","John"]
["2","Smith","Adam"], ...]
How to cast linq result to strings array?
var jsonData = from user in users
select new[] { user.Id.ToString(),
user.Person.Lastname,
user.Person.Firstname };
Alternatively, you can use the lambda syntax:
var jsonData = users.Select(user => new[] { user.Id.ToString(),
user.Person.Lastname,
user.Person.Firstname });
I was using an IQueryable as the starting point of creating an array of values, not a List<>, but in either case you can serialise an anonymous object array, instead of a string array, to get the same result without casting values to strings.:
e.g.
var jsonData = users.Select(user => new object[] {
user.Id,
user.Person.Lastname,
user.Person.Firstname
});
In my instance I was also using the result client-side with jQuery dataTable, so the result needed to be wrapped in another anonymous object (with the property name aadata).
e.g.
return Json(new { aaData = jsonData }, JsonRequestbehavior.AllowGet);
Hopefully this will help others that find this question looking for dataTable specific version of this problem (as I was).

Resources