Upload data base with link onClick - javascript

I am having trouble in uploading my database information when I click on a specific link.
It seems that the data is not sent to upload.php
HTML:
Mylink
Javascript:
<script type="text/javascript">
function myfunc(a, b)
{
$.ajax({
url: "upload.php",
type: "POST",
data: {"a": a, "b": b},
success:function() {
alert( "Done");
}
});
}
</script>
upload.php:
if (isset($_POST['a']) && isset($_POST['b']))
{
$a = $_POST['a'];
$b = $_POST['b'];
$query1 = $db->prepare('UPDATE users SET a = a + 1 where uid="'.$a.'"');
$query1->execute();
$query2 = $db->prepare('UPDATE users SET b = b + 1 where uid="'.$b.'"');
$query2->execute();
if (!$query1 || !$query2)
{
echo "Erreur SQL";
exit();
}
}

1st : Your html should be like this myfunc(<?php echo $a ?>,<?php echo $b ?>)"
Mylink
2nd :Add error handling part in ajax request
function myfunc(a, b)
{
$.ajax({
url: "upload.php",
type: "POST",
data: {"a": a, "b": b},
success:function() {
alert( "Done");
},
error:function(jqXHR,error_string,error){
console.log(error);
}
});
}
3rd : use bind_param the values to avoid SQL injection and integer value should not enclosed by single quotes
$query1 = $db->prepare('UPDATE users SET a = a + 1 where uid=?');
$query1->bind_param('i',$a);
$query1->execute();
4th : In your upload.php file your preparing $query2 first and trying to execute $query1 i think it was typo please correct it .

Related

Reload data from database without refreshing page

My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function () {
var k = document.getElementById("balanceNumber");
k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
}
}
);
}
and the handler.php
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
//$link = mysqli_connect("localhost","username","password", "users");
$bal = $userRow['userBalance']+$_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
Can anyone suggest me how to update this information without refreshing the page?
The issue is that you are trying to run php in the client side when you wrote k.innerHTML="string"+php code
You should instead produce an output in the php file you request to and retrieve that output and put it in here.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The link explains how to send data to server through POST and get data from server through GET.
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:
$.ajax({
'url': 'getdata.php',
'type': 'GET',
'dataType': 'json',
'data': {'topUpBalance':d},
'success': function(data) {
// if the request calls properly
},
'error': function(data) {
// if the request fails.
}
});
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-
if(isset($_POST['topUpBalance'])){
$res=mysqli_query($link, "SELECT * FROM users WHERE
userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
$bal = $userRow['userBalance'] + $_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
//Send output echo ...... ;
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
In jquery side :-
receive data using parameter
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function (data) {
// use sent data or unsent data for processing
}
}
);
}

How can i use this kind of var in AJAX?

The Problem is in the var a I have created
<script>
$( "#EDITsave" ).click(function() {
var a = parseInt(window.id.charAt(window.id.length-1)) //a gets parsed correctly but nothing happens in ajax until i set a number myself
console.log(a)
$.ajax({
type: "POST",
datatype: "text",
url: "edit.php",
data: {
inputID: a,
inputtxt: //issue is in 'a' here!
document.getElementById("editinputtext").value
},
});
});
</script>
PHP: // PHP CODE FOR AJAX
$inputID = $_POST['inputID'];
$inputtxt = $_POST['inputtxt'];
$sql = "UPDATE Contributions SET inputtxt = '$inputtxt' WHERE inputID = $inputID";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();
?>

How to pass multiple variables from a php file to ajax and use them?

I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console

Creating mysql delete link for every row in table, delete it with ajax and update table list

So I have table inside database. I have input field and based on input I call ajax to list table.
a = $("#a").val();
$.ajax({
type: "POST",
url: "list.php",
data: {a: a},
success: function(response){
$('#b').html(response);
}
});
return false;
and my list.php :
$result = $dbc->query("SELECT * FROM table WHERE a = '$a'");
while ($row = $result->fetch_array()) {
$x = $row['ID'];
$y = $row['a'];
$z = $row['b'];
echo $x;
echo " ";
echo $y;
echo " ";
echo '<input value="';
echo $z;
echo '" type="number" />';
echo '<a href="delete.php?ID=';
echo $x;
echo '"><span class="delete">x</span>';
echo '<br/>';
}
and delete.php :
$ID = $_REQUEST['ID'];
$sql = "DELETE FROM table WHERE ID=" . $ID;
if($dbc->query($sql) === TRUE) {
echo 'deleted';
} else {
echo "Error deleting record; ". $conn->error;
}
$conn->close();
So when I click on x near list of table rows it really delets row but via php. I need to do it via ajax. I tried this but doesn't work.
$('.delete').click( function (e) {
$.ajax({
type: "POST",
url: "delete.php",
data: {x: x, y: y, z: z},
success: function(response === 'deleted'){
$.ajax({
type: "POST",
url: "list.php",
data: {a: a},
success: function(response){
$('#a').html(response);
}
});
return false;
});
}
});
return false;
});
So logic is - when I click on x it prevent default and calls delete.php and delete row based on posted id and on success calls ajax again to update list without deleted row.
Hint?
As pointed out in the comments, you have a syntax error with your success function:
success: function(response === 'deleted')
When you click the "x", if your row is not being deleted in the database, then either the row with the information specified does not exist, or you are not properly sending and retrieving the POST data.
I noticed that when you send the POST request to delete.php, the keys you are sending are "x", "y", and "z": data: {x: x, y: y, z: z}. However, in delete.php you are looking for the request variable identified by "ID": $ID = $_REQUEST['ID'];. I believe that this is where your problem exists. You should make sure that your keys match.

Ajax separate data which came from mysql

I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax

Categories