Inserting into database using ajax , 500 (Internal Server Error) - javascript

In my html I have a simple ajax that's inside a function that gets called on a button press. I want the php script that's called to insert the javascript variable sent into a database.
var myval = 'testuser'; // generated by PHP
$.ajax({
type: 'POST',
url: 'testfile.php',
data: {'variable': myval},
});
In my testfile.php I have tried numerous things to insert into the database but with no luck. I know that ajax is working because doing just the bellow works fine with no errors.
<?php
$myval = $_POST['variable'];
echo $myval;
?>
I tried doing this bellow first with global variables. Then even tried putting in the values manually and I kept getting the 500 error even though I have the exact same code in another script (not being called by ajax) and it works fine.
$db = new PDO('mysql:host='. DB_HOST .';dbname='. test_user, DB_USER, DB_PASS);
So I tried opening it a different way.
$con = mysqli_connect('localhost','username,'pass','newdb');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
and that worked fine. However putting in the global variables causes it not to work.
Then I tried to insert to a table.
INSERT INTO send (user_id)
VALUES ($myval);
and I get a 500 error again.
I try accessing the php file directly (testsite.com/testfile.php) and get a blank page. Viewing source gives me nothing.
What am I doing wrong as to keep getting these errors?

PHP:
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'dbname'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$myval = $_POST['variable'];
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
$query = $pdo->prepare('INSERT INTO send (user_id) VALUES (?)');
$query->bindValue(1, $myval);
$query->execute();
echo $myval;
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
Javascript:
var myval = 'testuser'; // generated by PHP
$.ajax({
type: 'POST',
url: 'testfile.php',
data: {variable: myval},
});
Don't add quotes around the variable name. I've provided a php script that should work the way you want it to, comment back if you still need help.

Related

PHP login algorithm not redirecting to next page (unsure on connection to database)

I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.

D3 get data from database - php sends the data but on javascript null

I am using D3.js to create graphs. I have used d3.json function to get my data. But it is showing null on the Javascript side.
This is my code from HTML page:
<script type="text/javascript">
var id=[];
d3.json("dataread.php", function(data)
{
console.log(data);
});
</script>
On the console it displays null.
The php file code is as follows:
<?php
$user="report";
$pass="report";
$dbh = new PDO('mysql:host=127.0.0.1;dbname=report', $user, $pass);
$query = $dbh->prepare('SELECT run_id from run');
$query->execute();
$data=$query->fetchAll();
$dbh=null;
echo "Hi";
echo json_encode($data);
?>
When the page is loaded, I am getting the php data. I have attached an image showing it.
Please guide where am I going wrong?enter image description here
Try removing the
echo "Hi"
from your code

javascript when you have to pass in an url as a parameter to mysql using jquery ajax and php how to do this and process return data?

I've got a piece of javascript as follows:
$.ajax({
type:"get",
url:"http://www.orc23.com/get.php",
data: { solution: src },
datatype: "json",
success: function(returndata){
alert(returndata);
}
});
And this is the corresponding php file that interacts with mysql:
<?php
$con = mysqli_connect("orc23com.fwdsfawmsdfaysql.com","ssft","dsfss123","cookies");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db($con, "cookies");
$sql="SELECT SOLUTION FROM requests WHERE theurl = '$_GET[solution]')";
$result=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$returndata=json_encode($row);
echo $returndata;
mysqli_close($con)
?>
The variable "src" I am passing in is a URL (string) , so I believe I should be treating it in a different way b/c of the nature of an URL with all its' special characters ,,,, I am running my code and it errors out as a "null" , but when I run the appropriate sql statement query in mysql DB then the DB returns what I am expecting ..... please advise what I may be doing wrong please ?
the sql I am running is this:
SELECT solution
FROM requests
WHERE theurl = 'https://www.google.com/fskdfalkadsl?=sksdkalsk&soccer=uwiw'
;
I know it will return back to me single row with just one column , and know what to expect as the value , but I can't seem to get the "get.php" page to return anything but "null" it seems ....
You get NULL because PHP does not automatically populate the $_GET when it receives JSON formatted data, so there is nothing in $_GET['solution']. You need to capture and decode the input yourself.
Instead of:
$solution = $_GET['solution'];
You need
$data = json_decode(file_get_contents('php://input'), true);
$solution = $data['solution'];
Or something close to it.

How can I send HTML data to PHP using JSON?

I can't seem to understand how to send data from my Client-side HTML to my Server-side PHP (Which already means their not in the same folder and are not running in the server) and only get a Notice of an unidentified variable and a Fatal error: Cannot access empty property.
I tried the methods in W3Schools and still no luck. And just to be sure I tried to copy paste it. Still the same.
So my question is: How can I send this simple Client-side HTML/JavaScript data:-
<script>
function sender(){
obj = "tblname";
// how to send that data to the php server-side.
}
</script>
To this PHP:-
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "mydb");
$result = $conn->query("SELECT * FROM ".$objData);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Using JSON?
If anyone could elaborate and show me a sample it would be great.
Again, I am a noob/newb in using JSON and have no long term background (I just started like a week ago and that had a lot of problems already) and am completely clueless when it comes to this type of client-to-server communication.
I Just need the simple sender code (from the JavaScript) and the receiving code (from the Php) one or two lines will do; with a short description on how they work.
I'm using Windows 7, Wamp3.0.6 and Chrome.
PS: I got that from W3Schools. Yes it didn't work. And please don't be Vague. Thank you!
You can make ajax call form client side to server file and can send data with get method
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "path of your php file",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
})
-_-
Everyone seems to try and over complicate and over think this when the simple answer would have been this code.
function caller(){
myData = "myTbl";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "bring.php?q="+myData,true); //sends myData to the php. You can change the GET to POST if ya want to be extra safe but either way, the php won't care anyways.
xmlhttp.send();
}
The above code is from the client server and sends the data of myData to this Server-side php.
<?php
$q = $_REQUEST['q']; //the receiver of the data. You can use explode() to separate them into pieces and turn it into a jigsaw puzzle if ya want.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} // how to connect is not important in my question but it is important for you to be able to connect to the database.
// now for the important stuff
$sql = "SELECT * FROM ".$q." "; // I had to extend it with a space because sometimes it's misunderstood.
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$outp = array();
while($row=mysqli_fetch_assoc($result))
{
$outp[] = $row;
}
echo json_encode($outp); //sends the data gathered from the database table back to the client as a JSON file, and you are done.
?>
It took me 6 hours worth of studying with a lot of internet surfing and trials and errors.
And like I said; I am a newb at JSON so it's pretty much understood that I don't understand AJAX. Like, AT ALL.
I'm sorry if ya think I sound like an idiot but let's face it, almost all of us were idiots at one point while trying to learn programming. So, I'm surprised why some people are just plain rude here. Thanks. Somehow I'm not really surprised that their also like this here. Makes my internet social life a bit more boring.
So next time, do me a favor and instead of being totally rude, just answer the question if you have one.
You cannot transfer an object via HTTP as it is. You need to transform it into a string you can put into the body of your HTTP-POST Request:
try {
var jsonString = JSON.stringify(anyJsonObject);
//send it to the server
} catch(ex) {
//handle error if anyJsonObject wasn't a valid JSON object. Remember: Not every JS object is a JSON object too.
}
The opposite way is:
try {
var jsonObject = JSON.parse(anyJsonString);
} catch(ex) {
//handle error if anyJsonString was malformed
}

jquery ajax to php script not saving data

I have the following jQuery ajax call to a php script:
actualHtml = $('div').html(); // could this line be causing an issue?
$.ajax({
type: 'POST',
url: 'save-html-css-action.php',
data: {
'htmlTextToSave': htmlTextToSave,
'actualHtml': actualHtml,
'userId':userId
},
success: function(msg){
alert(msg);
}
});
php:
$htmlCssToSave = $_POST['htmlTextToSave'];
$userId = $_POST['userId'];
$actualHtml = $_POST['actualHtml'];
$mysqli = new mysqli($servername, $sqlusername, $sqlpassword, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
//printf("Connect failed: %s\n", mysqli_connect_error());
echo "Connection failed: ".mysqli_connect_error();
exit();
}
$mysqli->query("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values ('".$htmlCssToSave."',".$userId.",'".$actualHtml."')");
echo "success";
/* close connection */
$mysqli->close();
but when I check the database, the data isn't there. Am I doing something wrong in the jquery/php combo (meaning the ajax call)? I'm getting a javascript "success" alert, so it's hitting the script, but I'm not sure why the info isn't being inserted.
The table datatypes are medium text for both the htmlcsstosave and the actualhtml columns, and int for userid (not the primary key, this is a foreign key to another table)
so I added a an error alert and this is the output
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'margin-0'>
<head>
</head>
<body cl' at line 1
As we discussed, the issue is with escaping and sanitizing data. If you used prepared statements, it will handle it for you. let's have a look at how that would work:
Prepare the statement:
$stmt = $mysqli->prepare("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values (?,?,?)");
Bind your parameters:
$stmt->bind_param('sis', $htmlCssToSave, $userId, $actualHtml);
Then execute your statement:
$stmt->execute();
Then you should be good to go. The prepared statement should handle the data sanitization for you now.
Resouces:
mysqli prepare
mysqli bind_param
mysqli execute
Can you post the CREATE TABLE statement for the user_saved_data table?
In general, I'd recommend just tracing it through and see where the data gets lost.
For example, can you echo the query you are generating and run in manually in MySQL? You may have a syntax error in the SQL being generated...

Categories