404 not found - JS not sending variables to PHP - javascript

I am trying to send some variables to PHP script and then to upload them in MySQL db.
Here is my JS script:
$.ajax({
url: '/insert.php',
type: 'POST',
data: {endadres:endadres,stadres:stadres,amount_of_carriers:amount_of_carriers, price_finalized:price_finalized },
success: function(data) {
console.log(data);
}
})
All of variables are extisting inside the same function (I checked it via "alert()").
Here is my PHP code:
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['FirstName']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['LastName']);
$start_adress = $_POST['startadress'];
$end_adress = $_POST['endadress'];
$Price = $_POST['finallprice'];
$CarriersQuant = $_POST['carriersamo'];
// Attempt insert query execution
$post = "INSERT INTO Orders (FirstName, LastName, StartAdress, EndAdress, Price, CarriersQuant) VALUES ('$first_name', '$last_name', '$start_adress', '$end_adress', '$Price', '$CarriersQuant')";
LastName and FirstName are taken from .html, and I can upload them into my DB, but I am not able to get variables from js.
Error from console:

The variable names in the ajax post doesn't correspond with what you try to extract in the receiving end (PHP). If you stick with these names in JavaScript:
data: {
endadres,
stadres,
amount_of_carriers,
price_finalized
},
You must use the same key to collect them in PHP:
$foo = $_POST["endadres"]
To debug, I often find it useful to add this debug output to see all posted variables:
var_dump($_POST);
On a second note (unrelated to your question though), your SQL insert statement is very dangerous. You are concatenating the variables directly from the external request into the database query string, which means that a potential offender could post something like:
carriersamo: "'; DROP TABLE Orders;"
which would drop your Orders table from your database. I recommend you read up on PHP's PDO module, where it's quite easy to prepare "safe" statements to the database. http://php.net/manual/en/book.pdo.php

Related

PHP records not inserted to database using Ajax

here is the AJAX request body
Ajax
var date = new Date().toLocaleTimeString();
var text=this.value;
var id=1;
$.ajax({
type: "GET",
url: "StoreMessages.php" ,
data: { room: id, msg:text,sendat:date }
});
PHP Code
if(isset($_GET['room']))
{
$chatroom_name = $_GET['room'];
if(isset($_GET['msg']))
{
$text= $_GET['msg'] ;
if(isset($_GET['sendat']))
{
$local_time= $_GET['sendat']);
insertMessage( $text,$local_time, $chatroom_name);
}
}
}
function insertMessage($message_body,$local_time,$room_id)
{
echo "<script type='text/javascript'>alert('$message_body');</script>";
echo "<script type='text/javascript'>alert('$local_time');</script>";
echo "<script type='text/javascript'>alert('$room_id');</script>";
$conn = new mysqli($GLOBALS['server'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db_name']);
if($conn==false)
{
die("unable to connect database");
}
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES ('$message_body', '$local_time', '$room_id')";
if(mysqli_query($conn,$sql)){
echo "record inserted successfully"."<br/>";
}
else{
echo "error".mysqli_error($db_conn);
}
Explanation
ajax call triggers when user typed message and hit enter key ajax data field variable contains value i checked then by setting alert when i checked the the data field variables value by setting alert in php code there only text variable contain value and alertbox didn't appears for other variables acutally i am trying to store live chat to database
The first step to debugging this is is/was diagnosing where the failure occurred. To do this:
Open your developer console
Go to the network tab
Make whatever action triggers the AJAX request
Click the request that appears in the network tab
Go to the response tab*
*If the status code of the request is a 500 that also is an indication that the script is failing on the PHP side. Go to the server and look at the error logs.
From the response we got in the response tab we identify the issue to be the trailing closing parenthesis on this line:
$local_time= $_GET['sendat']);
Additionally you should use parameterized queries. A single quote in any of the fields will break your query.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Roughly:
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES (?, ?, ?)";
Then prepare that, bind the values, and execute the query.
Also I'd send back a JSON object rather than JS code. Take a look at http://php.net/manual/en/function.json-encode.php.

Trouble with inserting JS variable into MySQL table with PHP with AJAX

I am a pretty much a beginner to all of these technologies, I have been stuck all day on what I thought would be a fairly simple process. Basically, I'm trying to pass a parameter in a JS function through to my PHP code using AJAX, and then inserting the parameter into my database.
The JS function in my .html file.
function pushData(paramData) {
$.ajax({
url: "databaseStuff.php",
type: "post",
data: paramData
});
}
I wish to insert into my SQL table whatever I have put into the Parameters. For example the below code should create 3 new database entries. I have these hooked up to buttons in my actual project.
pushData('It is Wednesday');
pushData('My Dudes');
pushData('AHHHHHHH!');
databaseStuff.php
<?php
$mysqli = new mysqli("localhost", "root", "default", "testDB");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$paramData = $_POST['paramData'];
$sql = "INSERT INTO testDBtable (Name, Text) VALUES ('Joe', '$paramData')";
?>
My PHP is successfully connecting to the MySQL DB since I am getting the proper 'localhost via TCP/IP' message, however, I am getting stuck on:
"Notice: Undefined index: paramData in C:\wamp64\www\databaseStuff.php on line 23
Help is appreciated! I am not concerned with SQL injection vulnerability as this code will never leave localhost.
Try writing your Ajax data parameters like this
data: {
'paramdata':paramdata
}
Also, you never actually queried your data.
mysqli_query($mysqli, $sql);
But with the error that you're getting, it's likely because of the ajax data parameters.
If you just want to correct your code, replace the AJAX query with this:
$.ajax({
url: "databaseStuff.php",
type: "post",
data: {'paramData': paramData}
});
However, you should not concatenate user input with sql query directly because of SQL injections, I suggest you to use parametrized queries. Here is the PHP manual page with explanation and examples

Sending a JavaScript variable to PHP, use said variable in an SQL statement, then display PHP results

I'm trying to send a JavaScript variable to a PHP script, use the variable in my SQL statement, and then send the results back to JavaScript.
JavaScript:
// Sending a variable to PHP script
var variableToSend = '30';
$.post('myPHPscript.php', {variable: variableToSend});
// Using the variable from earlier, run PHP script to get results
var data_from_ajax;
$.get('http://www.mywebsite.com/myPHPscript.php', function(data) {
data_from_ajax = data;
});
// Display results on the document
var displayResult = document.getElementById('displayResult');
displayResult.innerHTML = data_from_ajax;
PHP:
<?php
// Connection stuff
$conn = new mysqli($servername, $username, $password, $dbname);
// Get the sent variable
$variable = $_POST['variable'];
// Run SQL statement
$sql = "
SELECT column
FROM myDatabase
WHERE id=$variable
";
$result = $conn->query($sql);
// Send results back to JavaScript
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row["column"];
}
?>
The reason that JS is calling a PHP script is because I used an event listener in JS to determine the variable that I want to send. The variableToSend varies every time depending on what was clicked, but I have set it to some random number here.
I'm aware that the problem lies in sending variables to PHP scripts in the JavaScript, but I'm unsure how else I can do this, besides using .post and .get.
I also considered using an AJAX call, but I wasn't sure how that would work.
Thank you for any pointers.
You are already using ajax, twice, via $.post and $.get.
You only need to make the post request, and display the response:
// Sending a variable to PHP script via ajax post, and display the returned results
var variableToSend = '30';
$.post('http://www.mywebsite.com/myPHPscript.php', {variable: variableToSend}, function(responseFromPhp){
$('#displayResult').html(responsefromPhp);
});
The data you want will be returned on this post ajax call. To retrieve it specify success function.
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
and also use some validation and escaping before use post values in mysql:
http://php.net/manual/en/mysqli.real-escape-string.php

Errors when attempting an ajax POST call to PHP to return SQL query variable to jquery

Im trying to trying to return a PHP variable which is made of a SQL query to the same database using jquery.
At the moment my method does not work but i cant figure out why. Currently getting the following messages on the PHP response along with the error alert configured in the js function:
Warning: Illegal offset type line 55
{"average":null}
Im very new to PHP and server side programming, so an explanation of where i am going wrong would be really good. I am sure it is just a really simple misunderstanding i have with how i am going about this.. its baffling me so far though!
javascript function to make ajax call to PHP page
so here i have defined an array and added 2 values to it to post to the PHP page.
once recieved i want PHP to change the value to one it will get by doing an SQL query
var javascriptvalue = []
javascriptvalue["id"] = "the id";
javascriptvalue["name"] = "the name";
function averageRecall() {
$.ajax({
type : 'POST',
url : 'recall.php',
data: JSON.stringify(javascriptvalue),
dataType : 'json',
success : function (result) {
console.log(result); // see too what we get in the request
console.log(result.average);
},
error : function () {
alert("error");
}
PHP:
Here PHP should run a query against the DB and return a single value into the variable $avg which will be passed to an array, coded to JSON and then echoed back into my JS callback function.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$avg = $conn->query("SELECT AVG(`Answer`) AS AvgAnswer
FROM (
SELECT `multi1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi5` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio5` AS Answer
FROM `zc_Answers`
) AS s1");
if (!$avg) {
echo 'Could not run query: ' . mysql_error();
exit;
}
header('Content-Type: application/json');
$avg2 = array('average' => $_POST[$avg]
);
echo json_encode($avg2);
$conn->close();
?>
First , try adding this to your php file because it doesn't return a JSON response :
header('Content-Type: application/json');
$avg = array(
'average' => $avgcalculation // you can try sending just a number to see if the script works excluding your query
);
echo json_encode($avg);
then , in your success function of javascript you have :
dataType : 'json',//So we need to do the header() step in php
success : function (result) {
console.log(result['average'])// ???????
},
You try to get an item of a javascript array by string index ... which is not possible.
1) You write dataType:json <<< So, the result variable is a object ! So you can access average value with :
success:function(result){
console.log(result); // see too what we get in the request
console.log(result.average); // thats all
}
UPDATE : in order to help you ._.
your php script is failing too because you are retrieving POST values that doesn't exist because you are not sending them !
Please read the documentation of $.ajax() here.
Try first with a simple script in php to see if your javascript works. Comment everything just let 2 lines.
header('Content-Type: application/json');
$avg = array(
'average' => $_POST["javascriptvalue"]
);
echo json_encode($avg);
then in your javascript file add the data tag (because you need to retrieve data in your server !)
data:{
javascriptvalue:"I'm sending this to php so it can be retrieved in my php script"
},
Finally your success javascript function should be executed without problem with :
success:function(data){
console.log(data);//an object with average property (data.average)
}
It should work anyway this is not dificult, read the documentation
"data: avg" in the Ajax call is the data you want to send to the PHP (your page form values) that's why "avg" needs to be defined in the javascript before making the ajax call, that's why you get "avg is undefined".
You need to create the variable and somehow fill it with the form values.
For the PHP if it is on a server you need to work a little bit more like Carlos explained.
I give you some example code from a project I'm working on:
JS CLIENT SIDE
//jsonvar is an array
jsonvar["id"] = "the id";
jsonvar["name"] = "the name";
$.ajax({
url: url_webservice,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(jsonvar), //turn jsonvar into json to send to the php server
})
.done(function(result) {
console.log("Show the result from the PHP in the console", result);
// Do all you want with the result
})
.fail(function(err) {
console.log(err.responseText);
// Do all you want in case of error
});
});
PHP SERVER SIDE
header('Content-Type: text/html; charset=utf-8');
//Get the data from the POST
$input_data = json_decode(file_get_contents("php://input"), FILE_USE_INCLUDE_PATH);
if(is_null($input_data))
{
trigger_error('Error empty input data in server.php', E_USER_WARNING);
}
//Do what you want with input data, sorry not familiar with mysql code.
echo json_encode($result); //Back to the client

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

Categories

Resources