Not getting query string value using angular.js - php

I have a URL like this http://localhost/phpdemo/edit_data.php?edt_id=1. Here I need the query string value which is 1. By using Angular.js, I am getting the following output in browser's console.
id is : Object {}
My code is given below.
update.js:
var app=angular.module("edit_data", []);
app.controller("updateController",function($scope,$http,$location){
$scope.errors = [];
$scope.msgs = [];
var id=$location.search();
console.log("id is :",id);
$http.get('js/edit.php',{"user_id":$location.hash()}).success(function(response){
console.log('response',response);
});
$scope.update_data=function(){
$http.post('js/update.php',{"first_name":$scope.first_name,"last_name":$scope.last_name,"city":$scope.city}
).success(function(data, status, headers, config){
if(data.msg!=''){
$scope.msgs.push(data.msg);
}else{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
}
});
Please help me to resolve this issue.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:
var id=$location.search().edt_id;
Location service Search Little Brief
search(search, [paramValue]);
This method is getter / setter.
Return search part (as object) of current url when called without any parameter.
Change search part when called with parameter and return $location.
// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var searchObject = $location.search();
// => {foo: 'bar', baz: 'xoxo'}
// set foo to 'yipee'
$location.search('foo', 'yipee');
// $location.search() => {foo: 'yipee', baz: 'xoxo'}

This $location.search(); return an array, so
console.log("id is :",id[0]);
Can you try with above.
UPDATE:
$location.search()['edt_id']
It must return the value 1

Related

showing the [Object Object] in Angular [duplicate]

I am trying to alert a returned value from a function and I get this in the alert:
[object Object]
Here is the JavaScript code:
<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible());
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
</script>
whichIsVisible is the function which I am trying to check on.
As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?
That is because there are different types of objects in Javascript!
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
… several more …
and Object objects!
stringify({}) -> [object Object]
That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
The default conversion from an object to string is "[object Object]".
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.
Sidenote: IDs should not start with digits.
[object Object] is the default toString representation of an object in javascript.
If you want to know the properties of your object, just foreach over it like this:
for(var property in obj) {
alert(property + "=" + obj[property]);
}
In your particular case, you are getting a jQuery object. Try doing this instead:
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible().attr("id"));
});
This should alert the id of the visible element.
You can see value inside [object Object] like this
Alert.alert( JSON.stringify(userDate) );
Try like this
realm.write(() => {
const userFormData = realm.create('User',{
user_email: value.username,
user_password: value.password,
});
});
const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
Alert.alert( JSON.stringify(userDate) );
reference
https://off.tokyo/blog/react-native-object-object/
Basics
You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.
string, number, boolean, null, undefined, and symbol.
In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
If primitives have no properties, why does "this is a string".length return a value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
By this means primitives have access to all the properties (including methods) defined by their respective object constructors.
So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.
Analysis of toString() method
Consider the following code
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.
But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?
Closer look at Object.prototype.toString()
As per the documentation,
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Understand this from the following example
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
References:
https://es5.github.io/x15.2.html#x15.2.4.2
https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
It's the value returned by that object's toString() function.
I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:
function whichIsVisible_v2()
{
if (!$1.is(':hidden')) return '#1';
if (!$2.is(':hidden')) return '#2';
}
That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.
[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
I think the best way out is by using JSON.stringify() and passing your data as param:
alert(JSON.stringify(whichIsVisible()));
You have a javascript object
$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...
you have to treat $1 and $2 like jQuery objects.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".
Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.
The object whose class is Object seems quite different from the usual class instance object, because it acts like an associative array or list: it can be created by simple object literals (a list of keys and properties), like this: let obj={A:'a',B:'b'}; and because it looks very like this same literal notation when displayed in the Developer Tools Console pane and when it is converted to a JSON string.
But, in fact, the only real difference in objects of other classes (which are derived or extended from Object) is that other classes usually have constructors and methods (these are all functions), in addition to properties (which are variables). A class instance object is allocated using the 'new' operator, and its properties and methods are accessible through the 'this' variable. You can also access the underlying static functions that are copied to each new instance by using the 'prototype' property, and even extend system classes by adding new functions to their prototype object.
The Array object is also derived from Object and is frequently used: it is an ordered, 0-indexed array of variable values.
Object objects, unlike Arrays and other classes are treated simply as associative arrays (sometimes considered ordered, and sometimes considered unordered).

How do I add query string to URL in Laravel?

What is the simplest way to add a query string to URL in Laravel? Let's say I have a route resources like this
Route::get('/test', function() {
});
Are there just some parameters I can pass through to make the url look like this
/test?foo=bar
I'm super new to Laravel and I'm really not looking for something fancy. Thanks!
The simplest way to do this is to simply add the query string in to the url exactly as you have suggested www.example.com/test?foo=bar. In an example:
Route::get('test', function(){
return Input::get("foo");
});
This would return bar.
Simply use Input::get() to retrieve the parameter from the URL.
You can extend this out as much as you want; www.exmaple.com/test?foo=bar&day=Monday&name=John and retrieve them all if you needed to using Input::all(). Printing this out would return:
Array
(
[foo] => bar
[day] => Monday
[name] => John
)
More on the Input function here: https://laravel.com/api/5.1/Illuminate/Support/Facades/Input.html#method_get
Use /test/{foo} for compulsory and /test/{foo?} for optional
Route::get('/test/{foo}', function($foo) {
return "foo value is : ".$foo;
});
Check https://laravel.com/docs/5.1/routing
You get query string values from the request object:
Route::get('test', function () {
$foo = request('foo'); // $foo is now 'bar' or null
});

Loop AJAX Response from php

I want to loop ajax response
response = [
["u.profile"],
["r.useractivity"],
["i.items_job"],
["i.setup"],
["search"],
["i.items_assortment"]
]
I want data = u.profile;
data = r.useractivity;
etc
Tried Method :
$.each(response,function(key,value){
console.log(key+":"+value);
});
Getting error in console
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [["u.profile"],["r.useractivity"],["i.items_job"],["i.setup"],["search"],["i.items_assortment"]]
The problem is that your response var is an array of arrays (an object) and the default keys are integers.
It would be an easier (and better) way if you could change it into an array of strings like this one :
var response = ["u.profile",
"r.useractivity",
"i.items_job",
"i.setup",
"search",
"i.items_assortment"];
With this, you can easily loop your response like this :
for(var info in response)
console.log(info+':'+response[info]);
Hope this will help !

Access JSON array values?

eSo I've got some parsed php data whiched I've fetched from my database and then parsed to JSON with json_encode(). Then I've used JSONparse() to make objects of my array. My code looks like this:
$.get("fetchDatabase.php", function(data){
var parsedData = jQuery.parseJSON(data);
}
I'm left with the array parsedData which looks like this:
[
{"person0":{"name":["Erik Steen"],"age":["1"]}},
{"person1":{"name":["Frida Larsson"],"age":["1"]}},
{"person2":{"name":["Abdi Sabrie"],"age":["2"]}},
{"person3":{"name":["Achraf Malak"],"age":["3"]}},
{"person4":{"name":["Adam Anclair"],"age":["1"]}}
]
I've placed those arrays in an array named
var peopleArray= { people: [ parsedData ] };
So far so good. Now what I want is being able to access certain persons attribute. Like names or age. How do I target those attributes? I've tried to print those attributes with no luck. I tried:
alert (peopleArray.people[0].person1.name);
Whiched returns:
Uncaught TypeError: Cannot read property 'name' of undefined
How can I access those attributes?
Apart from the typo ("namn") the problem is you're putting an array inside an array:
var peopleArray = { people: [ parsedData ] };
Since parsedData is an array then what you end up with is a structure like this:
// peopleArray
{ people : [ [ { "person0" : ... }, ... ] ] }
// oops -----^
See the problem? Since parsedData is a already an array the correct code would be:
var peopleArray = { people: parsedData };

iterate through json and access two dimensions deep

I'm returning rows from a mysql database in php and then making an array of all these rows and then json encoding this. I am then trying to turn that json into autocomplete for jquery, not that relavent. The issue I have is that once I have it in json, there is no defining the rows. How do I access the same json.id that is in every "row" returned in json? here is a sample json object I'm using
[{"id":"95833","fname":"john","lname":"walker","email":"john.walker#john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train#john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}]
I do I access the first id, or the second one?, etc
Here's some sample code showing how to iterate over your data:
var data = [{"id":"95833","fname":"john","lname":"walker","email":"john.walker#john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train#john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}];
for( var i = 0; i < data.length; i ++ )
{
var item = data[i];
var thisID = item.id;
// do something clever here
}
jQuery will parse the JSON into a Javascript array of objects for you:
data[0].id // First id
data[1].id // Second id
I think, I think you're trying to access the "columns", not the rows. Incidentally, this general problem of the relation model of the a SQL database not matching the object model of most languages is called "The Impedance Mismatch", and it sucks. Your particular issue could be addressed (in jQuery) with:
$.map(data, function(n) { return n.id } );
Which will return an array containing all the id values.
If you are using jQuery 1.6 then it's very simple
// to get ['id', 'fname', 'lname', 'email', 'major', 'year', 'gender', 'created']
// you only need to map the first element of the data array and return the key.
var columnArray = $.map(data[0], function (val, k) {
return k;
});
Happy Coding :)

Categories