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.
Related
i have a ajax and php as follows but it is not changing the value of html attribute with id #respo
is there any modification require?
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
dataType: "json",
data: {reccount: reccount},
success: function(response) {
var response = ($response);
$("#respo").text(response);
},
})
and php as
<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT response from paper WHERE ID=$id";
$result=mysqli_query($link, $sql);
while ($row = mysql_fetch_row($result)) {
$response => $row['response'];
}
echo json_encode($response);
// Close connection
mysqli_close($link);
?>
i want to assign a value of response to html element with id respo
Your code must look like
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
success:function(data){
var obj = jQuery.parseJSON(data);
document.getElementById('elementName').value = obj.varaibleName;
}
});
I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>
I want delete a record from database and to do it I want use ajax..
So I have a table where I put into last td this:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
this is my deleteUser function:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
And this is my php page to connect to db and delelte the record:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
But I obtain always (from every ajax request) error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
Why???
You can consider two solutions.
Your code is buggy. Try to execute it on it's own. Just call it in your browser and check the result!
You have specified a relational path for your script. url: "deleteUserAjax.php", try instead an absolute path and check the result (url: "http://yourdomain.com/deleteUserAjax.php")
Maybe make it more cleaner:
HTML part:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery part:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP part:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}
i want to add data to my database by passing as a json string then using php what i have done but adds an empty line in the database instead of adding the data that i sent and i get the alert("fail") message where is the mistake please
here is my 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',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
and here is my php file insert.php
<?php
$json = isset($_POST['data']) ? $_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']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
Can you try this:
JS:
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: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
PHP Code:
<?php
$email = isset($_POST['email']) ? $_POST['email'] : "";
$mdp = isset($_POST['mdp']) ? $_POST['mdp'] : "";
$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 ('".$email."','".$mdp."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
Get data using this way in PHP
$data = json_decode(file_get_contents('php://input'));
$email = $data ->email;
$mdp = $data ->mdp;
In your PHP, each individual variable that you're passing through (i.e. email and mdp) is passed as individual $_POST data, not into a single $_POST variable called 'data'. Right after your opening PHP tag, check for the email and mdp:
$email = (isset($_POST['email']) ? $_POST['email'] : "");
$mdp = (isset($_POST['mdp']) ? $_POST['mdp'] : "");
$conn= ....
You can try this:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {'email': eml,'mdp': mp}; //json
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: data,//pass it here
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
php:
<?php
if(isset($_POST['email'],$_POST['mdp']) {
$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 ('".$_POST['email']."','".$_POST['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
try like this,
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: {"data":JSON.stringify(data)},
// contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
Try this :
function save() {
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
type: 'POST',
url: "http://localhost:800/test/insert.php",
//dataType: 'json',
data: {"data": JSON.stringify(data)},
//contentType: "application/json; charset=utf-8",
success: function (data) {
if (data == 'created')
alert('Success');
else
alert('Fail');
}
});
}
I have this script, that has to send inputed data to a processing php page
<button id="whatever" onclick="sendData()">Send</button>
<script>
function sendData() {
var header = $('.header_input').val();
var content = $('.content_input').val();
$.ajax({
type: 'POST',
url: 'parts/post_functions.php',
data: {
header: header,
content: content
}
});
}
</script>
And the processing page looks like this:
<?php
$con=mysqli_connect("localhost", "root", "shit", "data");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$header = mysql_real_escape_string(htmlentities($_POST['header']));
$content = mysql_real_escape_string(nl2br(htmlentities($_POST['content'])));
$sql = mysqli_query($con,"INSERT INTO posts (Header, Content) VALUES
('{$header}','{$content}')");
mysqli_close($con);
?>
So how do I receive the data correctly, and of course, send it to a query?
I'm totally new to AJAX, but I believe this is a very simple question for those who have been working with it for a while now.
$header = $mysqli->real_escape_string(htmlentities($_POST['header']));
$content = $mysqli->real_escape_string(nl2br(htmlentities($_POST['content'])));
You can do something like this
<script>
function sendData() {
var header = $('.header_input').val();
var content = $('.content_input').val();
var dataString = 'header='+header'&content='+content;
$.ajax({
type: 'POST',
url: 'parts/post_functions.php',
data: dataString,
success: function(data) {
alert(data);
}
});
}
</script>
Now in the PHP page you can access the values by
<?php
$header = $_POST['header'];
$content = $_POST['content'];
// ANYTHING THAT YOU `echo` here will be alerted in jquery alert
?>
Hope you get some idea
Use this.
<button id="whatever" onclick="sendData()">Send</button>
<script>
function sendData(){
var header = jQuery('.header_input').val();
var content = jQuery('.content_input').val();
jQuery.ajax({
type: 'POST',
url: 'parts/post_functions.php',
data: {
header: header,
content: content
},
success: function( data ) {
alert(data);
}
});
}
</script>
and
<?php
$con = mysqli_connect("localhost", "root", "shit", "data");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$header = mysqli_real_escape_string($con,htmlentities($_POST['header']));
$content = mysqli_real_escape_string($con,nl2br(htmlentities($_POST['content'])));
$sql = mysqli_query($con,"INSERT INTO posts (Header, Content) VALUES
('$header','$content')");
if($sql)
{
echo 'done';
}
else
{
echo 'error';
}
mysqli_close($con);
?>