ajax inserting null values into SQL table (POST method) - javascript

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));

Related

How to send data from PHP into an HTML article

In my HTML I have an article containing clickable lists. I also have a form that adds data to my database. Once it's done adding the data I want my PHP to send a new list based off the data given in the form to the article in my HTML with my other lists.
How can I do this? I know how to display data from PHP in HTML but I don't know how to display that data in existing articles in HTML.
My function that updates and refreshes my page after every click on a link is called MyFnc and this is the JavaScript for it:
function myFnc(x) {
if (x == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else { //if a link is 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() {
//readyState = 4: request finished and response is ready
//status = 200: "OK"
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "get_data.php?q=" + x, true);
xmlhttp.send();
}
}
And get_data.php is where I display the data from the database to the webpage. I know that displaying the link must be done in get_data since that is where I display everything to the page. But for now I just want to know how to send the data retrieved from add_records and make a list out of it.
This is my article in my HTML:
<article>
<ul class="lists" style="list-style-type:none">
<li>Tiger</li>
<li>Hammerhead</li>
<li>Bull</li>
<li>Great White</li>
<li>Mako</li>
<li>Greenland</li>
<li>Whale</li>
<li>Thresher</li>
<li>Oceanic WhiteTip</li>
<li>Goblin</li>
</ul>
</article>
Here is my form in my HTML:
<form method="post" action="add_to_records.php">
<input type="hidden" name="addshark" value="true" />
<fieldset>
<label>Name:<input type="text" name="Name" /></label>
<label>SpeciesID:<input type="text" name="speciesID" /></label>
<label>Genus:<input type="text" name="genss" /></label>
<label>Family:<input type="text" name="famly" /></label>
<label>Order:<input type="text" name="ordr" /></label>
<label>Class:<input type="text" name="clss" /></label>
<label>Create New Shark</label>
<input type="submit" value="add shark" />
</fieldset>
<br />
</form>
Here is my add_to_records.php:
<?php
include 'connect.php';
if (isset($_POST['addshark']))
{
include 'connect.php';
$Namee = mysqli_real_escape_string($connect,trim($_POST['Name']));
$specID = mysqli_real_escape_string($connect,trim($_POST['speciesID']));
$gens = mysqli_real_escape_string($connect,trim($_POST['genss']));
$fam = mysqli_real_escape_string($connect,trim($_POST['famly']));
$ord = mysqli_real_escape_string($connect,trim($_POST['ordr']));
$cls = mysqli_real_escape_string($connect,trim($_POST['clss']));
if (!mysqli_query($connect, "INSERT INTO Species
(SpeciesID,Genus,Family,Order_,Class)
VALUES ('$specID','$gens','$fam','$ord','$cls')"))
{
die('error inserting new record');
}
//I would like the list it returns to look like this if the Name entered was Hello
//and the speciesID entered was Something
//<li>Hello</li>
//echo "shark was added";
header('Location: ProjectMainAdmin.html'); exit;
}
mysqli_close($connect);
?>
Just use jQuery's AJAX, it's a lot simpler and easier to implement. Data will be passed to server, then once completed you need to append the data into your list.
something like this:
$("form").submit( function(){
$.ajax({
url: "add_to_records.php",
success: function(result){
$(".lists").append("<li><a href=''>" + result.name + "</li>");
}
});
return false;
});

xmlhttp.open does not seem to do anything in MVC structure

I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.

Simple AJAX commenting system

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.

Submitting a form using AJAX

I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>

Submitting a form more than once

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.

Categories

Resources