Insert data into mysql using ajax - php

I'm trying to insert data to mysql, tried everything but nothing worked
here is my code :
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#rating-btn").click( function(){
var teaching=$("#teaching").val;
var marking=$("#marks").val;
var helpfulness=$("#helpfulness").val;
var difficulty=$("#difficulty").val;
var grade=$("#grade").val;
var com=$("#com").val;
$.ajax({
type: "POST",
url:"db/ajax.php",
data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
+"&difficulty="+difficulty+"&grade="+grade+"&com="+com,
dataType: "dataString",
cache: "true",
success: function(msg,string,jqXHR){
$("#results").html(msg+string+jqXHR);
}
});
});
});
ajax.php
<?php
error_reporting(0);
require 'db/connect.php';
$teaching = $_POST['teaching'];
$teaching = mysql_real_escape_string($teaching);
$marking = $_POST['marking'];
$marking = mysql_real_escape_string($marking);
$helpfulness = $_POST['helpfulness'];
$helpfulness = mysql_real_escape_string($helpfulness);
$difficulty = $_POST['difficulty'];
$difficulty = mysql_real_escape_string($difficulty);
$grade = $_POST['grade'];
$grade = mysql_real_escape_string($grade);
$com= $_POST['com'];
$sql = "INSERT INTO ratings VALUES ( '', '{$teaching}', '{$marking}' ,'{$helpfulness}', '{$difficulty}' ,'{$grade}' , '2' , '{$com}')";
mysqli_query($sql);
?>
connect.php
<?php
$db= new mysqli('localhost','root','','instructors');
if($db->connect_errno){
die("we are having some problems");
}
?>
I tried to the sql code and it worked in the phpmyadmin page.
So what is missing that is preventing the data from going into the database?
UPDATE:
when i try to echo all the variables and thier values apears normally
i also tried to do this :
$sql = "INSERT INTO `ratings` VALUES ( '', '3.5', '2.5' ,'4.5', '2.5' ,'1' , '2' , 'hello how are you')";
it does not insert this values to the database
but when i put the same sql code in the phpmyadmin its adds a row perfectly

It seems, your Js-code has some missing paranthesis. >ou should replace "val" with the function call "val()"
var teaching=$("#teaching").val();
var marking=$("#marks").val();
var helpfulness=$("#helpfulness").val();
var difficulty=$("#difficulty").val();
var grade=$("#grade").val();
var com=$("#com").val();
Afterwards, you should get some values in PHP-land, which can be inserted.
Additionally, you are mixing procedural and OOP-code.
mysqli_query($sql);
... is at least missing the connection as first parameter. But since you saved an instance of mysqli_connection already in $db try replacing it with:
$db->query($sql);

What everyone said about mysql and mysqli. Plus you have to add the & between the vars.
data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
+"&difficulty="+difficulty+"&grade="+grade+"&comment="+comment,

fixed my problem by just using the object $db that i already created in connect.php in the ajax.php
instead of writing
query(&sql)
the solution is :
$db->query($sql);
thanks for everyone for the help.

Related

PHP not receveing characters with accents from Ajax [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 5 years ago.
I made a script in Ajax that simply recovers data from MySQL and gives it back to PHP when a select option is changed:
$country = $_POST['country'];
$sql = "SELECT id,name FROM regions WHERE idcountry='$country' ORDER BY name ASC";
$result = mysqli_query($connexion->db, $sql);
$count_row = $result->num_rows;
$regions_arr = array();
while( $row = mysqli_fetch_array($result) ){
$idregion = $row['id'];
$nameregion = htmlentities($row['name']);
$regions_arr[] = array("id" => $idregion, "name" => $nameregion);
}
// encoding array to json format
echo json_encode($regions_arr);
And in my PHP page I have this script:
<script>
$(document).ready(function(){
$("#sel_country").change(function(){
var countryid = $(this).val();
$.ajax({
url: '/include/ajax/getRegions.php',
type: 'POST',
data: {country:countryid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#sel_region").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_region").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Everything works at is has to, except for some of the names recovered that have special characters, for instance "Genève" or "Zürich". Those values are not showed at all, my option has the correct value for the id but it looks empty in the name.
I searched and I tried with uriencode but it doesn't seem to change, any idea how to fix this?
Thank you!
UPDATE AND SOLUTION
I solved this by changing my tables to utf8m64 in this way (for each table):
ALTER TABLE
`table_name`
CONVERT TO CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Then in my script Ajax I added this:
mysqli_set_charset($link, 'utf8mb4');
And then it finally works :)
Try like this
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "xml/html/script/json", // expected format for response
contentType: "application/json"
});

Keep getting logged out after updating the database in PHP

I recently posted a question about deleting multiple rows in the database and basically re-used the code to update multiple rows in the database, but now I am having issue once the database has been updated and the page refreshes it keeps loggin me out an I'm not sure why.
Here is the ajax:
function editUser(){
var url = 'edit-user.php';
var ids = document.getElementById("edit-user-id").value;
var role = document.getElementById("role").value;
var status = document.getElementById("accountStatus").value;
var data = 'userID=' + ids.toString() + '&role=' + role + '&status=' + status;
$.ajax({
url: url,
data: data,
cache: false,
error: function(e){
alert(e);
},
success: function () {
var selects = $('#users-table').bootstrapTable('getSelections');
ids = $.map(selects, function (row) {
return row.id;
});
$('#users-table').bootstrapTable('refresh', {
silent: true
});
location.reload();
}
});
}
And here is the PHP:
require("../config.php");
try{
$role = $_GET['role'];
$status = $_GET['status'];
$ids = array($_GET['userID']);
$inQuery = implode(',', $ids);
$query = 'UPDATE users SET role = :role, account_status = :status WHERE user_id IN ('.$inQuery.')';
$query_params = array(
':role' => $role,
':status' => $status
);
$stmt = $db->prepare($query);
$stmt->execute($query_params);
// Set variable message of affected rows
$count = $stmt->rowCount();
$user_updated = ''.$count.' user(s) updated successfully.';
$_SESSION['user_updated'] = $user_updated;
} catch (Exception $e){
$error = '<strong>The following error occured:</strong>'.$e->getMessage();
$_SESSION['error'] = $error;
}
I tried changing cache: true, but that didn't work. Again, I do not want to be logged out. Any ideas what I am doing wrong?
EDIT: I have narrowed it down to only happen when the page refreshes. I removed this piece of code location.reload(); from the ajax call and it does not redirect me back to the login page, but if i hit F5 or click refresh it logs me out.
This is too long for a comment:
Nothing is jumping out at me that would cause you to lose what is set in the $_SESSION['user']. Try dumping $_SESSION on each page just to keep track of it and disable the redirect for now (just put an error message or something). You can dump the array like so:
print_r($_SESSION);
Do you also know your prepared statement is broken? I don't see the point of the array or the implode for $ids and $inQuery. It should be something like:
$stmt = $db->prepare(
'UPDATE users
SET role = ?, account_status = ?
WHERE user_id = ?'
);
$stmt->execute(array($_GET['role'], $_GET['status'], $_GET['userID']));
There is no point in using IN if you only have one entry. You also aren't protecting your query from anything because you are still inserting the values into the prepare statement.
It appears that I needed to move session_start() to the top of the config.php file to make sure that it is the very first thing called on the page. Everything seems to be working ok right now.

Insert Data mysql using Ajax and PHP

I am want insert data to MySQL Database using Ajax and PHP
My Ajax Code
$(function(){
$('#submit').click(function(){
var Name = $('#InputName').val();
var Email = $('#InputEmail').val();
var Phone = $('#InputPhone').val();
var Username = $('#InputUser').val();
var Status = $('#selectStatus').val();
//Ajax for add Dealer
$.ajax({
url : "../page/addnewDealer.php",
type : "POST",
async : false,
data :{
Submit:'adduser',
Name : Name,
Email:Email,
Phone:Phone,
UserName:Username,
Status:Status
},
success :function(result){
alert(result);
}
});
});
});
and PHP code is
if(isset($_POST['Submit'])=='adduser')
{
$pass= get_rand_id();
$time= get_currunt_Time();
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
$result = mysql_query($insertData);
}
It is a registration page when i am add a user using this program . program replies success massage but in database nothing happen
change
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
to
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('".$_POST[Username]."','".$pass."','".$_POST[Status]."','".$_POST[Name]."','".$_POST[Phone]."','".$_POST[Email]."','".$time."','".$time."')";
Add braces { } around your $_POST variables in the query. Also, check your spelling of your field names - is "contEmaill" correct? (Two 'l's).
You can simply take post data to a variable and append it to the sql query.

Parse JSON object created by a PDO statement

Here is my problem
I looked through Stak overflow and other websites but can't find an answer that solves my actual problem...
I call a php file from an AJAX request, my php file gets data from my db.
I'm making a pdo statement to get data from my db :
//initialize vars such as $db ...
$get = $db->prepare("SELECT * FROM myTable WHERE myTable_id=1");
$get->execute();
echo json_encode($get->fetchAll(PDO::FETCH_ASSOC));
//COLUMNS IN MY TABLE ARE ID, NAME, PHONE, INFO
so that object is returned to my ajax query
BUT I don't know how to fetch this object into my ajax/jquery statement to use its data...
Response from console :
[Object{id="1",name="myname",phone="8888888",info="information"}]
code...
success : function(response){
var id = '';
var name = '';
var phone = '';
var info = '';
}
please tell me how to parse, i tried json.parse(response), but can't display any data from this...
thanx
Do it like this
success : function(response){
var data = JSON.parse(response);
var id = data.id;
var name = data.name;
var phone = data.phone;
var info = data.info;
}
That should do the trick.

Ajax, PHP, MySQL returning sql table

I have the following Ajax code to send information from an HTML form to a PHP file.
$(document).ready(function(){
$('#txt').load( '../../do_comment.php' );
});
$(function(){
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#user_name").val();
var comment = $("#user_comment").val();
var ID = '2'; //must change for each post
$.ajax({
type: "POST",
url: "../../do_comment.php",
data: {user_name:name, user_comment:comment, ID:ID},
success: function(){
$('#txt').load( '../../do_comment.php' );
},
error:function(e){alert("it failed");}
});
});
});
In my PHP file I declare the variables like this:
$name = $_POST[user_name];
$comment = $_POST[user_comment];
$ID = $_POST[ID];
And correctly populate my database with this:
if($_POST[user_comment] != Null) {
$sql = "INSERT INTO $table_name (post_ID, user_name, comments)
VALUES ('$ID','$name', '$comment')";
$result = #mysql_query($sql,$connection) or die(mysql_error());
}
The problem is none of the variables will echo any sort of value, and when I try to query the database it only works if I hard code the ID value in instead of using the variable.
$data = mysql_query("SELECT * FROM $table_name WHERE post_ID =
'".mysql_real_escape_string($ID)."'") or
die(mysql_error());
Use the following when gathering from $_GET/$_POST/$_REQUEST:
$name = $_POST['user_name'];
$comment = $_POST['user_comment'];
$ID = $_POST['ID'];
Notice the tics. Proper syntax is $_POST[''].
Have you checked the database to make sure the proper values are being inserted?
Also, if the post_id is an integer, don't use tics
SELECT * FROM table WHERE post_ID = 1234
NOTICE: do not use MySQL_*, it has been deprecated in PHP 5.5. Use MySQLi or PDO. Watch out for SQL injections as well, especially when using MySQL_*.

Categories