Cannot pass data from my JavaScript to my PHP file - javascript

When I click on "subcribeButton" I want it to save the value and pass that value to my PHP file. I want that PHP file to then make a post to the SQL database.
This is my js:
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "save.php", { email: email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
This is my php code, I would like my php code to accept data from my js file and then post the data to my sql database:
<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
echo $text
$sql = "INSERT INTO MyGuests (email)
VALUES ($text)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The result is I'm getting the following error:
POST http://flockto.it/home/save.php 500 (Internal Server Error)
send # jquery.js:4
ajax # jquery.js:4
m.(anonymous function) # jquery.js:4
(anonymous function) # email.js:13
dispatch # jquery.js:3
r.handle # jquery.js:3

so why not adding a callback in your ajax request so you can debug it in console or with an alert see this it may help you
$.post( "save.php", { "email" : email } , function(result){
console.log(result);//here the result will display what you will echo after getting the post in your php file
});
so in your php file you can add this
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
//so if you check the console you will get the email
//value from your php file so then you can insert it at the DB as you want

You have a syntax error.
Your code is missing the ; at the end of this line:
echo $text
It should be:
echo $text;

The solution:
In the js file url was wrong and quotation marks around email were missing
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "data/save.php", { "email": email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
In the php file used the wrong variable
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
$sql = "INSERT INTO MyGuests (email)
VALUES ('$text')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
A million thanks to everyone who replied to this thread and helped me solve the issue.

Related

cannot get data to javascript from php DB

I am quite new to JavaScript and PHP.
I have started lately on my free time to develop a chrme extension to grab some data from db on a hosting server.
I have created a php file and upload it to the server, this file will be called from my extension js file and will connect to the DB to execute a query and return the result back.
everything goes fine except I dnt see the data, it keeps sending me null info.
Connection is ok, credentials are good but somiething is missing.
PHP code:
<?php
header("Access-Control-Allow-Origin: *");
$name = $_POST['name'];
$servername = "139.162.132.71";
$username = "evhoodco_EVhdAdm";
$password = "******";
$dbname = "evhoodco_EVhd623Vehicles";
// Create connection
$dbhandle = new mysqli($servername, $username, $password, $dbname);
if (!$dbhandle)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
echo "Success to connect to MySQL";
}
$result = $dbhandle->query("SELECT 1");
if ( false===$result ) {
printf("error: %s\n", mysqli_error($con));
}
else {
echo ' ... done...';
}
echo json_encode($result);
mysqli_close($dbhandle);
?>
JavaScript code:
$(document).ready(function(){
$.post('http://evhood.com/connDB.php','name=bob').done(function(data){
chrome.bookmarks.create({'parentId': "1",'title': '','url': "http://www.sapo.pt"});
console.log(data);
});
});
And this is the debug window result:

PHP Javascript Mysql Insert

I am trying to use java-script prompt to insert values into MySQL. I have a html file and a php file.
The html files saved as Test.html:
<button onclick="myFunction()">Create Project</button>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project });
}
}
</script>
The conn.php:
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The conn.php works perfectly and inserts values if I remove the post parameter.
For example, instead of this:
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if i use:
$proj = "NewProject";
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
NewProject gets inserted into the database.
I am not sure if I am missing something in my index.html which is not posting the value in the prompt to php script. I have tried echo $_POST['project']; instead of inserting into MySQL. The echo is missing.
I have run your given code, it runs only i have added the jquery link above script code
Please check this correction,
<button onclick="myFunction()">Create Project</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project },function(response){
console.log(response);
});
}
}
</script>
and also i have added isset() function with $_POST param in conn.php file
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = isset($_POST['project'])?$_POST['project']:'';
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Script not posting information from dropdown to textbox

I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?
I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML

Save entire DOM in mysql

I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

JavaScript PHP $_Get issue

so I have a JavaScript function which calls to a PHP file using an asyncronous method. This is my code
JavaScript
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback (xmlHttp.responseText);
}
xmlHttp.open("GET", "http://127.0.0.1/formulario/insertReporte.php?"+'nombreAlumno='+nombreAlumno+'&noCta='+noCta+'&semestre='+semestre, true);
xmlHttp.send(null);
And here is my PHP File
<?php
$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";
$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ($nombreAlumno,$noCta,$semestre)";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
My issue comes on this line $nombreAlumno = $_GET['nombreAlumno']; as I get this error
On my database my nombreAlumno field is declared as a varchar.
I know my connection works because if I change that line into $nombreAlumno = intval($_GET['nombreAlumno']); it inserts 0 into my database.
Any ideas what am I doing wrong?
You need to add quotes around your values. Also use mysqli_real_escape_string before insert into database to prevent sql injection
$nombreAlumno=mysqli_real_escape_string($conn, $nombreAlumno);
$noCta=mysqli_real_escape_string($conn, $noCta);
$semestre=mysqli_real_escape_string($conn, $semestre);
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";
Try this
<?php
$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";
$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Categories