Why is my date, when passed to the javascript function performing math operations on the values??
HTML:
<td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>
where Session("ECN") = '1111' and datStart3 = "6/02/2017"
Whenever I click this button, I my ajax request is for:
http://*****/apqp/updateDate.asp?ECN=1111&Date=0.001487357461576599
I want date to = "6/02/2017" (I have also tried replacing the '/' with '-' or 'a' with no luck)
The Javascript function:
function ChangeDate(strECN, strDate)
{
// Get an xmlHTTPRequest object. Jump out with an error if the object can't be created.
xmlHTTP = getXMLHTTPObject();
if(xmlHTTP == null){
alert("Your browser does not support AJAX!");
return;
}
strURL = './updateDate.asp?ECN=' + strECN + '&Date=' + strDate;
// Setup the xmlHTTP object, open it & send the request.
xmlHTTP.open("GET", strURL, false);
xmlHTTP.send(null);
// Display the line items.
window.location.reload();
}
Wow, Im an idiot.
Just realized that I was passing it in as a Integer.
Putting '' around datStart3 in the HTML portion of :
<td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>
fixes it.
Related
I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:
function newoption()
{
var option = "";
while((option.length < 1)||(option.length > 150))
{
var option = prompt("Please enter the option value... ").trim();
}
var add = confirm("You entered " + option + ", are you sure?");
if(add==1)
{
var code = window.location.href.length;
var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{this.responsetext = option;}};
xhttp.open("POST", "../special/new.php", true);
xhttp.send("poll=" + poll + "&opt=" + option);
}
else
{
alert("OK... try again");
}
}
The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?
The code for new.php is:
<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
new_poll_option($connection, $poll, $option);
}
?>
From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.
You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome).
If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.
You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.
I'm trying to create a form on my website where a user has a text field that they can use to enter a registration number. I want the registration number to be added to the end of the action URL so when that page loads I can use PHP to explode the URL and grab the number. Here's an example of what I'm looking for...
<form action="http://mywebsite.com/registrations/123456789">
<input type="text" name="registrationnumber">
<input type="Submit" value="Submit">
</form>
Is it possible to take whatever is entered into the text field called registrationnumber and have it passed to the URL the form directs to? Maybe an easier way is to create a text field that has a button, when the button is clicked the URL is links to is dynamically created by adding the registrationnumber to the end.
Anyone know of a way to do this?
Indeed you don't need a form to make an AJAX call. A simple input and button will suffice.
I have made a function that will make AJAX call, it will convert the object params containing all key/value pairs of the parameters you want to send to PHP, and concatenates it into a URL string:
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
Assuming you have an input field:
<input id="code" type="text">
<button id="sendData">Send</button>
Here's how we can use the function ajax:
function sendData() {
parameters = {
inputValue: document.querySelector('#code').value
};
ajax('target.php', parameters, function(response) {
// add here the code to be executed when data comes back to client side
// e.g. console.log(response) will show the AJAX response in the console
});
}
You can then attach the button to sendData using an event listener:
document.querySelector('#sendData').addEventListener('click', sendData)
I have to click twice for the activation/deactivation of a user for some reason. Obviously I dont want that, it should be enough with one click. What am I doing wrong here?
(I am guessing that it's something wrong with the AJAX call)
C#:
var toggleUrl = "AdminListUsers.aspx?column=" + (IsClicked.FirstOrDefault().Key ?? "Name") + "&direc=" + (IsClicked.FirstOrDefault().Value) + "&a=chstat&q=" + id.ToString() + "&d=" + disabled + "&z=" + Server.UrlEncode(txtSearchFor.Text);
var hl = new HyperLink();
hl.Text = status;
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = toggleUrl;
hl.Attributes.Add("onclick", "loadDoc();return true;"); //Calling the function here
cell.Controls.Add(hl);
tr.Cells.Add(cell);
cell = new TableCell();
cell.Width = new Unit("10%");
cell.Controls.Add(new LiteralControl("<nobr>"));
var linkbtn = new HyperLink
{
NavigateUrl = toggleUrl,
Width = 16,
Height = 16,
CssClass = disabled ? "user-status-disabled" : "user-status-enabled"
};
linkbtn.Attributes.Add("id", "aButton_" + id);
linkbtn.Attributes.Add("onclick", "loadDoc();return true;"); //Calling the function here
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl(" "));
JavaScript:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
window.scrollTo(window.pageXOffset, window.pageYOffset);
window.location.reload();
}
};
xhttp.open("GET", "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+", true);
xhttp.send();
$('.TellusAlternatingRowColor').load(document.URL + ' .TellusAlternatingRowColor');
}
Image for DataRows
The object you're using to contact the server, the XMLHttpRequest is part of the Ajax concept. Ajax stands for Asynchronous JavaScript and XML. This means that as soon as the request from the URL passed resolves, the event tied to onreadystatechange will be fired. Should the readyState and status be appropriate, your window calls will be resolved, too.
Being asynchronous, the whole browser won't stop because the server hasn't responded yet, the whole program will continue. You can still press the button because of this, but nothing will happen until that request is responded to. Clicking it again is sending another request to your server, which I'm assuming is also resolved, but your calls on window have happened by this point.
I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>
I have what should be a relatively simple task that's frankly got me stumped. I've researched it until my brain is fried, and now I'm punting, and asking you guys for help.
Here's the scenario:
I have an ASPX page (Q2.aspx) that is decorated with the WebService,
WebServiceBinding, and ScriptService attributes.
That page contains a method, GetAllContacts, that is decorated with the WebMethod
attribute and returns a string containing JSON data. (For what it's worth, the page
itself contains no other controls or functionality.)
I have an HTML page that contains JavaScript which uses the XmlHttpRequest
object to invoke the GetAllContacts WebMethod on the ASPX page and transform
the JSON data into an HTML table.
I have verified that my Web.Config file contains the appropriate protocol handlers
for HttpGet and HttpPut in the WebServices section under System.Web.webServices.
I have verified that my Web.Config file contains the ScriptModule entry under the
System.webServer.modules section, and that it matches the appropriate documentation.
However, when I view the HTML page in a browser, the following occur:
The web request goes through, but the results are for the unprocessed HTML from the ASPX page.
The GetAllContacts method is never invoked, as evidenced by setting a breakpoint in its code.
The code to invoke the Web service, however, is invoked, and the JavaScript callback
function that is invoked upon request completion is properly invoked.
It appears that the JavaScript code is largely set up correctly, but for some reason that is completely escaping me at this point, the HTML page will simply not execute the WebMethod on the ASPX page, and simply returns the page as though it were a plain HTML GET request. Clearly, an HTML document can't be evaluated by JavaScript's eval function, which brings me to my problem. (Also note that the JSON data appears nowhere in the HTML that's returned.)
I am, frankly, baffled. I've looked at dozens of Microsoft articles, StackOverflow posts, CodeProject articles, and who knows what else. My code looks like it's okay. But I know better. I'm missing something simple, stupid, and obvious. I just need someone to point it out to me.
Below you'll find the ASPX page code and the HTML code, in the hope that they'll shed some light.
ASPX Code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
<body>
<form runat="server" id="frmMain"/>
</body>
</html>
-- Codebehind
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace Satuit
{
[WebService(Namespace="http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public partial class Q2 : Page
{
[WebMethod]
public static string GetAllContacts()
{
return LoadJsonData();
}
private static string LoadJsonData()
{
using (var stringWriter = new StringWriter())
{
string xmlUri = HttpContext.Current.Server.MapPath("\\XmlData\\Contacts.xml");
string xslUri = HttpContext.Current.Server.MapPath("\\XmlData\\Q2.xsl");
using (var xmlTextReader = new XmlTextReader(xmlUri))
{
var xpathDocument = new XPathDocument(xmlTextReader);
var xslTransform = new XslCompiledTransform();
xslTransform.Load(xslUri);
xslTransform.Transform(xpathDocument, null, stringWriter);
return stringWriter.ToString();
}
}
}
}
}
HTML Code
var objectData; // Receives the objectified results of the JSON request.
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("GET", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200)
{
var jsonResultBuffer = xmlhttp.responseText;
objectData = eval(jsonResultBuffer);
DisplayTable();
}
}
};
xmlhttp.send(null);
function DisplayTable()
{
var sHtml = "";
sHtml = "<table><tr><th>ID</th><th>First</th><th>Last</th><th>Address</th></tr>";
for(i = 0; i < objectData.length; i++)
{
sHtml += "<tr>";
sHtml += "<td>" + objectData.ID;
sHtml += "<td>" + objectData.firstName + "</td>";
sHtml += "<td>" + objectData.lastName + "</td>";
sHtml += "<td>" + objectData.address + "</td>";
sHtml += "</tr>"
}
sHtml += "</table>"
document.getElementById("divTable").innerHTML = sHtml;
}
</script>
Dev Environment Details
Vista Ultimate SP 2
Visual Studio 2008
.NET Framework 3.5
Solution has not yet been deployed, so it's running in the "local Web server"
provided by Visual Studio. (Makes me wonder if I shouldn't just deploy IIS
under Vista.)
Note that the ASPX page containing the WebMethod and the HTML page reside within
the same solution.
I think we need to call web method with POST request
try changing this part of code
xmlhttp.open("POST", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var jsonResultBuffer = JSON.parse(xmlhttp.responseText);
objectData = jsonResultBuffer.d;
DisplayTable();
}
};
Response is returned in JSON format with "d" as the key in xmlhttp.responseText
Pls try the following using jquery to see the web service is accessible or not.
$.ajax({
type: "POST",
url: "Q2.aspx/GetAllContacts",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("success");
},
error: function(response, aa) {
alert("fail");
}
});
Thurein