Inserting data in mysql table with javascript / AJAX - javascript

When the user clicks a button i want to update a value in mysql table, but somehow I'm doing something wrong and nothing happens.
<button class="btn btn-primary" id= "openchest" onclick="insertvalue();"> Open </button>
javascript
function insertvalue(){
makeRequest('addgold.php');
}
EDIT: changed the javascript BUT it still doesnt do anything..
the addgold.php doesnt show any mysql error.
function insertvalue(){
$.ajax({
type: "POST",
url: "addgold.php",
cache: false,
data:{id:'openchest'},
}).done(function( msg ) { console.log(msg);
});
}
addgold.php
<?php include ("connection.php");
if(isset($_REQUEST)) {
$sql= "UPDATE members SET coins = coins + 10 WHERE id ='".mysqli_real_escape_string($link, $_SESSION['id'])."' LIMIT 1";
$result = mysqli_query($link, $sql);
}
?>

you have to use ajax function on click and dont forget to include jquery libray
function insertvalue(){
$.ajax({
type: "POST",
url: "addgold.php",
cache: false,
data:{id:'anything'},
}).done(function( msg ) { console.log(msg);
});
}

Related

How let an ajax request to read a number that is a result of an sql query

I have a very simple sql query:
case 'getFeedbackIvr':
$idClient = $_GET['idClient'];
$query = "SELECT COUNT(idClient) AS _callsNumber
FROM table
WHERE idClient = {$idClient}";
$callsNumber='_callsNumber'
First, I'm trying to understand if this:
$callsNumber='_callsNumber'
is correct
What I need is that when a field in a php form is filled, query is executed and an Ajax request reads the value in $callsNumber and if this value>0 a field (field) in a php form has to appear, else hidden if $callsNumber=0
After several attempts and searchs I'm doing this (but it's incomplete and that's why I'm making this ask):
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "html",
url: '<?=$requestUrl?>' + "?ivrChoiceId="+$(this).val()+"&qType=getFeedbackIvr",
success: function(data){
$("?").html(data);
},
async:true
$('#field').closest('tr').hide();
if ($callsNumber>0)
{
$('#field').closest('tr').show();
}else{
$('#field').closest('tr').hide();
});
});
});
</script>

Show data immediately after insert to db mysql using codeigniter MVC

I have one text box and one button, after filling in the text box and then clicking the button, the data will be saved to mysql.
My question is, how do I when I click the save button, the ID of the data that I save will immediately appear on that page. I mean the ID of the data that just i insert into mysql
This is the view
<label for="userAnswer">Answer</label>
<textarea name="userAnswer" id="userAnswer" class="form-control"></textarea>
<button onclick="saveAnswer()">Submit Answer</button>
This is the js
function saveAnswer(){
var inputAnswer = $('#userAnswer').val();
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
});
}
This is the Controller
function saveAnswer(){
$data = array(
'id' => uuid(false),
'answer' => $this->input->get_post("inputAnswer")
);
$this->db->insert('tableAnswer', $data);
}
Thanks
Views File
add this code
<input type="text" id="id">
Controller File
After insert, add this code
echo json_encode(array("val"=> $data['id']));
Javascript
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
success: function(val){
document.getElementById("id").value = val.val;
}
});
Thats it...
use this code:-
function saveAnswer(){
var inputAnswer = $('#userAnswer').val();
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
sucess:function(result){
alert(result);
},
});
}
the result wll carry your id and it will be shown in alert box, and the returning of id from ajax use this code:-
function saveAnswer(){
$data = array(
'id' => uuid(false),
'answer' => $this->input->get_post("inputAnswer")
);
$this->db->insert('tableAnswer', $data);
$id = $this->db->insert_id;
if($id > 0){
echo $id;
}
}
if you get the result don't forget to tick it right, so other can get help
after insert your data, paste below line in modal
return $this->db->insert_id();
it will reflect last insert data ID
You have to echo the id and not return it to get it from Js
echo $this->db->insert_id();

load a file using variable from client side

I need to load a file inside a container, but using an argument - to get some data from database firstly:
$('#story').load('test.php');
test.php
$st = $db->query("select * from users where id = " . $id);
... processing variables... load the finished content
Here I need $id from client side. Is it possible?
yes ..you could pass with url query
$('#story').load('test.php?id=1');
test.php
$id = isset($_REQUEST['id'])?$_REQUEST['id']):'';
$st = $db->query("select * from users where id = " . $id);
You can use ajax request and on success you load your file something like:
$.ajax({
type: 'POST',
url: "test.php", //make sure you put the right path there
data: {id: id},
dataType: "json",
success: function (resultData) {
$('#story').load('test.php');
}
})
Just make sure that your php function returns/echos the id you want.
That way you make a call to your php file and when it's successful you will load your file and you can put extra logic there if you want to return more data to use it of course.
resultData holds the output of your php function so it's up to you what info you want to be there.
You could use Ajax to post the ID to your php code.
$.ajax({
type: "POST",
url: "test.php",
data: { 'id': foo },
cache: false,
success: function(){
alert("Order Submitted");
}
});
php:
<?php
$id = $_POST['id'];

Delete post using $.ajax

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?
You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}
since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!
The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.
Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.

Javascript passing variable issue not returning

Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.

Categories

Resources