I want to insert data from the Client side to a remote mySQL database
I am calling a function and passing a variable into it.
function uploadMetrics(email){
var email;
$.ajax({
type: 'post',
url: 'php/insertConvertData.php',
data: {
data: {"email" : email },
//data:email,
},
success: function(result) {
console.log(result);
}
});
}
On the server I have a php file
$user = $_POST['email'];
echo $user;
echo '<pre>';
print_r($_POST); // for viewing it as an array
var_dump($_POST); // for viewing all info of the array
echo '</pre>';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO cms_conversion_funnel (email)
VALUES ('" . $user . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
The code runs fine and I can connect to the database and run the insert but in inserts an empty string.
I dumped out the value of 'email' to the console and got this:
(
[data] => Array
(
[email] => teretst#gmail.com
)
)
array(1) {
["data"]=>
array(1) {
["email"]=>
string(17) "teretst#gmail.com"
}
}
It seems like there is a value in the email variable but it is not being picked up an passed into the insert statement. Can anyone help, I am new to php and AJAX.
Because it's $_POST['data']['email'], not $_POST['email'].
Use data: {"email" : email }, email is a parameter, you don't have to declare it again:
function uploadMetrics(email){
$.ajax({
type: 'post',
url: 'php/insertConvertData.php',
data: {"email" : email },
success: function(result) {
console.log(result);
}
});
}
It is because you are taking the variable email as input and then redeclaring the same email which is again turning it empty. Please remove
Var email.
Next thing you have to fetch as $_POST['data']['email']
Related
I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType
I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.
This is my code:
<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});
$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});
function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}
function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}
</script>
And this is my PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$placeId = $_GET["placeId"];
$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";
$result = $conn -> query($query) or die("Query failed");
if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}
?>
Any idea what can be wrong?
I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.
Thanks for your patience and sorry for my bad english.
1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called
2) dont echo your JSON for each row like that, that's not valid either. –
Instead do this:
$response = [];
while ( $row = $result->fetch_assoc() ){
$response[] = $row;
}
echo json_encode($response);
3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];
Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
},
error: function(xhr, status, error){
console.log(xhr);
}
});
4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:
function insertResults(json){
alert("cenas");
$("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
}
In your PHP do this:
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
Also don't forget to do mysql_close($con) at the end. Hope this helps you!
From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input
function insertResults(json){
alert("cenas");
$("#teste").html(json["nome"]);
}
i want to insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url:"http://localhost:800/test/insert.php",
type: 'POST',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_POST['data'];
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ($new['email'],$new['mdp'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.
i am facing an problem in sending data from ajax to php i would need some help
$.ajax({
type: "post",
url: "/raffle.php",
dataType: "json",
data: {
"postraffle": "true",
"title": $("#rtitle").val(),
"message": $("#mess").val(),
"maxentry": $("#maxentry").val(),
"duration": $("#durr").val(),
"filter": $("#reffil").val(),
"split": $("input[name=split]:checked").val(),
"pub": $("input[name=rafflepub]:checked").val(),
"stype": $("input[name=stype]:checked").val(),
"invo": $("input[name=invo]:checked").val(),
"items[]": itms,
"games[]": gmes,
},
success: function(data){
if(data.status == "fail")
{
alert(data.message);
$("#rafBut").removeAttr("disabled");
$("#rafBut").attr("value", "Raffle it!");
}
else if(data.status == "ok")
{
alert(data.message);
}
}
});
and the php script is here
<?php
// getting data from AJAX
$raffle_title = $_POST['title'];
$raffle_message = $_POST['message'];
$raffle_maxentry = $_POST['maxentry'];
$raffle_duration = $_POST['duration'];
$raffle_filter = $_POST['filter'];
$raffle_split = $_POST['split'];
$raffle_pub = $_POST['pub'];
$raffle_stype = $_POST['stype'];
$done = false;
$data = array(
'status' => 'ok',
'message' => 'saved! redirecting you!',
'datakey' => 'HALLEYO!',
);
$host ="localhost"; // enter your host.
$pass =""; // enter your password.
$db = "test"; // Enter your database..
$user ="4"; // enter your username.
# MYSQL Connection
$con=mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach($_POST['items'] as $item){
$query = "INSERT INTO table (heading,content,items) VALUES ('".$_POST['title']."', '".$_POST['message']."','".$item."')";
// this should also be done for each item
if (!mysqli_query($con, $query)) {
printf("Error: %s\n", mysqli_error($con));
}
}
echo $data;
?>
Now the function of the above script is to get the data from ajax and upload it to mysql database and send an response to the ajax script back which currently doesnt work.
i think there may be problem with my mysql query (php mysqli parameterized queries)
Some help would be really appreciated.
Thanks!
Try replacing
echo $data;
with
echo json_encode($data);
echoing data will give just "Array" string, not anything JSON encoded
You can not print arrays!
You must chenge it echo $data; to echo json_encode($data);.
Here is what I have going on in my AJAX:
$('#submit-button').click(function(){
var twit = $('input#twittername').val();
var email = $('input#email').val();
if((email == "" || email == "you#address.com") && (twit == "" || twit == "#twittername")){
$('p#empty-error').fadeIn();
return false;
}
var datastring = 'email=' + email + '&twit=' + twit;
if(email != "you#address.com"){
$.ajax({
type: 'POST',
url: '/path/to/script1.php',
data: datastring,
success: function(){
$('#signup').fadeOut('slow',function(){
$('#email-response').fadeIn('slow');
});
}
});
return false;
}
if(twit != "#twittername"){
$.ajax({
type: 'POST',
url: '/path/to/script2.php',
data: datastring,
success: function(){
$('#signup').fadeOut('slow', function(){
$('#email-response').fadeIn('slow');
});
}
});
}
return false;
});
AJAX is returning the success function. And I can navigate directly to /path/to/script2.php, and it will add an empty record to my database. But for some reason, the PHP is not actually receiving and inserting the AJAX variable.
This was working before, and I'm unsure at what point it stopped. It's just a bit strange that it is two scripts that were both working, and now neither are.
Script one was written by me, and it inserts a blank record if I navigate straight to it:
<?php
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pw';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$dbname = 'databasename';
mysql_select_db($dbname, $con);
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo 'record added successfully';
mysql_close($con);
Script two is modified from MailChimp, and this does nothing if I navigate straight to it, which is expected:
function storeAddress(){
// Validation
if(!$_POST['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('66a7f17d87e96e439f7a2837e2963180-us1');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "b1ebe7c0ba";
if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_POST['email']){ echo storeAddress(); }
?>
Any ideas where I'm going wrong?
Also: I can successfully alert the datastring, if that's any help.
Not sure if it is just a typo here, but this line won't work:
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";
It should be (look at the quotes at the POST variale):
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('".$_POST['twit']."')";
Besides that, you should never put a POST Variable directly into the SQL statement due to security reasons (have a look at SQL injections).
Needed to delete the top "return false." A fun way to spend 4 hours.