Boolean value not being passed with jQuery/ $.get - Why? - javascript

I have my front end script which has the following jQuery code:
$.get("/backend/post.php", {
title: title,
message: post,
stick: sticky
}, function (output) {
alert("Call Back");
}
}, "json");
stick is a boolean value, the other two are strings. I've confirmed that they are in fact set. Now on the backend page, using $_GET, title and, message and being passed, but $_GET['stick'] is returning empty, and the PHP function gettype() is telling me it is NULL.
In request to one of the comments:
sticky comes from a form, it's a check box and I just select it with this code:
var sticky = $("input[name=sticky]").attr('checked');
When I use alert() to output the value of sticky, it will return true/false depending on what was selected.
Why is this boolean value not being passed? The JSON site tells me you can have the boolean values true/false in it. But it is not working here for some reason.

I can't be entirely sure because I haven't tested it myself, but I think this is related to how GET requests transfer as strings. Try something like this:
var sticky = $("input[name=sticky]").attr('checked')?"true":"false";
$.get("/backend/post.php", {
title: title,
message: post,
stick: sticky
}, function (output) {
alert("Call Back");
}
}, "json");
It's entirely likely that this won't work, but give it a try.

If in a form an input does not have a value it will not be sent as a parameter. So the absence of of a $_GET['stick'] is equivalent to the query string parameter stick=false. So if you must have a parameter:
var sticky = 'true';
if($("input[name=sticky]").not(':checked')) {
sticky = 'false';
}

Related

Is there a way to hijack what is in the DOM?

When I console.log a value, I get immediate response. But, the html takes time.
I know what the issue is and it has nothing to do with async or anything.
Is there a way to get what you are console.logging without doing a return?
Possibly saving it in localStorage.
"status" comes from third party API where it's boolean.The value changes from true to false based on user input. Which is correct. But, HTML takes time for it to change in timely manner
public elementEvent($event) {
this.isValid = $event.status;
console.log($event.status);
}
//output: true
<div>{{isValid}}</div>
//output: false
So here is what I had to do:
public elementEvent($event) {
this.isValid = $event.status;
this.ref.detectChanges();
}

Retrieve Database record via Javascript

What I am trying to do is retrieve the record (object) in the database that is the most recent in relation to the record that the user is entering. And get a specific property of that object and use it in a simple subtraction conditional statement.
JavaScript:
<script type="text/javascript">
$('#DialogTime').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
"Confirm": function () {
$("#DSCreateForm").submit();
},
"Cancel": function () { $(this).dialog("close"); }
}
});
$('.btnSubmitDS').on("click", function (e) {
// this is where the conditional statement needs to be.
{
e.preventDefault();
$(function () {
$('#DialogHighFlightTime').dialog('open')
});
}
});
</script>
Now, the view that has this script on it, is a form... and once the user hits submit, the record they just submitted will become the last row in the table.. so I need to get the property value from the row above the one the user just entered.
I know how to write the conditional statement.. I just need to know how to retrieve the right record.
I might be going about this all wrong, but I don't know how else to retrieve record that is closest to the record that the user just entered.
Any help is appreciated.
If you have a insert timestamp associated with the records, you may consider sorting the results in descending order,skip the first one (the one just got inserted) and take the first item.
LINQ might be handy.
Something like
var secondLastRecord = db.Issues.OrderByDescending(s=>s.CreatedTime).Skip(1).Take(1);
If you want to limit this to a specific user, you might consider adding other condition with a where clause.
var userIdToCheck=324;
var secondLastRecord = db.Issues.
.Where(c=>c.CreatedById==userIdToCheck)
.OrderByDescending(s=>s.CreatedTime).Skip(1).Take(1);
Assuming db is your DbContext object. If you are using non EF data access layer, you can still use the LINQ OrderByDescending-Skip-Take approach. Replace db.Issues with any IEnumerable<T> which represnts your table data.
Also, to get this in javascript, you need to make an ajax call to server action method where you will execute this code and return it.

Passing javascript event as parameter to Ajax in Lift?

I am trying to implement DirtyForms-style validation library using Lift. What I'd like to do is send the event parameter from a click action to some server-side validation logic. I've found many answers to the problem of passing function arguments to Ajax, but none using Lift.
Here is what I have...
The DirtyField class is a class that keeps track of fields that have been 'dirtied'. Its method isDirty(): Boolean evaluates whether the field value has changed since the page was initialized (this works great).
class DirtyForm(fields: Seq[DirtyField[_]])
{
val popupId = "popup"
private def fieldsDirty(): JsCmd = fields.exists(_.isDirty) match {
case true => Run("""function(e) { e.preventDefault(); $('#""" + popupId + """').dialog(); }""") //prevent them from clicking link if they need to save their data
case false => Noop
}
def seq(): NodeSeq = {
Script(Run("""
$(document).ready(function() {
$(document).on('click', 'a[href]', """ + SHtml.ajaxInvoke(() => fieldsDirty()).toJsCmd + """);
});""".stripMargin)) ++ ConfirmationDiv(popupId) /*div with 'popup' as id*/
}
}
Calling code:
def render = {
//...
val myDirtyForm = new DirtyForm(/*some fields to watch here*/)
"* *+" #> myDirtyForm.seq()
}
Generated javascript:
<script>
// <![CDATA[
$(document).ready(function() {
$(document).on('click', 'a[href]', liftAjax.lift_ajaxHandler("F1336229574104X2J5CL=true", null, null, null));
});
// ]]>
</script>
When this ajax call is invoked on a link click with a dirtied field, I get the following error in the console: The server call succeeded, but the returned Javascript contains an error: SyntaxError: Unexpected token (, which I expect to be because I am trying to use function() where it is not applicable.
TL;DR: My problem revolves around two things:
I want to evaluate whether or not the form is dirty via ajax
If it is dirty, I want to call preventDefault()
Disclaimer: this is my first post, so any suggestions on how to improve the question would be appreciated!

Cannot switch between classes with jQuery

I've got a problem with switching between element classes - probably sth stupid, but I couldn't find the answer.
In my system I display a list of items. Now I want to be able to promote items, so that they appear at the top of the list. I created some backend infrastructure which works ok and added things to my frontend: a star (a span with star bg) next to every item's title and a jQuery script which is supposed to:
listen to 'click' event - when I click on a star
get some data- attributes from the span
post them to my controller
the controller checks if I'm allowed to promote items and replies 'true' or 'false'
if 'true' then I switch between 'gold-star' and 'silver-star' classes of the item
For some reason the classes don't switch - only when I refresh the page I can see the effect. I tried debugging with Firebug - it gets to the toggle line, but then nothing happens.
Here's the code:
<span class="silver-star promote">
$(".promote").bind("click", function() {
var $this = $(this);
var itemId = $this.attr("data-id"),
isPromoted = true;
if ($this.hasClass("gold-star")) {
isPromoted = false;
}
$.post('/promoteitems', { itemId: itemId, isPromoted: isPromoted }, function(allowPromotion) {
if (allowPromotion == true) {
$this.toggleClass("silver-star").toggleClass("gold-star");
}
});
});
Thanks in advance!
When you are getting a response back it might not recognise it as a boolean simple test would be to check response as string
From your comment on the question:
...the allowPromotion value is 'True' (with a capital T)...
That tell us it's a string, not a boolean. You don't want to just do if (allowPromotion), because that will toggle the classes even if you get back "False".
Instead:
if (allowPromotion == "True") { // Note the quotes and capital T
// ...toggle the classes
}
Or if you want to allow for possibly getting back something with a lower-case T at some point in the future:
if (/^\s*true\s*$/i.test(allowPromotion)) {
// ...toggle the classes
}
That's over-engineering it a bit (it'll work with "True", "true", " True " [note the spaces], and even an actual boolean true)...

Why is the JSON results "undefined" in this JavaScript

I am having some issues getting my JS to work right. I am trying to select an option from a dropdown which then calls this function. The function is being called properly (type is set to 'truck' and id is set to 5). I want to then use the data returned to populate several fields. The alert() I added to test gives me "undefined".
Here is my JS:
function getDueDates(type, id) {
$.getJSON("loadVehicle.php",
{
id: id,
type: type
},
function(data) {
alert( "TEST: " + data.year);
$("#inspection_due").val(data.inspection_due);
$("#short_due").val(data.short_due);
$("#full_due").val(data.full_due);
}
)};
When I check the loadVehicle page manually (with id=5, type=truck) I get:
[{"truck_id":"5","status":"A","truck_number":"21","year":"1999","make":"Freightliner","model":"Classic","engine":"Detroit","vin_number":"1FUPCSZB2XPA16977","transmission_number":"","tire_size":"","inspection_due":"2009-04-30","short_due":"0000-00-00","full_due":"0000-00-00","comments":"Caf Inc Truck","web_id":"b963940bfd96528f7fd57c08628221f0","last_update":"2009-03-09 16:26:28"}]
But in the page the alert comes up with "TEST: undefined"
You need data[0].year since you are getting an array containing a single object.
Try data[0].year.
It looks like your loadVehicle.php is returning an array of objects not just one object.

Categories