Check passed data with a view is not empty in laravel - javascript

I am using laravel 4 and I want to pass a data with a view.
I have used this code in a controller.
$view = View::make('settings.editEvent');
$view->bounderyData = $bounderyData;
And I want to check whether this data exists or not in the view settings/editEvent.blade.php
Tried using this..
<script>
if('{{$bounderyData.length()}}'!=null)
console.log('exists');
</script>
Error :
Array to string conversion error
How can I check the existence ?

Do not assign the data to the View variable, but instead, pass it along using with as Laravel requests you to use:
$view = View::make('settings.editEvent')
->with('bounderyData', $bouderyData);

Actually both of the snippets work the same way. You can either pass data using with() method or by assigning it to view as property. So it doesn't really matter. But it looks like you are using some weird syntax because you are trying to access method length() using dot syntax inside Blade echo statement. Try:
if({{count($bounderyData)}}!=null)
console.log('exists');
or something similar. Remember that everything inside {{}} is going to be echo'ed by PHP. So if you have some sort of array there you may either want to count number of elements or maybe cast it to JSON and then decode it inside Javascript. If you still have problem, let us know what is the issue.

Related

Get value in data object Javascript

I have a data object, and i want to get on of the value from it, when i try to print the data:
console.log(data);
i got an object like the image below :
the problem is i want to get the order[billing_address][country_id] which i think is an object, but i don't know how to fetch it. i've tried :
console.log(data.order); //didn't work
console.log(data.order[billing_address][country_id]);//didn't work
The name of the property is: "order[billing_address][country_id]"
To access its value try:
console.log(data['order[billing_address][country_id]'); // Should work
It appears that the values you are looking for have keys that are the whole string:
"order[billing_address][telephone]"
You can access these values like this:
data["order[billing_address][telephone]"] //"5"
You are currently trying this:
data.order[billing_address][country_id]
What you are trying doesn't work because there are no variables billing_address or country_id that are defined, and the object is not that deeply nested - just has the above mentioned long string for a key.

Assign unserialize Laravel object to JS array

I have serialize object returning from Controller to blade view in laravel like:
"a:3:{i:0;s:1:"2";i:1;s:1:"4";i:2;s:1:"6";}"
from my blade view I use this JS code block to get those value as array.
var branches = {{unserialize($preliminary->branches)}};
But in there I'm getting error saying
expression expected
any suggestions to solve this situation..?
Run json_encode on top of your unserialize.
E.g.
var branches = {{json_encode(unserialize($preliminary->branches))}};
unserialize is giving you a PHP object, which you are trying to inject directly into JS. By passing it through json_encodeyou convert it to a string javascript can grok.

Accessing javascript object named via php globally

I have a bunch of CSS properties stored in a MySQL database accessed via PHP. I need to make these properties available to JavaScript after the page has finished loading.
So what I did is foreach row, put the values in a Javascript object like so:
foreach ($cellcontent as $cellproperty) {
echo 'var '.$cellproperty->cell_id.' = {cellwidth:"'.$cellproperty->cell_width.'"};';
}
(For simplicity's sake I've only included one object property here but in reality there are many more.)
My problem is that at runtime, via JavaScript I get the cell_id reference which is somewhere in the html page like so:
var dacell = $(this).closest("div");
var cellid = dacell.attr("id");
So at this point, cellid is equal to the name of my var from the php output.
But when I try to get the property of my object (cellwidth) via JavaScript it doesn't work. Says its undefined when I try to see the value in an alert:
alert(cellid.cellwidth);
I think I'm just not referencing the actual object at this point and just trying to get a property of what has now become a string.
Is there a way to get back the reference to the object itself?
var cellid = dacell.attr("id");
The variable cellid is a string. Your hopes would be that the variable your are looking is in the global namespace which you can access via the following:
window[cellid].cellwidth
It's an awfull practice to pollute the global namespace with so much stuff.
Fetch all the values you need to inject into the JS, create an associative Array and inject it as a single JSON into the Page.
Nevermind everyone. The eval() javascript function fixed it all.
Instead of doing:
alert(cellid.cellwidth);
I did:
alert(eval(cellid).cellwidth);
and everything worked.
Thanks for all your time.
Cheers,
Erick P.

Access fields in an array contained in a model

I have some JavaScript code that needs to be able to access fields of an array of objects that is contained within my model. I currently have this:
var model = #Html.Raw(Json.Encode(Model));
for(var i = 0; i < model.testobject.length; i++) {
console.log(model.testobject[i]);
}
Which prints out the fields within each object of testobject. But say I have a field, ID, in my testobject class. How do I then access that? Doing this:
console.log(model.testobject[i].ID);
Does not work. Do I have to somehow encode that specific instance of testobject before accessing it's fields?
And yes, before anyone says it I know this should be contained within the controller. As it currently stands though, that's not possible for this project.
This is the general structure of what is printed out:
Object {field: value}
Edit:
I attempted to use JSON.stringify on my model.IdentifiApprovalConfigurations and it seems I got a little close to reaching my solution. This is what it looks like now:
console.log(JSON.stringify(model.testobject[i]).ID);
However, this prints out undefined.
Edit 2:
Oops, seems the ID field I'm trying to access isn't being populated before I send them to my view which is my own issue. JSON.stringify works though, and I understand why it wasn't working earlier.
Final edit:
JSON.parse(JSON.stringify(model.testobject[i])).Value
I had to stringify and then parse my JSON to access the value.
As I'm still starting out with web development, I forgot that I needed to convert my object into a JSON object. This:
JSON.parse(JSON.stringify(model.testobject[i])).Value
Is the final piece of code that allows me to stringify an object, parse the JSON and then access fields within that object.

How to access rails variables within Javascript code?

I am using Rails 3.0.5
I have a javascript code that uses jQuery dropdown checklist and I would like to have the checkboxes displaying which item is checked already and which is not, when using my form in the 'Edit' action of my belongings controller.
Basically, it can work like this in Javascript:
$('element').val([1,3,4]);
$('element').dropdownchecklist();
Let us say that in my controller, edit action, I have a instance variable called #selected_items that contains the items that are selected (here: #selected_items = [1,3,4]) and I would like to use the value of this instance variables into my Javascript code, how could I proceed ? How could I access the value of this instance variable in a .js file ?
Many thanks for your answer !
Just write the javascript in your view, and at the appropriate place, print the #selected_items array as json:
app/views/*/*.html.erb
<script>
$('element').val(<%= #selected_items.to_json %>);
$('element').dropdownchecklist();
</script>
You can also use the Gon gem if to_json cannot serialize more complicated objects.
A better and a clean/neat way of handling such requirements is
1.Don't create javascript inside the views not as per the rails
best practices
2.Handle it this way
In your app/views/*/*.html.erb
where you are having the instance variable like (#selected_items) assign it into the options within the helpers something like :sel => #selected_items
In your javascript
<script>
$('element').attr('sel');
$('element').dropdownchecklist();
</script>
I hope it helps!

Categories