How do I connect my ajax post to php and mysql? - javascript

I spent hours testing all my code, step by step, and still can't make it work. I eventually got the php file to send a test object to the mysql database but I still can't get the jQuery ajax post to connect to php. Can anyone spot the issue? I get the "500 internal server error" message when I run the code.
Javascript:
var jsonEntry = {"timestamp":"2015/01/21 22:18:00","note":"hi there","tags":["one", "two"]};
// send json converted object to php file via ajax
$("#sendButton").click(function () {
$.ajax({
url: 'php/ajax.php',
type: 'POST',
dataType: 'JSON',
data: jsonEntry,
error :
function(xhr, status, error) {
alert(xhr.status);
alert(error);
},
success :
function(data) {
console.log('send success');
}
});
});
PHP code from "ajax.php:"
<?php
if(isset($_POST["data"])) {
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$timeStamp = $obj[timestamp]; //added semicolon here
$note = $obj[note];
$tags = $obj[tags];
//Connecting to a database
//Connection info
$hostname = "localhost";
$username = "root";
$password = "root";
//Code to connect
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select database to work with
$selected = mysql_select_db("notes", $dbhandle)
or die("Could not select examples");
//Execute SQL query and return records
mysql_query("INSERT INTO notes (dateAndTime, noteBody, noteTags) VALUES ('$timestamp', '$note', '$tags')");
// Close the connection
mysql_close($dbhandle);
}
?>
UPDATE:
I have added the semicolon where needed in the php file but now get error 200, "SyntaxError: JSON Parse error: Unexpected EOF."

I think the problem is a missing semicolon here:
$timeStamp = $obj[timestamp]
With this error fixed, you switch this line:
$json = file_get_contents('php://input');
to:
$json = $_POST['data'];

Related

Jquery/Ajax to get database using php

I have an HTML page that is too big to post on here, however I'll just post the ajax/jquery I am using to try and access the PHP file variables.
threadPage.html
<script type="text/javascript">
$.ajax({
url : '/ThreadCreation.php',
type : 'POST',
data: {'titles': titles}
crossDomain: true,
dataType : 'jsonp',
success : function (data) {
console.log(data) /
},
error : function () {
alert("error");
}
})
</script>
<!-- bunch of html -->
So essentially I am trying to get the variable from the ThreadCreation.php in JSON form. It should be in an array so that I can loop through it in the HTML file.
ThreadCreation.php
<?php
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$sql = mysqli_query($conn, "SELECT title FROM thread");
while($row = mysqli_fetch_array($sql)) {
$titles[] = $row['title'];
echo json_encode($titles);
?>
I will repeat though, that this HTML file is only getting information from the database through PHP. So there is no form submission here.
I keep getting that 'titles is not defined'. This makes sense because there is not titles defined in the HTML, however I am unsure how to construct my ajax request to collect the data, as this format is all I have seen people use.
Mention empty array first just to prevent error in case you have no data
in database then empty array will proceed.
$sql = mysqli_query($conn, "SELECT title FROM thread");
$titles = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);

jQuery GET request to PHP failing although PHP is fetching the data

I having written a php script which makes an SQL query and fetches a list of unique names from the database.
I am making an AJAX GET request using jQuery to the php script. When I check resources in the console I see that the php script is being called, and when I check the response it contains a list of unique names.
However, the jquery GET request is failing, and is displaying an error message in the console.
It may be easier and clearer to look at my code, as I have no idea what is the issue here. Please see code below.
php
<?php
header('Content-Type: application/json');
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT(name) FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
$conn->close();
?>
JS
$.ajax({
type: 'GET',
url: 'getcustomers.php',
success: function(data){
console.log(data);
},
error: function() {
console.log('error');
}
});
In the console it simply says error, meaning it has executed the error function.
When I load the php file in the browser it displays the following.
{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}
Your JSON response is not a valid one. You are printing each data row on each iteration. So replace the while statement with this one,
if ($result->num_rows > 0) {
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = array('customer' => $row["name"]);
}
echo json_encode($return);
} else {
echo "0 results";
}
Considering your script returns any result (I hope you've tried running it in broswer) then you can use something like this:
$.get('path/to/file/filename.php').done(function(response) {
$('#exampleDiv').html(response);
});
Although, common errors because you must specify the directory path if the php file you're requesting is outside the current working directory.
change your error handler function header to the following:
error: function (jqXHR, textStatus, errorThrown) {
then print that and see what the error is
you are echoing json_encode string in side while loop, instead of that you will have to push row in an array and at the end you can echo json string only once.
$outputArr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push(outputArr ,array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
echo json_encode($outputArr);

PHP not inserting data into MySQL table with correct SQL syntax

I'm trying to insert a JSON array of objects passed via a jquery $.ajax POST into a MySQL database via PHP. I've seemingly tried everything but for some reason I can't get it to work. Any suggestions would be much appreciated.
PHP
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = json_decode($_POST, true);
foreach ($data as $item) {
$worker_id = $item['worker_id'];
$response_time = $item['time'];
$video_id = $item['video_id'];
$submission = $item['response'];
$test_answer = $item['test_answer'];
$sql = "INSERT INTO nristudy (worker_id, response_time, video_id, submission, test_answer)
VALUES ('$worker_id', '$response_time', '$video_id', '$submission', '$test_answer')";
if (!($conn->query($sql))) {
die($conn->error);
}
}
if (!$conn->commit()) {
echo "Transaction commit failed";
exit();
}
$conn->close();
?>
Javascript
var json = JSON.stringify(submissions);
$.ajax({
type: "POST",
url: "http://hci.cs.wisc.edu/nri/store_data.php",
data: json,
success: function(data){
console.log("Success: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... look at the console for more information!');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
The solution to your problem depends heavily on what the error is. However, one thing that is pretty clear is that you should be escaping the strings you are trying to put into the query.
I recommend that you switch to using PDO and prepared statements as you will not have to worry about escaping anything and can rely on PDO to take care of it when you prepare the statement.
You might also want to try serialize instead of json_encode but if it works there is a chance that SQL injection is still a real big possibility for you.

Save data from dataTable to database

how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!

Get data from database using PHP, JQuery and AJAX in JSON format

I'm having trouble getting data from my database. My goal is to get all groups from my database and return them in JSON (in an alert box or whatever).
Now it won't convert to JSON and I am getting weird response text from the ajax call. If you need anything else to solve this problem, please do not hesitate to ask.
Here is what I did.
PHP
$servername = "redacted";
$username = "redacted";
$password = "redacted";
$dbname = "redacted";
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'getGroups' : getAllGroups();break;
}
}
function getAllGroups() {
$mysqli = new mysqli($servername, $username, $password, $dbname);
$query = $mysqli->query("SELECT * FROM groups");
while($row = $query->fetch_object()) {
$result[] = $row;
}
echo "{\"results\":";
echo json_encode($result);
echo "}";
$mysqli->close();
}
JS
function getPosts() {
$.ajax({
url: 'functions.php',
data: {action: 'getGroups'},
type: 'post',
success: function(output) {
var result = JSON.parse(output);
result = result.resultaten;
alert(result);
}
});
}
getPosts();
Thanks in advance,
Mistergrave.
No need for that extra echos. Try with -
echo json_encode(array('results' => $result));
Instead of -
echo "{\"results\":";
echo json_encode($result);
echo "}";
No need for - if(isset($_POST['action']) && !empty($_POST['action'])) {
if(!empty($_POST['action'])) { - do the all.
Define $result first.
$result = array();
while($row = $query->fetch_object()) {
$result[] = $row;
}
Okay guys, I managed to solve everything. Apparently the php function couldn't find my credentials to log in to the database server because I defined them on top of the php file (and since javascript only executed the function, these credentials were undefined).
Solution:
I just copy-pasted the credentials at the start of each function so these were defined. And tadaah! It worked :).
Now I realize why the responseText was full of tables, because it started to return error tables about the connection.
I hope my explanation will help other people who have this issue as well.
Cheers, and thanks for all the helpfull answers,
Mistergrave.
use
echo json_encode(array('result'=>$result));
As it takes array as parameter. Check here
Just a note :
If are sure you will return json data, use dataType:json , so you wont need JSON.parse(output).

Categories

Resources