I am trying to pass several variables from a php page into a java script. However only the first parameter is being passed.
The php page calls the script like this:
<?
$sdate = 0;
$edate = 2;
?>
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid('<? echo $sdate; ?>', '<? echo $edate; ?>');
};
</script><BR>
The Java Script being called is:
function DatabaseGrid(sdate, edate)
{
this.editableGrid = new EditableGrid("demo", {
enableSort: true,
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid(sdate);
this.fetchGrid(edate);
}
DatabaseGrid.prototype.fetchGrid = function(sdate, edate) {
// call a PHP script to get the data
alert("loaddata_dailyotp.php?o=" + sdate + "&e=" + edate + "");
this.editableGrid.loadXML("loaddata_dailyotp.php?o=" + sdate + "&e=" + edate + "");
};
DatabaseGrid.prototype.initializeGrid = function(grid) {
grid.renderGrid("tablecontent", "testgrid");
};
I added the alert window to show the exactly what was being requested. I was expecting this:
loaddata_dailyotp.php?o=0&e=2
However what I am getting is:
loaddata_dailyotp.php?o=0&e=undefined
Why is my second parameter not going through?
You are not passing the "edate" parameter to your fetchGrid() call. That's why it's displayed as "undefined". For some reason you're calling fetchGrid() two times instead.
You could do it the following way:
<script type="application/json">
var payload = <?= json_encode(array('sdate' => $sDate, 'edate' => $eDate)); ?>
</script>
and then call your script:
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid(payload.sdate, payload.edate);
};
</script>
Call fetchGrid like this
function DatabaseGrid(sdate, edate)
{
this.editableGrid = new EditableGrid("demo", {
enableSort: true,
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid(sdate, edate);
}
You missed to pass the second parameter.
I am sharepoint developer. I faced the same issue in one my application where i was passing two values and only first value was reaching the other end. even alert box was showing two values.
Issue was only last values was not reaching other end so CRAZY SOLUTION was to pass 3 parameters, 3rd being test param so my two params were reaching other end and 3rd param which was anyways useless was getting neglected automatically.
Suggestion in your case :
Please check with THREE parameters whether you are still getting only 1 param or
params ;)
Related
I am kinda new to asp.net mvc website with jquery, razor, javascript and html. Right now my actionlink has a problem where I cannot insert the filter part, into ..page/?sortMethod=StartDate
filters?=pending generates from a button (pending is just 1 of the many status)
?sortMethod=StartDate generates from actionlink.
I am trying to make them work together to get:
..page/?filters?=pending&sortMethod=StartDate
I tried to do a script that tries to replace the
This is the initial code, sortMethod is a string.
<script>
$(function () {
$("#filterUidClear").click(function () {
$("#filterUid").val('');
});
$('#filterPending').checkboxradio();
$('#filterDirect').checkboxradio();
$('#ApplyFilter').click(function () {
var params = "";
if ($('#filterPending')[0].checked) {
params = "filters=pending";
}
if ($('#filterDirect')[0].checked) {
if (params !== "") {
params = params + "&";
}
params = params + "filters=direct";
}
$("#param").val("?" + params);
window.location.href = "?" + params;
});
});
</script>
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate })
This is the new modified one
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate }, new { id = action })
<script>
$(function() {
$('#action').click(function() {
var filterparam = $("#param").val();
this.href = this.href + '?filters=' + encodeURIComponent(filterparam) + '&sortMethod=' + #ViewBag.StartDate;
});
</script>
I am trying to make them work together to get:
..page/?filters=pending&sortMethod=StartDate but to no avail.
The table will display filtered with pending results and sorted by date
Right now it displays ..page/?action&sortingMethod=StartDate
the table shows sorted by date but no filter and action is not being replaced by filter type e.g. ?filters=pending
I have an object from FullCalender
events: [
<?
$sql = "Query removed";
if ($result=mysqli_query($link,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_assoc($result))
{
echo " {
title: '".$row['eName']."',
backgroundColor: 'green',
start: '".$row['scheduledDate']."',
eventID: '".$row['eID']."'
}, " ;
}
// Free result set
mysqli_free_result($result);
}
?>
],
eventClick: function(event) {
$('#modifydialog').dialog('open');
$("#notes").val(event.eventID);
var eID = event.eventID;
}
I am trying desperately to make an object (the event.eventID into a global variable so I can use it here:
var eID = '';
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'checkDelete.php?sID=<?echo $sID;?>&eID='+eID, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
Basically, I'm trying to take the value, and pop it into the ajax url for the get statement - I am open to suggestions if there are better ways. Thank you for any advice.
I think you can use:
'checkDelete.php?sID=<?echo $sID;?>&eID='+$("#notes").val()
that is if the value of this element won't be changed in the meantime. You can also declare eID in the global scope and use eID = event.eventID; to set it.
var eID;
events: [
....
],
eventClick: function(event) {
.....
eID = event.eventID;
}
you can even do this:
window.eID = event.eventID;
Ok so the scenario is currently I am populating a drop down list from my model with the following code
ViewBag.LeaseCompanyID = new SelectList(ContractModelEntity.system_supplier.Where(x => x.Type == "Lease"), "CompanyID", "Name", data.LeaseCompanyID);
This works perfectly, however on my form I have a button located next to the drop down list which adds another option in the database, using ajax and a modal popup.
The controller code for this is here
[HttpPost]
public JsonResult AddSupplier([Bind(Include="Name,Type")] system_supplier data)
{
if (ModelState.IsValid)
{
ContractModelEntity.system_supplier.Add(data);
ContractModelEntity.SaveChanges();
return Json(0, JsonRequestBehavior.AllowGet);
}
return Json(1, JsonRequestBehavior.AllowGet);
}
When the new option is added into the database I then need to refresh my dropdownlist to get this new data (currently if I refresh the page I can see the new option). I am using minimalect plugin for the drop downs.
Does anybody know a way of updating this minimalect list, there must be a way of building the list through an ajax call which returns some JSON data.
Thanks in advance for your help
OK so after doing a bit of research here is my solution, hopefully it will help other poeple. Someone might even have a cleaner solution.
I first created a jsonresult controller method which looked like this
[HttpGet]
public JsonResult RetreiveSuppliers(string contractType)
{
var supplierData = ContractModelEntity.system_supplier.Where(x => x.Type == contractType);
var result = new List<object>();
foreach (var x in supplierData)
{
result.Add(new { Id = x.CompanyID, Name = x.Name });
}
return Json(result, JsonRequestBehavior.AllowGet);
}
That got me the data from the database. then I created a javascript on the page which looks like this
$("body").on("click", "#btn_InsertNewSupplier", function () {
var supForm = $("#addSupData");
$.ajax({
url: "#Url.Action("AddLeaseSupplier", "Contract")",
data: supForm.serialize(),
type: "POST",
success: function (result) {
if (result === 0) {
var inst = $.remodal.lookup[$('[data-remodal-id=modal_AddSupplier]').data('remodal')];
inst.close();
NotificationAlert("success", "New Supplier Created");
GetNewSupplierList();
} else {
NotificationAlert("error", "Failed Adding New Supplier");
}
}
});
});
function GetNewSupplierList() {
var actionurl = "#Url.Action("RetreiveSuppliers", "Contract", new { contractType = "Lease"})";
$.getJSON(actionurl, tempdata);
}
function tempdata(response) {
if (response != null) {
var html = "";
for (var i = 0; i < response.length; i++) {
html += '<option value="' + response[i].Id + '">' + response[i].Name + '</option>';
}
$("#LeaseCompanyID").html(html);
}
}
So once the ajax call is successful it will trigger the GetNewSupplierList function which calls my controller method and returns some JSON data. Once that is returned it calls tempdata, which builds the new HTML for my select picker, once that is built it updates the html on the selectpicker id.
Works like a charm!!!
Thanks to everyone who took a look at this post.
I'm sending a value to another page. If there is results from a sql query I want to display in an overlay. If there is no results do not display the overlay.
What's happening is that the overlay pops up whether there are results or not. I'm new to this style of version of posting with jquery. I'm used to 'spelling it out' via $.ajax({}); or plain php.
This is my jquery:
$(document).ready(function ()
{
$("#signup").overlay();
$('#status').change(function()
{
whoclock=$('#associate').val();
$.post("ckrd_messsys.php",{asso:whoclock},function(result)
{
if(result)
{
$("#signup").overlay().load();
$("#signup").overlay({mask: '#999', fixed: false,load:true});
$("#spellout").html(result);
}
});
});
$("#confirm").click(function()
{
$.post("ckrd_messsys.php",{asso:whoclock,confirmread:"Y"},function(result)
{
$("#signup").overlay().close();
});
});
});
This is my php:
$asso = $_REQUEST['asso'];
$confirmread = $_REQUEST['confirmread'];
$getmess = mysql_fetch_array(mysql_query("SELECT `file` FROM `foo` WHERE `empl`='".$asso."' ORDER BY `id` ASC",$con));
if($asso != "")
{
if(file_exists("message/".$getmess[0].".txt"))
{
$txtfile = fopen("message/".$getmess[0].".txt", "r") or exit("Unable to open file!");
$readIT=fgets($txtfile);
echo $readIT;
fclose($txtfile);
}
}
If there is no txt file I do not want the overlay to load. How do I tell the jquery there is no 'file' or 'result' and not to load?? (Sorry for all the edits....just seems I'm not getting the answers/help I'm after.)
Can I just simply add to my php page:
else
{
echo "NOTHING";
}
Then change my jquery to something like:
if(result != "NOTHING")
{
....
}
I've tried this and it didn't work.
I got some observations:
1. I never used before that overlay plugin but seems like the load property fires the overlay if true so there is no need to put at first $(selector).overlay() and later invoke $(selector).overlay().load() It doesn't make sense if you specify the property at first.
2. I think will be good to check the callback response object (result). Sometimes, when implementing a rest or something else, you can return JSON, XML, string, html, etc but in general it is supposed that result is a javascript object, something similar to this:
Object: {} (if empty) or Object: {name: 'Oscar'} (with data)
So, I think what you are checking when doing your conditional if(result) { ... } is to determine if the variable is false or undefined but you are not considering if its empty or not AND! when evaluating an Object: {} as your result variable, it will pass the condition as "true".
What you can do is using the $.isEmptyObject function from jQuery when evaluating your Object as the following code I've implemented for testing.
Check this out.
Live demo: http://jsfiddle.net/oscarj24/34m2R/5/
HTML:
<div id="signup">
<input class="btn" type="button" value="Make ajax call (no results)"/>
<input class="btn" data-type="wr" type="button" value="Make ajax call (with results)"/>
</div>
jQuery:
$(document).ready(function() {
/* In this case, this is the function that replaces
* your on 'change' event handler
*/
$('.btn').on('click', function() {
var type = $(this).data('type');
makeAjaxCall(type);
});
});
/* This makes the ajax calls.
* #param {type} if 'wr' will add some extra
* data to the response obj.
*/
function makeAjaxCall(type) {
$.post('/echo/json', function(data) {
if(type === 'wr') { // wr: simulate data with results
data.name = 'Oscar';
}
if(!$.isEmptyObject(data)) {
makeOverlay($('#signup'), data);
}
}).fail(function(r) { // ajax call failed (you can test this by replacing URL)
var code = r.status;
var error = r.statusText;
alert('Error: ' + code + ', ' + error);
});
}
/* This will make the overlay with
* predefined cfg.
* #param {elem} affected element
* #param {data} callback response object
*/
function makeOverlay(elem, data) {
var cfg = {
mask: '#ccc',
load: true
};
elem.overlay(cfg);
elem.html('<b>Hello ' + data.name + '!</b>');
}
You probably always have a result object from the response, just with different properties.
I usually always return the json property success=true. Then I check:
if(response.success===true) { }
Why not add debugger; in the javascript and check the result object in your browser?
This is my code where I call the Request for Ajax, than a simple input button which on onClick event send some data to a function called setValue();
This is the code (JS):
//request for ajax XML
<script type='text/javascript'>
function callAjax(){
var XMLObj = false;
if(window.XMLHttpRequest)
XMLObj = new XMLHttpRequest();
else if(window.ActiveXObject)
XMLObj = new ActiveXObject('Microsoft.XMLHTTP');
if(!XMLObj)
return false;
return XMLObj;
}
//var for ajaxobject handle;
var objAjax = callAjax();
function setValue(value, id, num, item){
if(objAjax){
if(objAjax.readyState == 4 || objAjax.readyState == 0){
objAjax.open('POST', 'addview.php', true);
objAjax.send('value=' + val + '&id='+id+'&num='+num+'&item='+item);
}
}
}
//input for sending value to function setValue();
<input type='button' onClick='setValue(1, 2, 3, 4)' />
//and this is where I handle the sent data via php
<?php
if(!$_POST['value'] || !$_POST['id'] || !$_POST['num'] || !$_POST['item'])
exit();
include('config.php');
$value = mysql_real_escape_string($_POST['value']);
$id = mysql_real_escape_string($_POST['id']);
$num = mysql_real_escape_string($_POST['num']);
$item = mysql_real_escape_string($_POST['item']);
mysql_query("UPDATE `window` SET window_val = window_val + ".$value." WHERE window_id = '".$id."' AND window_num = '".$num."' AND window_item = '".$item."' ") or die(mysql_error() );
mysql_close($con);
?>
The php script is working, I tried it with sending data manually ($_GET['']) and it's working. Also I checked the URL with alert('value='+value+'&id='+id...) and all variables are Ok, but the database won't be queried.
If you see, I don't add any function for response, reply from the server. I just only want to send those data and query the data base.
Thank you !
You may be missing
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Consider improving your function names: callAjax doesn't call Ajax, it returns a reference to the XHR object. Call it getXhr or something more like what it's actually doing.
If you're ok with jQuery, just call
function setValue(value, id, num, item){
$.post('addview.php', 'value=' + val + '&id='+id+'&num='+num+'&item='+item);
// or the cleaner version
$.post('addview.php', {value: val, id: id, num: num, item:item});
}