I'm trying to make a simple AJAX commenting system. I'm not experienced with it. Here's my code:
function sendComment() {
var obj = { //make an object to send via ajax
values: [document.forms['commentform']['getpage'].value, document.forms['commentform']['commentname'].value, document.forms['commentform']['writingcomment']]
};
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else { // code for IE6, IE5
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open('POST', '/postcommentwritings', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(obj)); //stringify the object to send via ajax
}
<div class="comments-section">Comments</div> <a id="reader-delete-btn" class="menu-reader-viewer">…</a>
<div class="comments-container">
<div class="comments-container-child">
<form name="commentform" onsubmit="return validatecomm()" method="POST">
<input type="text" name="commentname" placeholder="Optional: give yourself a name">
<br>
<textarea name="writingcomment" id="writeComment" placeholder="comment.."></textarea>
<input type="hidden" name="getpage" value=<%=story.ID %>>
<input type="submit" onclick="sendComment()" value="submit">
</form>
</div>
</div>
and this is the server side node.js code for the route responsible for posting the comment and saving it to the database but it's too long and unnecessary so I'll just be putting the new code which screwed things up:
router.post('/postcommentwritings', function(req, res){
var commentsObj = {
post_ID : false,
name: "",
comment: false
}
var getObj= JSON.parse(obj);
for(x in getFoo){
commentsObj['post_ID'] = getObj[x][0];
commentsObj['name'] = getObj[x][1];
commentsObj['comment'] = getObj[x][2];
}
Then I continue with my normal code which works perfectly. But the problem is with either the ajax script on the HTML or this part of the code in the route. I genuinely don't know. The error only tells me "cannot look up view error". It's an ejs error so I suppose the problem might be with the front end part. Something else that might maybe help is that the route /postcommentwritings gets me a status of 500 in the node command prompt. It doesn't get connected to. So to those who're experienced with AJAX what is the problem and how do I fix it? Thank you all in advance.
Related
Im trying to insert data from inputs into an SQL table via an Ajax request.
The Ajax request itself seems to work, but it doesn't get the inputs value before inserting a new line into the SQL table : a new line is indeed added, but all other values are set to default except for the time and date which is correct.
I looked for many tutorials to check I did write my Ajax function properly but all I found were jQuery Ajax tutorials, so I don't really know what I'm doing wrong here.
HTML :
<form method="POST">
value1: <input type="text" name="value1" maxlength="4"> <br>
value2: <input type="text" name="value2" maxlength="4"> <br>
value3: <input type="text" name="value3" maxlength="4"> <br>
</form>
<button onclick="send_ajax()"> Send</button>
Ajax function :
function send_ajax() {
console.log('function clicked');
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('data sent');
}
}
xmlhttp.open('POST', 'filled_inputs_test.php', true);
xmlhttp.send();
}
Any idea what I'm doing wrong ?
Note : considering that my php file works perfeclty when called via submit button without using Ajax, I think the problem comes from Ajax not getting my inputs value before calling the php file.
I didn't add the php code because it's quite long, but please let me know if you need to check it
You're trying to send empty request. Try to change send section to this:
xmlhttp.send(new FormData(document.getElementsByTagName('form')[0]));
You're not sending the input values in the AJAX call. Use:
xmlhttp.send("value1=" + encodeURIComponent(document.querySelector("input[name=value1]").value) +
"&value2=" + encodeURIComponent(document.querySelector("input[name=value2]").value) +
"&value3=" + encodeURIComponent(document.querySelector("input[name=value3]").value));
I am trying to solve this problem without using jQuery so that I can have a better understanding of how things work.
I am sending an AJAX request to a node server with a JSON object. The server can receive the request and respond but the request body is always empty. I have tried setting the request header to 'application/json' but for some reason this changes the form submission to POST the parameters to the URL, rather than use the Javascript function. If anyone could tell me why that is happening as well it would be much appreciated.
Form
<form onsubmit="sendEmail(); return false;">
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
</form>
Email Function
function sendEmail() {
var emailContent = JSON.stringify(
{
email: $('input[name=fromEmail]').val(),
subject: $('input[name=subject]').val(),
message: $('textarea[name=message]').val()
}
);
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open('POST','/message', true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
}
httpRequest.send(emailContent);
}
Node JS Routing
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// set body parser
app.use(bodyParser.json());
// Process email form
app.post('/message', function(req,res) {
console.log('Request received by email path.');
console.log(req.body);
res.send('{"success": true}')
console.log('Response sent.')
});
I think I understood your problem, what you need is to call the function sendEmail() without doing a postback. Well, for this you will nead a regular html button instead of a form submit. Forms are used to execute server requests to an specific url and generate another postback.
You have two options:
1) Do a client side call using a button and an ajax request (XMLHttpRequest):
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
<button type="button" onclick="sendEmail()">Send</button>
2) Use a form submit and call the service directly form the form. The parameters will be taken from the form and will be sent in the request:
<form action="/message" method="post">
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
</form>
Then in the server side you can access the data using the names you gave to the fields:
fromEmail = req["fromEmail"]
If you are trying to send json response, you need to set the content type of response as json.
res.setHeader('Content-Type', 'application/json');
You can try this:
httpRequest.open('POST','/message', true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.send(emailContent);
Reference:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Writing a basic XML file reader into an HTML page. I am having trouble reading from the XML file. Here's my set up: I have three text fields and a button. When the button is pressed, the request is put in to grab three pieces of XML and to populate the three text fields. However, I am running into trouble with the status of the request. I am getting the status code 0, instead of 200. According to my research (http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/282972), I think it has to do with cross domain blocking. I have tried putting the source XML both locally and on a server.
<html>
<head>
<script type="text/javascript">
function displayQuotes()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
//if (xmlhttp.readyState==4 && xmlhttp.status==200)
//{
document.getElementById("quote1").innerHTML=xmlhttp.status;
//}
}
xmlhttp.open("GET","http://filebox.vt.edu/users/yiuleung/project5/letter.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("quote1").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("quote2").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("quote3").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body>
<div id="quote1" style="margin:0;padding:0;position:absolute;left:65px;top:319px;width:250px;height:16px;text-align:left;z-index:2;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 1</font></div>
<div id="quote2" style="margin:0;padding:0;position:absolute;left:65px;top:389px;width:250px;height:16px;text-align:left;z-index:3;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 2</font></div>
<div id="quote3" style="margin:0;padding:0;position:absolute;left:65px;top:458px;width:250px;height:16px;text-align:left;z-index:4;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 3</font></div>
<input type="button" id="shuffle_button" name="" value="Shuffle" onClick=displayQuotes() style="position:absolute;left:316px;top:228px;width:96px;height:25px;font-family:Arial;font-size:13px;z-index:10">
</body>
</html>
You use xmlhttp.open("GET","letter.xml",true); - it open XMLHttpRequest in async mode. But next two lines of your code expected to work in sync mode. You need to switch to sync mode: xmlhttp.open("GET","letter.xml",false); or (better) to modify code for work in async mode, as in example below:
function displayQuotes()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","letter.xml",true);
xmlhttp.onreadystatechange=function() {
console.info(xmlhttp.readyState,"|",xmlhttp.status,"|",xmlhttp.statusText); // for debugging only
if(xmlhttp.readyState===4&&xmlhttp.status===200) {
// HTTP OK
xmlDoc=xmlhttp.responseXML; // maybe var xmlDoc ???
document.getElementById("quote1").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("quote2").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("quote3").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
};
xmlhttp.send(null);
}
Using XMLHttpRequest in MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
What now is:
A page on localhost, which sends a request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://www.3dfind.ru/site/js.js');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
</head>
<body>
<form method="get">
<div id='searchform'>
<table>
<td>
<input name='q' id='searchinput' type='text' value=''>
</td>
<td>
<select name='type' id='searchselect'>
<option value='1'>Val 1</option>
</select>
</td>
<td>
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
</td>
</table>
</form>
<div id='ResponseDiv'>
</div>
</body>
</html>
Then there js script on the server, which receives the request:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
var params = 'q=' + encodeURIComponent(q) + '&type=' + encodeURIComponent(type) + '&search=' + encodeURIComponent(s)
xmlHttp.open("GET", '/result.php?'+params, true)
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
If the file result.php search on the server, you get a url:
http://3dfind.ru/site/result.php?q=%E4%F4%E4%E4%F4%E4&type=1&search=%CF%EE%E8%F1%EA%21
Also in result.php I accept the GET- request :
$var = #$_GET['q'] ;
$s = $_GET['s'] ;
$typefile = $_GET['type'];
What am I doing wrong ?
Alright my man, I think you're a bit confused. Your HTML contains
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
And your Javascript contains
function MakeRequest()
but you say "Then there js script on the server, which receives the request:"
The Javascript should be on the client and sends the request.
Then I'm not even sure what you're trying to do and what's going wrong. Are you getting errors? Is it supposed to do something that it isn't?
Back to basics: use Firefox and install Firebug. Enable the "console". Open your page and do what you're trying to do. If you have Javascript errors, they'll show in the console. You can open every ajax request in the console as well so you can see if you're getting a server side error.
Yeah, I'm a bit confused what you're asking, here is a reference you may look into for cross-site xmlhttprequests here. There is another good reference to cross-site requests here also
From your other question ("cross-site request") I think I understand what you're trying to do. I think you're trying to get the results from "results.php" which is hosted in a different server.
What you need to do is change your MakeRequest() function. Instead of
xmlHttp.open("GET", '/result.php?'+params, true)
it should be
xmlHttp.open("GET", 'http://URL_OF_OTHER_SERVER/result.php?'+params, true);
Hope this helps.
I am try to have a forum submits more then once when a user clicks the submit button. Why? I am try to add more then one idem to a shopping cart, The shopping cart software I am using doesn't support adding more then one product at a time and I don't want to edit there core code. The hidden forum would have the product ids like '1,2,3' I'd then need the JavaScript to separate the values and post each one using AJAX to the cart. I am not great a JavaScript but I coded what I think should work but its just giving me a alert: 'There was a problem with the request.' twice. I can't see whats wrong with it, any and all help and suggestions are welcomed! Here the code:
JS
<script type="text/javascript">
function testResults (form) {
var product_id = form.product_id.value;
var quantity = form.quantity.value;
var brokenstring=product_id.split(",");
for ( var i in brokenstring )
{
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
var poststr = "product_id=" + encodeURI( brokenstring[i] ) +
"&quantity=" + encodeURI( quantity );
makePOSTRequest('post.php', poststr);
}
}
</script>
HTML
<form action="javascript:testResults(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="product_id" id="product_id" />
<input type="hidden" name="quantity" id="quantity" value="1" />
<br />
<input type="submit" name="button" value="Submit" />
</form>
<span name="myspan" id="myspan"></span>
post.php
<?php
print_r($_POST);
?>
If you want to add two items to the cart shouldnt you be doing two posts with the same item? I can just see one post per item there. You are not taking the quantity into account. But this is not the problem. In this case this is only a logic error.
For the javascript side I would recommend you to use jQuery to treat the ajax stuff because it will make your life WAY easier than regular javascript that might event not work with all browsers.
This is the link related to the POST method of jQuery: http://docs.jquery.com/Post
Hope it helps
It is against all the programming logics to post a form several times instead of having a more complex form. From what I can see or understand from your code you are trying to loop through your splitted (brokenstring) string. Your loop is not constructed where and how it should be. Anyway, if I were you, I would consider migraton to another free cart o the possibility to write one myself. From what I see you will be able to do so with a little bit of help from here.