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);
Related
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
I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});
I need help to do something small but I don't know how to solve it.
I have a javascript file with ajax inside like this
$.ajax({
data: "mc_id="+someid,
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_GET['mc_id'])) {
$id = $_GET['mc_id'];
}
//some process here $data
echo json_encode($data);
I can get data from $_GET['mc_id'] but when I need more data and I change the parameters in javascript like this
$.ajax({
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
url: "includes/getDataPrs.php",
and then I got nothing in php $_GET['mc_id'] or $_GET['limit']
in my desperate to solve it, I put in url "includes/getDataPrs.php?mc_id=someid&limit=somelimit
any comment or suggestion I truly appreciated
thanks in advance
passing multiple variable in ajax should be like
$.ajax({
data: {mc_id: someid, limit: some_limit},
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
It is always better to use data: {mc_id: someid, limit: some_limit} because it will treated like object itself.
Try using following syntax for sending data in ajax function:
...
data:{mc_id:someid,limit:somelimit},
...
Without using quotes.
Change from
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
To
data: "mc_id="+someid+"&limit="+somelimit,
Follow the below steps:
1) Replace `data: "mc_id="+someid,` with `data: { mc_id: someid},`. (required)
2) Now you can get your data in PHP file like `$_POST['mc_id']` (optional). It is better to use `type: 'POST'`in your jQuery code.
So below is your whole code:
$.ajax({
data: { mc_id: someid},
url: "includes/getDataPrs.php",
type: 'POST',
dataType: "json",
async: false,
success: function(msg){
//some function here
}});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_POST['mc_id'])) {
$id = $_POST['mc_id'];
}
//some process here $data
echo json_encode($data);
?>
You try this
$.ajax({
type: "POST",
url: "includes/getDataPrs.php",
data: {'mc_id': someid, 'limit': somelimit}.done(function (response) {
//
});
});
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);
}
});
That is my function, for exp.:
adId = 1, adTitle = test
function deleteAd(adId, adTitle) {
$.ajax({
dataType: 'json',
url: 'ajax.php',
type: 'POST',
data: {
adId : adId,
adTitle: adTitle
},
success: function(data) {
alert(data);
}
});
That is ajax.php:
echo $_POST['adId']; echo $_POST['adTitle'];
But echo only adId, don't have adTitle.
I try this:
data: {
adId : adId,
adTitle: "test"
},
And don't have result too. With HttpFox I found this post and postdata is: adId=1&&adTitle=test
If your variable test === undefined then it will not get posted to your PHP script therefore you will not see it on the server side.
If test is an empty string than you just might not be seeing it on the client due to it not having any visible length.
Try doing: var_dump($_POST['adTitle']);