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.
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);
})
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 6 years ago.
I am having trouble sending data to a php file to be processed. I have tried just about everything but cannot find the source of the problem. Below is a php file that sends a product name, price, and ID to a checkout function after a user clicks on a buy button.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT P1.Product_Name, S2.Price, P1.Product_ID FROM Product P1, Sale_Item S2 WHERE P1.Product_ID=S2.Product_ID AND P1.Category='Sports'";
$res = $conn->query($sql);
$counter=0;
while ($row = $res->fetch_assoc()){
$Product_Name = $row["Product_Name"];
$Price = $row["Price"];
$Product_ID = $row["Product_ID"];
echo ('<td><p></p>'.$row["Product_Name"].'<br>'.$row["Price"].'<p></p><input type="button" value="Buy" onclick="checkout(\'' . $Product_Name . '\', \'' . $Price . '\', \'' . $Product_ID . '\')"</td>');
$counter++;
if ($counter==3) {
$counter=0;
print "<br>";
}
}
$conn->close();
?>
And next the checkoutfunction:
<script type="text/javascript">
function checkout(Product_Name, Price, Product_ID) {
//document.write(Product_Name, Price, Product_ID)
var theProduct_Name = Product_Name;
var thePrice = Price;
var theProduct_ID = Product_ID;
$.ajax({
type: "POST",
url: "http://localhost:8888/checkout.php",
data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
});
window.location.assign("http://localhost:8888/checkout.php")
}
</script>
I am using MAMP's phpMyAdmin's database. Is my url incorrect? I've tried using "http://localhost:8888/checkout.php" and just checkout.php. Below is the php file where I need to process data. For simply learning how to send the data I am just echoing inside the file to make sure it is actually posting. But nothing is being echoed.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$theProduct_Name = $_POST['Product_Name'];
$theProduct_ID = $_POST['Product_ID'];
$thePrice = $_POST['Price'];
echo $theProduct_Name.$theProduct_ID.$thePrice;
?>
I am new to web-programming so any help or tips would be appreciated. I've been looking at this for hours now and cannot seem to get it to work.
When using Ajax, the request is sent by ajax and you can see the response in the success method. Any direct call to the action URL will sends new request which is empty in this case for the line
window.location.assign("http://localhost:8888/checkout.php")
Remove that line of code and change your jQuery.Ajax like bellow to see what's the response.
var request = $.ajax({
type: "POST",
url: "http://localhost:8888/checkout.php",
data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
You can track the ajax request in browser console. It will show you the request and response and the error you are receiving from your php script.
If on button click you are not able to see any request in the console then try to use "method" instead of "type". Some older jquery version doesn't support type. method: "POST",
I tested your code and it worked, the ajax request occurs normally, try remove this single line from your javascript code.
window.location.assign("http://localhost:8888/checkout.php");
I use this version of jQuery: https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js
In Network tab of Google Inspector I get this:
Request:
Request URL:http://localhost:8888/checkout.php
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:8888
Response:
Bike150
you should have following changes on your code
$.ajax({
method: "POST",
url: "http://localhost:8888/checkout.php",
data: {"Product_Name": "theProduct_Name", "Price": "thePrice", "Product_ID": "theProduct_ID"},
success : function(responseText)
{
alert('success to reach backend');
// you can console the responseText and do what ever you want with responseText
console.log(responseText);
},
error : function(jqXHR, status, error){
if (jqXHR.status === 0) {
alert('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status == 404) {
alert ('The requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert ('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert ('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert ('Time out error.');
} else if (exception === 'abort') {
alert ('Ajax request aborted.');
} else {
alert ('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
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!