Why is my json data empty when using stringify to convert data? - php

When I use JSON.stringify, the data that is in it can't be send for some reason. But when I remove JSON.stringify, it does send and I would like to know why? Is there a way to controll the json data in PHP file without using stringify? Any help is much appreciated!
$(document).ready(function(){
$.ajax({
dataType: "jsonp",
url: "***/server/jsonp/data",
callback:"test",
success: jsonSuccess
});
function jsonSuccess( data ){
for( var i = 0; i < data.length; i++ ){
if ( i == 0 ) {
var formData = {name:"tolga",age:"25"}; // test object
$.ajax({
type: "POST",
url: "wp-content/themes/flex/saveJsonInfo.php",
data: { info: JSON.stringify(data[i]) }
}).done(function(data2) {
console.log(data2);
});
}
}
}
});
The json data that I receive is something like this:
test([{"EniNumber":"22325326","Name":"Test Fi","StartDate":"\/Date(1381788000000)\/","Rows":[{"T":42878,"Y":51.880965,"X":4.395925,"D":14.56},{"T":42879,"Y":51.880967,"X":4.395925,"D":14.56},{"T":42880,"Y":51.880967,"X":4.395925,"D":14.59}]}, {"EniNumber":"12312312","Name":"Test Fi 2","StartDate":"\/Date(13817880021300)\/","Rows":[{"T":42878,"Y":51.880965,"X":4.395925,"D":14.56},{"T":42879,"Y":51.880967,"X":4.395925,"D":14.56},{"T":42880,"Y":51.880967,"X":4.395925,"D":14.59}]}])
This is how my PHP example file looks:
$json_data = $_POST['info'];
if( isset($json_data) ){
echo json_encode( $json_data );
} else {
echo json_encode( "What happened?" );
}

Related

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

How to run PHP with Ajax to validate results?

I'm making a Ajax script which validates results with PHP file before processing. Below is my Ajax script but I don't understand how to retrieve this DATA to validate.php and how to get results back from my PHP file.
<script>
function shake(){
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(),
success: function(data){
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
How can I process this Ajax script with validate.php ?
Can it be like:
<?php
// Get values from AJAX
$userid = $_GET['userID'];
$pass = $_GET['pw'];
?>
What results is this Ajax script expecting? I see resultado==0
So my question is how can I send resultado=1 with PHP to this script?
Should it be:
<?php
// Send result to AJAX
$resultado = 1;
?>
Thank you for helping.
I think this is what you're asking for.
The php script at the bottom is missing the closing tag for a reason.
In the success function, after you parse the result into a json object, you can reference the members with a '.' E.G result.varName
<script>
function shake()
{
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else
{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: {userID: $("#userID").val(), pw: $("#pw").val()},
success: function(data){
try
{
var result = $.parseJSON(data);
// result is now a JSON object
}
catch (e)
{
alert("JSON Parsing Failed on" + data );
return 0;
}
console.log(result);
if(result.isValid === 1){
// do something
}
alert(result.Message);
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else
{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
<?php
if( !isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST')
{
exit;
}
if( !isset($_POST['userID']) || !isset($_POST['pw']) )
{
// need more validation than this
exit;
}
$output = array();
$output['isValid'] = '1';
$output['Message'] = 'Data transfered';
$output['moreData'] = false;
echo json_encode($output);
Change data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(), to:
data: {userID: $("#userID").val(), pw: $("#pw").val()}
Also, I'd recommend setting userID and pw vars before passing it in as it is easier to read and easier to maintain.

Processing json array in PHP sent via jquery

I am trying to consume a JSON array in PHP sent via JQuery. The data being sent to the server is in this format:
[{"id":"7","start":"00:00","end":"02:30","date":"2013-11-15"},{"id":"10","start":"23:00","end":"23:30","date":"2013-11-15"},{"id":"5","start":"13:00","end":"14:00","date":"2013-11-16"},{"id":"6","start":"18:00","end":"18:45","date":"2013-11-16"}]
I am sending the above data to the server through this function:
$('#updateOverallChanges').click(function(event){
var formArray = new Array();
$('.updateForm').each(function( index ) {
formArray.push($(this).JSONFromSerialize());
});
$.ajax({
url: 'inner/formTester.php',
data: JSON.stringify(formArray),
type: 'POST',
contentType: "application/json; charset=utf-8",
});
});
The function JSONFromSerialize is responsible for converting the form in meaningful json data:
(function($) {
$.fn.JSONFromSerialize = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
I am using the following PHP code to process the JSON array:
<?php
$params = json_decode($_POST[]);
echo $params;
?>
But the above code give the following output:
Fatal error: Cannot use [] for reading in C:\xampp\htdocs\holidaymanager\inner\formTester.php on line 2
Second attempt
Modified the payload to be a name value pair:
var postData = {
data : formArray
};
$.ajax({
url: 'inner/formTester.php',
data: JSON.stringify(postData),
type: 'POST',
contentType: "application/json; charset=utf-8",
});
The post data is:
{"data":[{"id":"7","start":"00:00","end":"02:30","date":"2013-11-15"},{"id":"10","start":"23:00","end":"23:30","date":"2013-11-15"},{"id":"5","start":"13:00","end":"14:00","date":"2013-11-16"},{"id":"6","start":"18:00","end":"18:45","date":"2013-11-16"}]}
The php code still fails:
<?php
$params = json_decode($_POST["data"]);
echo $params;
?>
Error:
Notice: Undefined index: data in C:\xampp\htdocs\holidaymanager\inner\formTester.php on line 2
Please advice how can I consume a JSON array sent over to the backend written in PHP.
$.ajax({
data : {data:JSON.stringify(postData)},
})
in php
$params = $_POST['data']; // add this line
$params = json_decode($params,true);
print_r($params);
or else
$params = json_decode($_POST,true);
print_r($params);
you have pass 2nd argument true with json_Decode()...
hope it may help you

Jquery Ajax not receiving php response correctly

I'm sending a JSON response from php to jquery:
foreach ( $obj as $o )
{
$a[ $o->key] = utf8_encode($o->id);
}
die(json_encode($a));
my html/jquery code is:
$.ajax({
type:'POST',
url: "imoveis/carrega_bairros",
data: ({cidade:10}),
dataType:"json",
success: function(ret)
{ alert(ret)
if(ret.success)
{
// ...
}
else
alert("error");
}
});
The json response is perfect (i get it on the console), but jquery is receiving a NULL ret object and it alerts "error". What's the problem???
Add a JSON header to the top of your PHP file:
header('Content-type: application/json');
use this:-
<?php
$temp = array();
foreach ( $obj as $o )
{
$temp[ $o->key] = utf8_encode($o->id);
$a[] = $temp;
}
die(json_encode(array('valid' => true,'content'=>$a)));
?>
in javascript:-
$.ajax({
type:'POST',
url: "imoveis/carrega_bairros",
data: ({cidade:10}),
dataType:"json",
success: function(ret)
{
if(ret.valid == true)
{
// get your array as
var arr = ret.content;
alert(arr)
}
else
{
alert('error occured');
}
}
});

ajax json decode returning undefined not data

I'm trying to pull json data via ajax from a PHP script, but it is not working.
while ($row = mysql_fetch_array($result)) {
$response = array(
'hello' => $row['name']
);
$responses[] = $response;
}
echo json_encode($responses);
Then I use this JavaScript
$('.clickme').click(function() {
$.ajax({
url: 'http://example.com/testFixGet.php?department=1',
dataType: 'json',
data: 'manufacturer=alpine,kicker',
success: function(json) {
alert(json['hello']);
$('.result_new').html(json);
}
});
});
The dialog presents: 'Undefined'
But, if I actually load the php page the data is json decoded and it looks like this:
[{"hello":"Rand McNally Soft Case for Most 5\" GPS"}]
You'll notice your JSON payload contains an array with one object element. Try
alert(json[0]['hello']);
Also, getJSON() is much more concise
$('.clickme').click(function() {
$.getJSON('http://example.com/testFixGet.php', {
department: 1,
manufacturer: 'alpine,kicker'
}, function(json) {
// loop over results
for (var i = 0; i < json.length; i++) {
var response = json[i];
console.log(response);
}
});
});
Try this:
$('.clickme').click(function() {
$.getJSON('testFixGet.php', { manufacturer: "alpine,kicker", department: "1" }, function(json) {
alert(json[0].hello);
$('.result_new').html(json);
} );
}
Are you setting the content type?
header('Content-type: application/json');
ANd by the way
[{"hello":"Rand McNally Soft Case for Most 5\" GPS"}]
it is an array so it would be
alert(json[0]["hello"]);
To loop
var bar = [{"a":"1"},{"a":"2"},{"a":"3"}]
$.each( bar, function(i, jObj){
alert( jObj.a );
});

Categories