error when post to php with ajax and json - javascript

I tried everything but it still don't work.
Without $_POST value it is working, without JSON it's working, with both it's not.
Function shows this error:
<b>Notice</b>: Undefined index: someVar1 in <b>C:\xampp\htdocs\ajax3\test.php</b> on line <b>2</b><br />
Array()
{"jeden":"Po obr\u00f3bce 123 123 ","dwa":null}"
script.js
$(document).ready(function(){
var data = {
someVar1: '123'
};
data = JSON.stringify(data);
$.ajax({
method: "POST",
url: "test.php",
dataType : 'json',
contentType: "application/json; charset=utf-8",
data: data,
success: function(json) {
$.each(json, function(i, ob) {
console.log(i, ob);
});
},
error: function(error) {
console.log(error);
}
});
});
and test.php
<?php
$someVar1 = $_POST['someVar1'];
$a = " 123 ";
$result = array();
$result['jeden'] = 'Po obróbce ' . $a . $a;
$result['dwa'] = $someVar1;
echo json_encode($result);
?>

It because you send data in JSON format. $_POST will be empty always
In this case you need to use I/O stream
Try this
$postData = json_decode(file_get_content('php://input'));
look more http://php.net/manual/en/wrappers.php.php

Related

Jquery + Ajax, Params has data but response says no data

I have the following script:
$("#spid").blur(function() {
$.ajax({
url: 'getsponsor.php',
type: "POST",
dataType:'json',
data: ({ spid: $("#spid").val() }) ,
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#sponname").text(result);
},
error: function () {
$("#sponname").text("Cannot fetch the sponsor name.");
}
});
});
Note: #sponname is a label tag.
Following is the php code of getsponsor.php:
if(!isset($_POST['spid']) || empty($_POST['spid']))
echo json_encode("No Data");
else {
$spid=$_POST['spid'];
$stmt = $con->prepare("SELECT name FROM users WHERE id=?");
$stmt->bind_param("s",$spid);
$stmt->execute();
$stmt = $stmt->get_result();
if ($stmt->num_rows >0) {
$row = $stmt->fetch_object();
echo json_encode($row->name);
}
else {
echo json_encode("No Records");
}
}
When I Inspect the page and goto Network->Params, I get the right value from the textbox:
spid=1125468
But, when I go to Network->Response, I get the following message
"No Data"
Please tell what wrong I am doing?
Get rid of this line:
contentType: 'application/json; charset=utf-8',
The data is being sent URL-encoded, not as JSON. jQuery will send the correct Content-type header by itself.

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);

Use JSON result when ajax success

I have this code:
function openIzmeni(value) {
$.ajax({
url: "getRzaizmenu.php",
type: "POST",
async: true,
data: { vrednostid:value}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
console.log(data);
$('#brojracuna1').val(data[0].br);
console.log(data[0].br);
console.log(data.br);
so as you can see I call getRzaizmenu.php to get JSON output.
getRzaizmenu.php code is:
try {
$result = $db->prepare("SELECT * FROM racuni WHERE ID=:id AND user_id=:user_id");
$result->execute(array(':id' => $_POST['vrednostid'], ':user_id' => $user_id));
$result = $result->fetchAll();
$r= json_encode($result);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $r;
and this php return me output:
[{"ID":"22","0":"22","prefiks":"","1":"","br":"14321","2":"14321","sufiks":"993.67","3":"993.67","kupac":"Pavle Aleksov","4":"Pavle Aleksov","adresa":"Desanka Maksimovic 6\/a","5":"Desanka Maksimovic 6\/a","grad":"18320 Dimitrovgrad","6":"18320 Dimitrovgrad","pib":"567890","7":"567890","total":"1200.00","8":"1200.00","valuta":"Din","9":"Din","nacin":"gotovinsko","10":"gotovinsko","datum":"2015-05-25","11":"2015-05-25","rok":"2015-05-25","12":"2015-05-25","isporuka":"2015-05-25","13":"2015-05-25","naplaceno":"0000-00-00","14":"0000-00-00","napomene":"","15":"","interne":"","16":"","jezik":"","17":"","status":"","18":"","sifra":"yyx5y","19":"yyx5y","user_id":"1","20":"1"}]
So this code return me "0":22 and "ID":22 but its the same column.
and you can see I try to use this data into ajax success function like this:
success: function(data) {
console.log(data);
$('#brojracuna1').val(data[0].br);
console.log(data[0].br);
console.log(data.br);
but I get undefined.
How I can use data in success?
Change
dataType: "html",
to
dataType: "json",
And try again.
you have encoded the data, that's ok.
But while parsing you are not decoding the data. So you have to decode the data using JSON.parse() and parse function.
You need to parse the JSON, try like this
success: function(data) {
$.each(data, function(index, element) {
console.log(index);
console.log(element);
});
});

Issue with decoding json array in php

Okay now i am having a weird issue here, sometime back i learned how to encode and decode a json array properly here on stackoverflow but now i am having a weird issue on my godaddy server that i cannot comprehend, maybe i may have made i typo or something somewhere in code but i honestly cannot tell what is wrong here. The code works okay on my localhost but not when i upload it too my godaddy server.
The code here is basically supposed to pass an id as a json to the php server which is then supposed to execute a query using the id as a parameter.
Here is the jquery code:
<script text="text/javascript">
$(document).ready(function() {
$('#download').click(function(e) {
// e.preventDefault();
var tid = $('#id').val().trim();
var data = {
ID:tid
};
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
}
});
});
});
</script>
and this is the php code:
<?php
if (isset($_POST['data']))
{
$Data = $_POST["data"];
$arr = json_decode($Data);
$id = $arr->ID;
$sql = $pdo->prepare("update ********** set ******** = ******** + 1 where id=:id");
$sql->bindValue("id", $id, PDO::PARAM_INT);
$sql->execute();
unset($_POST['data']);
}
?>
Now i checked if the value was being sent to the server using my browser console and it was. I also checked if the $_POST['data'] on the server contained any data using var_dump and it did in fact have the data i wanted.
in the ajax set the content type to contentType: "application/json",
so:
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
contentType: "application/json",
success: function(response) {
}
});
and in the php use:
$json = file_get_contents('php://input');
$data = json_decode($json);

How to get the ajax response from success and assign it in a variable using jQuery?

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);
}
});

Categories

Resources