Post data using AJAX then retrieving the value of JSON array - php

I am trying to create a validation to check if my data already exist or not using Ajax. It's works, but now I want to add JSON inside my Ajax php file and retrieve the array inside of the JSON, unfortunately it doesn't work as expected.
Take a look at my JQuery below :
$("#button").click(function(e) {
e.preventDefault();
var tempcode = $('#someobject').val();
$.ajax({
method:"POST",
dataType: "text",
url:'example.php',
data:{
Code: tempcode
},
success:function(data){
var my = JSON.parse(data);
alert(my.Title);
}
});
});
And below is example.php :
$AJAXCode = $_POST['Code'];
$myObj = array();
$strSQL = mysql_query("select * from sometable where Code ='$AJAXCode'");
$check = mysql_num_rows($strSQL);
if ($AJAXCode == NULL) {
$myObj->Title= "Choose Something";
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
} else {
if ($check != 0) {
$myObj->Title= "Already Exist !";
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
} else {
$myObj->Title= "You are good !!!";;
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
}
}
As you can see at my JQuery scripts, I am trying to call "Title" inside my JSON array, but it doesn't work. Am I missing something ?
This is the result in Console.log, no error show up just this:

Firstly, you initialize your object the wrong way. Use instead of $myObj = array(); one of the following:
$myObj = (object) array();
or
$myObj = new StdClass();
For more information and more ways to create your object, look up this link.
Next, change the dataType attribute to:
dataType: "json"
in order to tell your script that your PHP response is encoded as JSON. You can use now your response the regular way, with JSON.parse(), try:
console.log(JSON.parse(data));

Replace Below Code :
$("#button").click(function(e) {
e.preventDefault();
var tempcode = $('#someobject').val();
$.ajax({
method:"POST",
dataType: "json",
url:'example.php',
data:{
Code: tempkode
},
success:function(data){
console.log(data.Title); // Example
}
});
});

Change variable tempkode to tempcode in data

Related

Undefined Variable in Ajax from PHP

I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}

Angular encoding data

I've got this code
Javascript
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data;
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
That is trying to get some table numbers, but when this really works it shows me the parameter name and the value, i need only the value, what can i do to get only the value so not the parameter name?
I'm using PHP as database connector.
PHP Code
<?php
include('base.php');
$data = array();
$result = mysql_query('SELECT table_number FROM waiters_assigned ORDER BY id',$connect);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
} else {
echo "0 results";
};
echo json_encode($data);
mysql_close($connect);
?>
The result is this one: {"table_number":"3"} what i need is just: 3
Firstly, please dont use mysql_query you should have a look at PDO or at the very least mysqli, for security and because it is deprecated.
As for returning just the number, update your while to return the field you desire:
while($row = mysql_fetch_assoc($result)){ $data[] = (int)$row['table_number']; }
When looking at your PHP i believe you're actually getting [{"table_number":"3"}], as you're json_encodeing an array.
The reason updating your PHP is better than updating your Javascript is that you appear to be returning an array of objects currently, when you actually want to return an array of numbers. Doing things the JS way you'll need to cycle through the response, parseInt on the strings, and strip the object down to a number. Far easier and more efficient to just send the correct data.
In your php code use mysqli or pdo extension because mysql extension is deprecated.
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data.table_number;//outputs 3
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
It's very simple:
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data ? "" + response.data.table_number : "";
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

jquery.ajax creates non-object error

hey there i have this jquery:
var input = JSON.stringify(data); // output: [100.100]
var lines = input.split('.');
var vari1 = lines[0]; // output: [100
var vari2 = lines[1]; // output: 100]
var data = {'x':vari1+"."+vari2};
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success : function(data) {
alert(data);
}
});
checkAvailability.php:
$data = $_POST['data'];
$data = json_decode($data,true);
if($availabilityChecker->check_availability($data['x'])) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
but than i get:
Call to a member function check_availability() on a non-object
for this line:
if($availabilityChecker->check_availability($data['x'])) {
i just want to get this string "100.100" in my check_availability-function, how to do this? greetings
in your PHP, it sounds like $availabilityChecker is a simple variable or an array. You're trying to call a method inside that object but it's not one to call. To be an object instance it needs to have something like
$availabilityChecker = new Class();

Categories