[ASK] I make a quiz that require a result that can be save to my database
oke here the code that i tried to save the result from that quiz
$scope.questions.forEach(function (q, index) {
answers.push({ 'QuizId': $scope.quiz.Id, 'QuestionId': q.Id, 'Answered': q.Answered });
$http.post('http://localhost/server_log/insert.php', answers).success(function (data) { alert(data);
});
});
and here is the insert.php
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
$connect = mysqli_connect("localhost", "root", "", "dataujian");
$data = json_decode(file_get_contents("php://input"));
$answer = mysqli_real_escape_string($connect, $data->Answered);
$query = "INSERT INTO nilai (jawaban) VALUES ('$answer')";
mysqli_query($connect, $query);
echo true;
?>
But when i try to submit it nothing happen, it there anything wrong with my code.
it there anything wrong with my code.
There are a few problems with your code. Build in small pieces so you can test as you go.
One problem is that you're doing a new HTTP POST request for each answer.
Another problem is that you're not validating your inputs on the PHP side, so you don't know what php://input actually contains or whether json_decode was successful
Another problem is that you're not checking for errors when you run your DB query so you have no clue whether the query was executed successfully
You say:
when i try to submit it nothing happen
This is vague. Does it mean that AngularJS doesn't make any request? That PHP doesn't respond?
Related
I have an HTML page with a filter that basically lists car names. When the user selects a value in the filter, I want to show the data associated to that value which comes from my PostgreSQL database. I have attached the code below. At the moment when the user is presented with the page and selects a value from the filter nothing is currently appearing not sure why. Any help welcome thank you
<html>
<select id="filter">
<option>All</option>
<option>BMW</option>
<option>Mercedes</option>
</select>
<?php
$db_connection = pg_connect("host=localhost dbname=postgres user=postgres password=postgres");
$feild_value = $_POST["filter"];
// you can use this $feild_value variable in query;
$result = pg_query($db_connection, "SELECT * from cars where car_name= $feild_value;");
//echo query result here
while($row = pg_fetch_array($result))
echo $result;
die;
?>
<script>
$(document).ready(function()
{
var value = $("#filter").val();
$.ajax({
type:"POST",
data:{"filter":value},
success:function(result){alert(result);}
})
});
</script>
</html>
I'm not sure about your code but your ajax function will not work on the filter change if you didn't call it in on change even, and make sure to put a submit URL to the ajax call and I hope your PHP script is in a separate file if not your script will not run after the die()
$('#filter').on('change',function(e){
//put your ajax submit here
});
There are couples of things with your code that you should be aware of.
Firstly, the die() function will stop the PHP code before the rest of the code is executed and outputted.
Secondly, $result = pg_query($db_connection, "SELECT * from cars where car_name=$feild_value;"); should be
$result = pg_query($db_connection, "SELECT * from cars where car_name='$feild_value;'");
Note the single quote around the $field_value in the SQL statement.
I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).
I have data which is a name. And I am having an input type=text where the value is equals to the name, together with a button type=submit. So what i'm trying to do is that, i want to change and update the name in my database and also output the new name without reloading the page at once because I want to run a JS function (Not Alert but a Toast Notification) which is I cannot do. So to shorten, ( EDIT -> UPDATE -> SHOW = without reloading the page).
EDIT:: I'm sorry I forgot to mention. I know jQuery and AJAX is the solution but I am having trouble understanding AJAX not unlike jQuery.
profile.php (FORM CODE)
<form action="profile.php" method="POST">
<input type="text" id="changename" name="changename" class="form-control" placeholder="New Name" required>
<button id="btnchange" type="submit"></button>
</form>
profile.php (PHP CODE)
<?php
if(isset($_POST['changename'])) {
require 'connect.php';
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
header('location: profile.php');
// MY JS FUNCTION HERE //
}
mysqli_close($conn);
}
?>
How to update and output a databse without reloading the page? what u looking for is AJAX.
I know you have selected the answer, but there's an extra information that you need that might help you in the long run
The are some good ajax tutorials you can follow in the web
Ajax Introduction
What is Ajax ?
And many more you can find on the web.
This is what u need to do, first your form method is GET and on your php script you are requesting an $_POST therefore this will generate an undifined notice error,changename : notice : undifined variable changename so the solution is to use one method in a single form if your form is $_GET you use $variable = $_GET['fieldname'] if form method is POST on your server side use $variable = $_POST['fieldname']; not the way you did. So lets change your form method to POST Then this is what u should do.
edit.php
Update
<script type="text/javascript">
$('document').ready(function(){
$('form').on('submit',function(event){
event.preventDefault();//prevent the form from reloading the page when submit
var formData = $('form').serialize(); // reading form input
$.ajax({
type :'POST',
data : formData,
url : 'profile.php',
dataType : 'json',
encode : true,
success : function(response){
//response = JSON.parse(response);
if(response == "ok"){
$('#success').html('profile updated success');
setTimeout(' window.location.href = "profile.php"; ', 6000); // redirecting
}else{
//could not update
$('#error').html(response);
}
},
error : function(e){
console.log(e); // debugging puporse only
}
});
});
});
</script>
That's what you need on the frontend side.. Please note if you have more than one form in a single page then do not use $('form').on('submit',function(event){}); you then give each form a unique ID then on replace the form on jquery/ajax with the iD of the form u wanna submit.
Then your server side.
I have noticed that you have header('location: profile.php'); that's
for redirecting, since we are sending ajax request to the server and
back to the client, you don't redirect on the server side, your
redirect using the client side after you have received the response
you expected from the server. I have commented that section where I do
redirecting with client side, on the script above.
profile.php
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
$message = 'ok'; // success
}else{
$message = 'system error could not update please try again later';
}
echo json_encode($message);//sending response back to the client
mysqli_close($conn);
}
?>
That's all you need, note you need to validate all your inputs fields in both the client and server side before using them.
I would also advice you to learn more about prepared statements, using mysqli or PDO they are very easy to use and very safe.
running a query like this : $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'"; is very unsafe, your inputs are not validated and not filtered and sanitized.
so with prepared statements its easy like :
profile.php prepared
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
//prepare and bind
$sql = $conn->prepare("UPDATE login SET login_name= ? WHERE user_id= ? ");
$sql->bind_param("si",$newname,$user_id);
if($sql->execute()){
$message = 'ok';
}else{
$message = 'Error Could not update please try again later';
}
echo json_encode($message);
$conn->close();
}
?>
$sql->bind_param("si",$newname,$user_id); This function binds the parameters to the SQL query and tells the database what the parameters.
are.By telling mysql what type of data to expect, we minimize the risk of SQL injections.
First thing to do in your form is to change your form method to POST (and not GET) as you try to retrieve "changename" by POST method.
So change this:
<form action="profile.php" method="GET">
by this:
<form action="profile.php" method="POST">
on my research site, I have a few radio buttons and I want to send their values to MySQL table using jquery and AJAX. All buttons and jquery code are put in single-project.php (I modified WordPress theme) and the bits of code that should handle interaction with the MySQL are put in the db.php in the same folder.
However, something is not in order, because values do not appear on the database table. Could someone help?
jquery:
//the last button
$('#submit_last_button').click(function(){
SomeVariable = $('input:radio[name=lastRadio]:checked').val();
if (!$("input:radio[name=lastRadio]").is(":checked")) {
$("label#lastRadio_error").show();
$("input#lastRadio").focus();
return false;
} else {
if ('input:radio[name=lastRadio]:checked')
$('#PreviousButtonDiv').hide();
$('#NextDiv').show();
$.post('db.php',{action: "submit_last_button", previous_variable:SomePreviousVariable, last_variable:SomeVariable},function(res){
$('#result').html(res);
});
}
});
});
db.php:
<?php
$con = mysql_connect('localhost','user', 'password');
$db = mysql_select_db('my_database');
if($_POST['action'] == 'submit_last_button'){
$previous_variable = mysql_real_escape_string($_POST['previous_variable']);
$last_variable = mysql_real_escape_string($_POST['last_variable']);
$sql = "insert into MyTable (id, variable1, variable2) values ( NULL, '$previous_variable', '$last_variable')";
$query = mysql_query($sql);
if($query){
echo "Record Inserted.";
}else {
echo "Something Wrong!";
}
}
?>
There are various possibilities of what is not working on your code. But first, the problem is not in AJAX not saving on MySQL. AJAX is passing your data to the php script on your server to then, save it on MySQL.
Check if the values are reaching your script correctly;
Check if you're getting a db connection - check error logs or print them out;
Check if you're not getting a SQL syntax erro - again, check for logs;
Check if auto-commit is true (it is by default).
I need help in this PHP Ajax updating mysql database using PDO. I wanted to update the database if a user checks the checkbox. Below is my code:
JS:
$('input[name=product_new]').click(function(){
var chkbox_id = $(this).attr('alt');
var chkbox_selected = $(this).is(':checked');
if(chkbox_selected == true)
{
chkbox_selected = "checked";
}
else
{
chkbox_selected = "uncheck";
}
$.post({
url: "../products_listing.php",
type: "POST",
data: {product_id: chkbox_id, product_new: chkbox_selected},
cache: false,
success: function(){}
});
});
PHP page with PDO to update database:
$id = $_POST['product_id'];
$product_new = $_POST['product_new'];
if(isset($_POST['product_new']))
{
try
{
$query = "UPDATE productinfo SET new_arrival=? WHERE id=?";
$stmt_new_chkbox = $conn->prepare($query);
$stmt_new_chkbox->bindParam(1, $product_new, PDO::PARAM_STR);
$stmt_new_chkbox->bindParam(2, $id, PDO::PARAM_INT);
$stmt_new_chkbox->execute();
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
It was working when I use mysql but now I've changed it to use PDO, it won't work anymore. I can't find where went wrong. Thanks in advance guys.
Below is the old code from mysql_:
$id = mysql_real_escape_string($_POST['product_id']);
$product_new = mysql_real_escape_string($_POST['product_new']);
if(isset($_POST['product_new']))
{
$upt_new=mysql_query("update products_list set new_arrival='$product_new' where id='$id'");
}
Ok! I know what's wrong already. The damn directory path. I took out ../ and it works! Kinda weird though.
Because my js file is in JS folder and products_listing.php is outside of the js folder. Isn't it supposed to be ../products_listing.php?
Can anyone tell me why it's not working which it is supposed to be?
Thanks in advance guys!
Just split your task into 2 parts: AJAX part and PDO part.
First of all make sure that your PDO part works well. Make a mock $_POST array, and then start playing with PDO calling this script directly, without AJAX. Ask questions here, if something goes wrong. then, as you ret it to work, move to AJAX part, the same way - first, without PDO by just by sending data to server and verifying if it's correct.
Solving 2 problems at once makes things a lot harder. Always split your task into separate parts and solve them one by one.