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']);
}
}
});
Related
So i have this jQuery:
$("#dropbin").droppable(
{
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
and that includes this url: url: 'deleteNote.php',
in deleteNote.php:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid']))
{
// $noteid2 = $_POST['noteid1'];
echo "You finally hit this bit, congratulations...";
// $stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
// $params = $noteid2;
// $stmt = sqlsrv_query($conn, $stmt, $params);
// if ($stmt === false)
// {
// die( print_r(sqlsrv_errors(), true));
// }
}
else
{
echo "No Data";
}
?>
Now even in the URL if i run /deleteNote.php?noteid=25 it hits the "No Data" part of my PHP.
When i run in debugger it populates the variable noteid with a NoteID so that bit is working but the PHP file is saying its not set?
Let's look in your Ajax call:
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
Looks nice, but you are sending post data with no id, you're just sending a value. Try this instead.
$.ajax({
type: 'POST',
data: {
noteid: noteid
},
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
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!');
}
})
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);
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
Hello guys I have a problem in getting the response from my ajax. If I display it in the console. I can view it. But How do I assign it in a variable?
Here's what I have.
In my PHP code I have this
public function checkPassword($password){
$username = $this->session->userdata('username');
$validate = $this->members_model->checkPassword($password,$username);
echo $validate;
}
In my jquery I have this
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
if(g == 1){
$('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
}else{
$('#existing_info').html('Password is INVALID!');
}
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var k=response;
if(k.indexOf("1") != -1)
$('#existing_info').html('Password is VALID');
else
$('#existing_info').html('Password is INVALID!');
}
});
response is in response variable of success function.
indexof returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex,
returns -1 if the value is not found.
try something like this
<script>
var k = null;
$(function(){
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
if(response == 1){
k = response;
}
}
});
});
})
</script>
In your success response you will get what you are set to output in php.
If you want to get an array or data set you can encode it in json in your php script like
echo json_encode($validate);
Then in your jquery you can use this response like this
var responseData = jQuery.parseJSON(response);
console.log(responseData);
console.log will print json object in browser console.
You can use this json object like this
responseData.some_data
Ajax is asynch so you will have access to it after the ajax method returns:
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json'
}).then(function(response){
var k;
if(response == 1){
k = response;
//call another function that needs k here
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
k=response;
}
});
var k = null;
$('#existing').on('keyup', function() {
var id = '<?php echo $this->session->userdata("user_id"); ?>',
password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type : 'POST',
url : password_url,
success : function(data) {
if(data === '1') {
k = data;
}
}
});
});
response parameter itself contain data so just assign that to variable and use it.
$.ajax({
type: 'POST',
url: password_url,
success: function(response){
if(parseInt(response) == 1){
var k = response;
}
}
});
Your response data is in response variable of success function. Since the response type is json you can assign it directly to javaScript variable.
Also you comparison is wrong try if(g == '1') instead if(g == 1). You are getting a string as response and your checking equality with a numeric type which won't be equal at any point.
ie:-
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
contentType:"application/json",// Add Content type too
success: function(response){
k=response;
}
});
if your json response is as shown below
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
you can access menuitem array as
success: function(response){
k=response.menu.popup.menuitem;
}
File Name votepost.php
<?php
include("domain.php");
$csid=$_POST['CSID'];
$voteid=$_POST['VOTEID'];
$myid=$_POST['MYID'];
$usertype=$_POST['USERTYPE'];
$myurl =URL."putvote.php?csid=".$csid."&voterid=".$myid."&voteid=".$voteid."&usertype=".$usertype;
$myurl=str_replace(" ","%20",$myurl);
$jsondata = file_get_contents($myurl);
$data = json_decode($jsondata);
if($data->response=="true")
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax reponse use $.trim for IF ELSE
$.post("votepost.php", {CSID:csid,VOTEID:voteid,MYID:myid,USERTYPE:usertype}, function (data) {
if($.trim(data)=='true')
{
alert('ok');
}
else
{
alert('error');
}
});
I hope you will solve your problem
You can create the js blank array and assign it to the same array.
var resp = [];
jQuery.ajax({
dataType: "json",
method: 'post',
url: 'ajax.php',
async: false,
data: {postData: 'postData'},
success: function(data){
resp.push(data);
}
});