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!
Related
I stuck in the following process:
Here is the well known "Facebook Login for the Web with the JavaScript SDK example":
https://developers.facebook.com/docs/facebook-login/web
I want to get the Facebook USERID as a simple string to pass it to a PHP variable. Altough the USERID is shown when I print the $fbID, but it's not a string.
How can I get the USERID as a simple string (or a number)...?
Here is my code:
<?php
$fbID = "<script>
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = response.id;
});
}
</script>";
?>
</script>
<div id="status">
</div>
<?php
echo $fbID;
$sql = "select id from customer where fbid = '$fbID' and status = '1'";
$table = mysqli_query($conn,$sql);
list($realid) = mysqli_fetch_array($table,MYSQLI_BOTH);
echo $realid;
?>
Thank you in advance for your answers!
Use ajax to persist the ID in your database. Add the following code to your FB.api('/me', function(response) { } function:
$.ajax({
url: 'persistID.php',
type: "POST",
dataType:'json',
data: ({id: response.id}),
success: function(data){
console.log(data);
}
});
And create a seperate persistID.php file where you persist the FacebookID:
<?php
$ID = $_POST['id'];
$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 customer (fbid) VALUES ($ID)";
// Persist userid
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
i am trying to get the users ip address using jquery and store that ip address in var, then send that variable to my php page to be inserted via SQL to my database.
function rateMedia(mediaId, rate, numStar) {
$('.box' + mediaId).html('<img src="design/loader-small.gif" alt=""
/>');
var ip = 1; // i would like to store the ip address in a variable
var data = {mediaId: mediaId, rate: rate, ip:ip}; // Create JSON
which will be send via Ajax, this includes the variable for the ip
$.ajax({ // JQuery Ajax
type: 'POST',
url: 'ajax/tuto-star-rating.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json',
timeout: 3000,
success: function(data) {
$('.box' + mediaId).html('<div style="font-size: small;
color: green">Thank you for rating</div>'); // Return "Thank you
for
rating"
// We update the rating score and number of rates
$('.resultMedia' + mediaId).html('<div style="font-size:
small; color: grey">Rating: ' + data.avg + '/' + numStar + ' (' +
data.nbrRate + ' votes)</div>');
..............................
tuto-star-rating.php
if($_POST) {
$mediaId = $_POST['mediaId']; // Media ID
$rate = $_POST['rate']; // Your rate
$ip = $_POST['ip']; //i would simply like to get the ip address
like this
$host = 'localhost';
$dbname = 'mov';
$username = "root";
$password = "";
$pdo = new PDO('mysql:dbname=mov;host=localhost', $username,
$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
...............................
$query = $bdd->execute('INSERT INTO tc_tuto_rating (media, rate, user_ip) VALUES
('.$mediaId.', '.$rate.','.$ip.')'); // insert the new rate
}
..............................
I have tried excluding ip from jQuery entirely and getting the ip address in the php script below which usually works. but it doest work if the ip variable is not declared before the post in the jQuery, the ip column in my database is empty doing it this way. code below
<?php
if($_POST) {
$mediaId = $_POST['mediaId']; // Media ID
$rate = $_POST['rate']; // Your rate
$ip = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
return $ip;
}
$host = 'localhost';
$dbname = 'mov';
$username = "root";
$password = "";
$pdo = new PDO('mysql:dbname=mov;host=localhost', $username,
$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$get_cat = $pdo->prepare("SELECT * FROM tc_tuto_rating WHERE media
= :media AND user_ip = :user_ip");
$get_cat->bindParam(":media", $mediaId, PDO::PARAM_INT);
$get_cat->bindParam(":user_ip", $ip, PDO::PARAM_INT);
$get_cat->execute();
?>
i have used var ip = 1; to test it. The ip address is stored correctly as 1 in the database, how can i correctly get the correct ip address. i have seen similar questions and tried most of them which either didnt work or couldn't figure out how to merge the solution with my code.
All I want to do is print 'win!' if they log in with their details in the Database (working correctly) and 'loss' if for some reason their info was not found in the DB.
So my issue is that for some reason my line of code 'echo $email;' doesn't work. It seems be set to NULL.
At the moment it only ever prints 'loss' regardless what i enter, but, if I add a row in the database that has a blank email and password (email = "", password="") then the php script returns 'win!'.
PHP CODE:
<?php
// echo "php test";
//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";
//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
//Check connection for failure
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Read in email & password
echo "reading in email & password...";
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']);
echo $email; //this prints blank
echo $password; //this also prints blank
$sql = "SELECT Name FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
echo "win!!";
} else {
echo "loss";
}
mysqli_close($conn);
?>
JS CODE:
$(document).ready(function(){
// alert("js working");
$('#login_button').click(function(){
var email = $('#email').val(); //prints the correct value
var password = $('#password').val(); //prints the correct value
var dataString = 'email1=' + email
+ '&password1=' + password;
$.ajax({
type: "POST",
url: "http://localhost:8888/php/login.php",
data: dataString, //posts to PHP script
success: success()
});
});//eo login_button
function success(){
alert("success");
}
});//eof
Apart from the fact that that is completely, insanely useless and with no security whatsoever, you can just exchange $.ajax() for $.post() and do like this:
var loginEmail = $('#email').val();
var loginPassword = $('#password').val();
$.post('login.php',{email:loginEmail,password1:loginPassword},function(data) {
console.log(data);
})
I know this question has been asked before but none of the solutions I have tried work, I wrote a php rest service which I'm hosting on a server, I used advanced rest client data on chrome to test my rest service and it works, it posts data to the database, but when I wrote my own client in an ajax post below the browser complains of
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8383' is therefore not allowed
access.
I have tried adding a header to my php code still doesn't work i get another error..., I'm just wondering what I'm doing wrong?
>// MY PHP REST SERVICE
<?php
$servername = "localhost";
$username = "root";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Insert data into data base
$sql = "INSERT INTO UserData.register (name, surname, email, password)
VALUES ('$name', '$surname', '$email','$password')";
if ($conn->query($sql) === TRUE) {
$json = array("status" => 1000, "msg" => "Done User added!");
} else {
$json = array("status" => 0, "msg" => "Error adding user!");
}
header('Content-type: application/json');
echo json_encode($json);
$conn->close();
}
> //MY java script ajax client doing the posting.
<script type="text/javascript">
function RegisterUser() {
var name = $("#name").val();
var surname = $("#surname").val();
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "http://xxx.xxx.xxx.xxx/signup.php",
data: '{"name":"' + name + '","surname":"' + surname + '","email":"' + email + '","password":"' + password + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d)
}
});
}
</script>
Try Using .htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
CORS guide is here which lists all the possible ways to solve the problem regarding CORS.
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'];