insert in database using json jquery and php - php

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');
}
});
}

Related

insert in database using php, json and jquery

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.

Ajax PhoneGap always error

I must make an application, and I've decided to use PhoneGap, but my Ajax always say "ERROR", and I don't know why, because the insert works very well...
$("#test").click(function() {
var name = $("#name").val();
var password = $("#password").val();
alert(name+' '+password);
$.ajax({
type: "POST",
url: "http://191.165.1.16/PULZ/ajax_action.php",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data : {
actionname : 'insert',
name:name,
password:password
},
success: function(data) {
alert("work");
},
error: function(data) {
alert("There was an error loading the feed");
}
});
});
And my PHP code
if (isset($_POST["actionname"]) && !empty($_POST['actionname'])){
$actionname = $_POST['actionname'];
if($actionname == 'insert'){
$connect = new PDOsql();
$name = $_POST['name'];
$password = md5($_POST['password']);
$sql="INSERT INTO user(name,password) VALUES(?,?)";
$opt = array($name, $password);
$connect->query($sql,$opt);
$connect = null;
die(
json_encode(
array(
'state'=>'success'
)
)
);
}
}
Try this
JAVASCRIPT
$("#test").click(function() {
var name = $("#name").val();
var password = $("#password").val();
alert(name + ' ' + password);
$.ajax({
type: "POST",
url: "http://191.165.1.16/PULZ/ajax_action.php",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
actionname: 'insert',
name: name,
password: password
},
headers: {
'Content-Type': 'application/json'
}
success: function(data) {
alert("work");
},
error: function(data) {
alert("There was an error loading the feed");
}
});
});
PHP
if (isset($_POST["actionname"]) && isset($_POST['name']) && isset($_POST['password'])){
$actionname = $_POST['actionname'];
$name = $_POST['name'];
$password = $_POST['password'];
if($actionname == 'insert'){
$connect = new PDOsql();
$name = $_POST['name'];
$password = md5($_POST['password']);
$sql="INSERT INTO user(name,password) VALUES($name,$password)";
$opt = array($name, $password);
$connect->query($sql,$opt);
$connect = null;
die(
json_encode(
array(
'state'=>'success'
)
)
);
}
}
You can't use "empty()" with a non variable element, you will receive a internal server error "500", always.
Note: Prior to PHP 5.5, empty() only supports variables; anything else
will result in a parse error. In other words, the following will not
work: empty(trim($name)). Instead, use trim($name) == false.
PHP Manual - empty

Getting the value from option

Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help..
PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
});
data: {instructor:$('#SELECT_ELEMTN_ID').val()},
Depending on scope and stuff, you may not wanna use "this".
Jquery
$(document).ready(function () {
$.ajax({
type: "GET",
url: "phpfile.php",
dataType: "json",
success: function (data) {
$.each(data, function (idx, obj) {
$('#selectdata').append('<option value="'+obj.user_id+'">'+obj.user_name+'</option>' )
});
}
});
});
</script>
</head>
<body>
<select id="selectdata">
</select>
</body>
phpfile.php
<?php
$host = "localhost";
$user = "root";
$password ="";
$database= "databasename";
$con = mysqli_connect($host , $user , $password);
$database_connect = mysqli_select_db($con, $database);
$result = mysqli_query($con, "select Id as user_id,Name as user_name from users");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
?>

How to insert a variable in a query from .ajax post

I thought this will be very simple but i think there is a bug when posting a variable from .ajax to a query. Is there any other way I ca get my result?
here is my jquery:
jQuery_1_4_2(document).ready(function()
{
jQuery_1_4_2('.mainfolder').live("click",function()
{
event.preventDefault();
var ID = jQuery_1_4_2(this).attr("id");
var dataString = 'folder_id='+ ID;
if(ID=='')
{
alert("Serious Error Occured");
}
else
{
jQuery_1_4_2.ajax({
type: "POST",
url: "display_folder.php",
data: dataString,
cache: false,
success: function(html){
jQuery_1_4_2(".right_file").prepend(html);
}
});
}
});
});
here is my display_folder.php
<?php
$folder_id = $_POST['folder_id'];
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
Can anybody explain why this not work? i tried to echo $folder_id and it is working, but when you put it inside the query it is not working.
Note: This is not a dumb question where i forgot my connection of db. Thanks
I agree with both you and here I am providing (just for clean display) the same with some little formatting.
var dataString = 'folder_id=1';
$.ajax({
url: "folder.php",
type:'post',
async: false,
data:dataString,
success: function(data){
alert(data);
}
});
and php part where I am getting folder_id properly.
<?php
$postid = $_POST['folder_id'];
//echo $postid;
$link = mysql_connect("localhost","root","");
mysql_select_db("test", $link);
$query = mysql_query("select * from post where id='$postid'");
while($row=mysql_fetch_array($query))
{
echo $row['text'] . "<br>"; //a, b etc in each row
}
?>
So it should work.
Try this in your php code
<?php
$folder_id = addslashes($_POST['folder_id']);
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>

why pdo don't save sign of + and & into database?

Why when i typed "+-1-23$%^&sdfsdf/><" in the textarea but it save only "-1-23$%^" into database?
Code :
function postingMsg (){
$('.error').hide();
var messageposting2= $("textarea#messageposting").val();
var dataString = 'messageposting2='+ messageposting2;
$.ajax({
type: "POST",
url: "note-send.php",
data: dataString,
success: function(msg) {
msg = parseFloat(msg)
}
});
return false;
}
if ((isset($_POST['messageposting2'])) && (strlen($_POST['messageposting2']) > 0)) {
$messageposting3 = $_POST['messageposting2'];
$sql = "UPDATE users
SET my_note=?
WHERE user_id=?";
$q = $conn->prepare($sql);
$q->execute(array($messageposting3, $_SESSION['user_id']));
echo "1";
} else {echo "0";}
It has nothing to do with PDO or your database. You must URL-encode your string before sending it through Ajax.
var dataString = 'messageposting2='+ encodeURIComponent(messageposting2);

Categories