inserting data, sent from javascript using POST, into mysql database using php - javascript

I have been trying to insert data into a table in a mysql database. This data was sent with ajax using the POST method. However, when I try to insert it into the database nothing happens.
So here is the javascript function the sends the data to the php file.
addToCart: function(itemId,userId){
let request = new XMLHttpRequest();
request.open("POST", "../E-CommerceCore/addToCart.php?
itemId="+ itemId + "?userId=" + userId, true);
request.send();
},
Here is where it is being used. This is nested in a bigger function so thats where the book[i].Id comes from.
document.getElementById('add-to-cart').onclick = function(){
cartFunctions.addToCart(book[i].Id, '1');
};
So this takes an item id and a user id and stores them in a php variables here.
class Cart
{
public function addToCart($item,$user){
include 'connect.php';
$query = $bookStore->prepare("INSERT INTO cart SET item_Id=?, user_Id=?");
$query->execute([$item,$user]);
}
}
$cartManager = Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];
$cartManager->addToCart("$itemId","$userId");
This php file then runs the addToCart function which should insert it into the table. This is where I run into the problem because not data is inserted to the database when the user clicks the button. I use the connect.php file for another controller that selects from a different table in the same database, if that is an issue, and yes I have checked to make sure that the connection to the database is good. Any insight would be immensely appreciated. Please no jQuery solutions. Thank you for you time and effort.

request.open("POST", "../E-CommerceCore/addToCart.php? itemId="+ itemId + "?userId=" + userId, true); You are sending the parameters as GET with the url and you have another mistake since you used another ? to separate the 2 parameters . Please follow this link to send your data: Send POST data using XMLHttpRequest
var http = new XMLHttpRequest();
var url = "path_to_file.php";
var params = "itemId="+ itemId + "&userId=" + userId; //Please note that the 2 params are separated by an **&** not a **?** as in your question
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Also the quotes here are unnecessary when passing parameters:
$cartManager->addToCart("$itemId","$userId");
If it is possible try to var_dump($_REQUEST) before calling the addToCart method to make sure that parameters have been successfully sent through the javascript request.
Now regarding the sql query you have to update the class and use bindParam and afterwards call the execute. I have updated your php code as follows:
class Cart{
public function addToCart($item,$user){
include 'connect.php';
$query = $bookStore->prepare("INSERT INTO cart SET item_Id=:item_id, user_Id=:user_id");
$query->bindParam(':item_id', $item);
$query->bindParam(':user_id', $user);
$query->execute();
}
}
$cartManager = new Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];
$cartManager->addToCart($itemId, $userId);
For more reference regarding prepared statements you can have a look at this: http://php.net/manual/en/pdo.prepared-statements.php

Related

How to handle POST form data with Django (refresh avoided)?

I'm trying to save the form's data in a database using Django. Refreshing after click on submit button is avoided using:
scripts.py
var form = document.getElementById("mail_form_id");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
function send_mailform(){
console.log("cal")
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + document.getElementById('mail_input').value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
document.getElementById("mail_send_btn").addEventListener('click', send_mailform, false);
views.py
#Mail check
if request.POST:
Marketingform = Marketingforms(request.POST)
if Marketingform.is_valid():
receiver_mail = Marketingform.cleaned_data['receiver_mail']
p = mail_receiver(receiver_mail=receiver_mail)
p.save()
print("correct")
views.py
class mailForm(forms.ModelForm):
class Meta:
model = mail_receiver
fields =[
'receiver_mail',
]
widgets = {
'receiver_mail': forms.EmailInput(attrs={ 'id':'mail_input', 'name':'mail_input'}),
}
How can I receive the value of params in the django views.py?
First your ajax request is not going to work because of csrf token. you must have a request header with name: 'X-CSRFToken' and value of the csrftoken cookie that is in the browser cookies. You must get the csrftoken cookie value and set as the header value.
Header should look like:
http.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
And getCookie() must be function to get cookie value based on its name. Django has a clean doc about this: https://docs.djangoproject.com/en/3.0/ref/csrf/
And the answer for your question is that request object contains the post data and you can have them like:
request.POST.get('param_name')
This will return None if param_name doesn't exists.
Also its better to check like:
if request.is_ajax():instead of if request.POST:

Why is my ajax request repeating same data from Laravel controller?

Goal: load more rows from the database to a view using an ajax request when a user clicks the "load more" button. I would like the data to load without a page reload.
Problem: The data being loaded via ajax keeps repeating the same rows on every request and doesn't paginate as per standard request.
Detail: I have a view that loads 4 rows from the database which I paginate using Laravel's built-in pagination. I've added an event listener on a "load more" button which successfully sends the request to the controller, which in turn successfully returns data. The controller returns a partial view of the data I want to display. However this data doesn't seem to increment properly and keeps repeating the records shown on each request. I am not sure what I am missing here, if the problem is in the controller or in the JS?
I am not very experienced with Laravel, PHP and JS since coming from more of a web designer and UI design background and would love to really understand what I am doing wrong here.
PLEASE NO JQUERY EXAMPLES.
Partial view:
#foreach ($products as $product)
<div style="background-color:pink; width: 200px;">
<p>{{ $product->title }}</p>
<img src="/images/product/{{ $product->img }}" alt="{{ $product->title }}" style="width: 50px;">
</div>
#endforeach
Javascript:
(I am updating the button href attribute so the request URL reflects the correct query)
const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
let url = button.getAttribute('href'); // http://127.0.0.1:8000/sandbox?page=2
let pageNum = button.getAttribute('href').substr(35,1);
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// if page loads successfully, replace the number at the end of the url with the incremented page number
pageNum++;
newUrl = url.replace(/page=([^d]*)/, `page=${pageNum}`);
button.setAttribute('href', newUrl);
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
Controller:
public function sandbox(Request $request)
{
$products = Product::orderBy('title', 'asc')->paginate(4);
if($request->expectsJson()){
return view('sandbox-more', compact('products'));
} else {
return view('sandbox', compact('products'));
}
}
Consider this snippet for your javascript
const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
let url = button.getAttribute('href');
let pageNum = button.getAttribute('data-page-number') || 0;
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// if page loads successfully, replace the number at the end of the url with the incremented page number
pageNum++;
newUrl = url + '?page=' + pageNum;
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText);
button.setAttribute('data-page-number', pageNum);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
What I've done here is to have the page number saved to a dedicated custom attribute "data-page-number". Doing "button.getAttribute('href').substr(35,1)" is inefficient. And then check the page number and increment it on the button's click event. Also, only update the "data-page-number" attribute when the request has been successful. I hope this helps
You should regenerate the pagination every time you make a request to get the correct data. Here is a very good example on doing it via jQuery. Should just adjust it to your needs since you are using pure Javascript.

PHP is shown on wrong page

I'm recently working on a website project. Therefor I have a website.php with all html code, a function.php and saveArray.js . In website.php I'm printing a html table with a button at the bottom. Through the button click I'm getting to the saveArray.js, where I save all the table data in an array.
With this code
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'function.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
request.send('daten=' + arrString);
I post the JS array to function.php. In function.php I do something with the array and in an if statement I want to show a modal.
The modal itself works, but I want to show it on website.php page. Which doesn't happends, because I'm currently on function.php .
How can I solve this ?
EDIT: In my array is an ID and I want to check if this ID is already in my database or not. Depending on this result I want to show the modal and upload the data if necessary. All the checking is happening in function.php
I suppose you want to inject the string returned (the modal PHP code) by your function in function.php in your current page ('website.php').
To do this, you'll have to inject the response given by the XMLHttpRequest when the request is finished.
Let's suppose we want to add all the contents within
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
See, You are not handling the response of the request.So handle the response.and restuern the status of the request from function.php and if data is saved the open the model. You need not go to the function.php page. See the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is response of the request //now check it
//Suppose you returned " data saved" as response from function.php
if(this.responseText='data saved'){
//Open model here
}
}
};
xhttp.open("POST", "function.php", true);
xhttp.send();

XMLhttprequest.send() doesn't send variables to PHP

I have this code.
JAVASCRIPT
function removeAndReplace(id, sezione){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send("id=" + id + "&sezione=" + sezione);
}
PHP
print_r($_POST);
$id = $_POST['id'];
$sezione = $_POST['sezione'];
.
.
.
HTML
<input type="button" value="Elimina" class="btn_elimina" onClick="removeAndReplace(1, 'Shopping')">
I want to call a PHP function after the button click so I read that the better way is to use AJAX.
Firefox and Chrome return this error message:
Array
(
)
Notice: Undefined index: id in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 6
Notice: Undefined index: sezione in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 7
Line 6 is: $id = $_POST['id'];
Line 7 is: $sezione = $_POST['sezione'];
Where am I going wrong?
You are dumping your data into the request body without telling the server how it is formatted.
Since PHP doesn't know you have sent it data in an encoding it understands, it ignores the request body.
You need to add:
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
… before you send the request.
Aside
While your hard coded data is free of special characters, it is best practice to encode your data. This will save you headaches in the future:
xhttp.send("id=" + encodeURIComponent(id) + "&sezione=" + encodeURIComponent(sezione));
You can save yourself the trouble of manually encoding the data and having to set your own content-type by using the FormData API:
var data = new FormData();
data.append("id", id);
data.append("sezione", sezione);
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send(data);

Passing a JavaScript value to PHP on completion of quiz

I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});

Categories