Sending data through AJAX to MySQL - javascript

So I'm trying to send dynamic generated data with AJAX to mysql.
<script type="text/javascript">
var postId;
function getdata(){
postId = document.getElementsByTagName("post-id");
}
function senddata(){
var data = getdata();
$.ajax({
url: "php/count_shares.php",
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
}
</script>
The function is done through onClick method per picture. I'm sending a string in the post-id tag. Then with count_shares.php my code is as follows:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$server = '';
$dbname = '';
$dsn = "mysql:host=".$server.";dbname=".$dbname;
$username = '';
$password = '';
if (isset($_POST['data'])) {
$click = $_POST['data'];
$sqlcs = ("UPDATE posted_ad_img SET share_count = share_count + 1 WHERE post_id = $click");
$dbcs = new PDO($dsn, $username, $password);
$dbcs->$opt;
$dbcs->prepare($sqlcs);
$dbcs->execute();
}
But nothing is being sent to my database. Any help on this matter?

Try this:
$.ajax({
url: "php/count_shares.php",
type: "POST",
data: "data="+data,
success: function(data){
console.log(data);
}
});

Firstly - you don't return value from getData function. Need to change it
function getdata(){
postId = document.getElementsByTagName("post-id");
return postId[0].nodeValue;
}
Also you have to change your ajax request, something like this:
$.ajax({
url: "php/count_shares.php",
type: "POST",
data: {data: data},
success: function(data){
console.log(data);
}
});
If you provide your html I can write more details

Related

Why is $_POST empty when sending data using fetch?

I am trying to just sent some POST data via fetch to a PHP endpoint and want PHP to just output the _POST details.
e.preventDefault();
(async () =>
{
const response = await fetch('form-api.php',
{
method: 'POST',
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await response.json();
console.log(content);
})();
form-api.php : <?php echo json_encode($_POST) ?>
But content is always []
I understand I can get it via :
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
But I want to know why $_POST is empty. It isn't when I use jQuery's AJAX like this.
$.ajax(
{
url : "<?php echo CB_ABS_URI ?>ajax/change-bp-name.php",
type: "POST",
dataType: "json",
data: { BPID: "<?php echo $BPID ?>", Name: $('#txt-bp-name').val() },
success : function(data, textStatus, jqXHR)
{
if (data['Status'] == 'Error')
{
alert(data['Message']);
}
else
{
// alert(data['Message']);
}
}
});

Ajax Sending data (JSON) throught POST

Someone can see why it shows the error Maximum call stack size exceeded? And why is not working the script? UPDATE: I added the php code that don't put the value "domain" and I updated the JS code.
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
eldmn = document.getElementById('adddomain').value;
nwentry.name = el;
nwentry.domain = eldmn;
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: nwentry,
succes: function(data) {
alert('Ok')
}
})
}
php:
//ADD
$app->post('/domain', function () {
$jsonContents = file_get_contents('data/data.json');
$name = $_POST['name'];
$domain = $_POST['domain'];
$data = json_decode($jsonContents, true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'name' => $name,
'domain' => $domain,
'id' => $last_item_id+1
);
$json = json_encode($data);
file_put_contents('data/data.json', $json);
return $this->response->withRedirect('../index.html');
});
You are passing control object not the value to ajax. try below code
function addentrys() {
var nwentry = {};
el = document.getElementById('addname')
nwentry.name = el.value;
var data = JSON.stringify(nwentry)
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: (nwentry),
succes: function(result) {
console.log(result)
}
})
}
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
nwentry.name = el;
var data = JSON.stringify(nwentry)
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: (nwentry),
succes: function(result) {
console.log(result)
}
})
}
Try following code. Check success function typo and sending data varaible, not nwentry object
function addentrys() {
var nwentry = {};
el = document.getElementById('addname')
nwentry.name = el;
var data = JSON.stringify(nwentry)
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: data,
success: function(result) {
console.log(result)
}
})
}

How do I alert the variable using url segment with ajax?

I am using HVC codeigniter.
I wanted to alert the value of variable.
Here's the code on my view.
$("#user_table tr").click(function(){
$userid = $(this).closest('tr').children('td:first').text();
$.ajax ({
type: "POST",
url: "manageUser_controller/log_history/$userid",
success: function(data){
alert(data);
}
});
});
Here's the code on my controller.
function log_history($userid) {
echo $userid;
}
You need to edit your code as follows
var userid = $(this).closest('tr').children('td:first').text();
url: "manageUser_controller/log_history/'+userid,
try to send as data like this
$("#user_table tr").click(function(){
var userid = $(this).closest('tr').children('td:first').text();
$.ajax ({
type: "POST",
url: "manageUser_controller/log_history",
data:{userid : userid},
success: function(data){
alert(data);
}
});
});
and get it on controller using input post like this
function log_history()
{
$user_id = $this->input->post('userid',true);
echo $userid;
}
it's also be filter by true.

How do i parse json data retrieved from php script in javascript or jquery

Please somebody help me, am new to ajax, i have been trying to read json data from php script but just no success.
when i console.log the data i get this,
{"name":"JOHN","surname":"FIGO","sex":"M","Records_id":"1","student":""}.
and when i do this console.log(data[2]); i simply get n character. what i want is to get the values, for example, console.log(data['name']); should give JOHNor console.log(data[0]); should give JOHN. when i use either javascript or jquery parse methods, i get an error, i dont understand. Here is are the codes;
<?php
$conn= new mysqli('localhost', 'root', '', 'Goldfinger');
$query= 'SELECT * FROM records';
$result= $conn->query($query);
while($row = $result->fetch_assoc()) {
echo json_encode($row);
}
?>
and jquery;
$('#one').click(function () {
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
success: function (data) {
if (data) {
console.log(data['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
})
pardon my code if it's very poor. Thank you in advance.
Put dataType : 'json', inside ajax setting like so :
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
dataType : 'json', //<------------- here
success: function (data) {
if (data) {
console.log(data['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
or simply parse inside success callback :
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
success: function (data) {
var myData = $.parseJSON( data ); //<------- here
if ( myData ) {
console.log(myData['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})

Ajax response undefined or strange

i'm trying to send an array to JS, but i can't have the answer i want.
this is my PHP code:
$output = array('total'=>(float)$BHoras[1]'gastas'=>(float)$BHoras[2]);
echo json_encode($output);
and this is my JS code:
function ProjectSelect()
{
var proj = document.getElementById('ProjetosSelect').value;
$.ajax({
url: 'CRM files/TSread.php',
type: "POST",
data: ({ProjetosSelect: proj}),
complete:function(data)
{
var Horas = data.responseText;
alert(Horas); // response -> {"total":146,"gastas":84.5}
alert(Horas[3]); // response -> o
}
});
}
i only want the "146" and "84.5".
i tried to do, alert(Horas['total']), alert(Horas.total), but give me undefined
Just specify dataType: "json" and jQuery will parse response for you:
function ProjectSelect()
{
var proj = $('#ProjetosSelect').val();
$.ajax({
url: 'CRM files/TSread.php',
type: "POST",
data: ({ProjetosSelect: proj}),
dataType: "json",
success: function(Horas)
{
alert(Horas.total);
}
});
}
On server side you could try TracKer note. And you can add a header too.
<?php
$output = array('total'=>(float)$BHoras[1], 'gastas'=>(float)$BHoras[2]);
header('Content-type: application/json');
echo json_encode($output);

Categories

Resources