$.ajax callback function is not working - php

I am just starting to learn JSON where a tutorial from other site uses this code (which I already modified to simplify this):
$(document).ready(function(){
$('#getdata-button').click(function(){
$.ajax({
type: "GET",
url: "json-data.php",
dataType: "json",
success: function(){
alert('a');
$('#showdata').html(
"<p>item1="+data.item1+
" item2="+data.item2+
" item3="+data.item3+"</p>"
);
}
});
});
});
And this is the code for json-data.php
<?php
$item1 = "candy";
$item2 = "chocolate";
$item3 = "ice cream";
//return in JSON format
echo "{";
echo "item1: ", json_encode($item1), "\n";
echo "item2: ", json_encode($item2), "\n";
echo "item3: ", json_encode($item3), "\n";
echo "}";
?>
The problem is that alert function (for debugging purposes) isn't responding after I have clicked the button (with the id of "getdata-button"). Firebug says that the request is successful and I can see the data from there. No error was found. It is just the callback function is not executing, but why?

You need to output your JSON correctly. Replace your PHP with the below
$items = array(
'item1' => $item1,
'item2' => $item2,
'item3' => $item3
);
header('Content-type: application/json');
echo json_encode($items);

Related

Making AJAX JSON request to PHP file (parse error)

I have a PHP file in which I'm getting data from a geoJSON file, I'm going through the data and storing what I need in a new associative array, then sorting it. I need to make an AJAX call to this PHP file to get the sorted data through, but it's throwing "SyntaxError: Unexpected token a in JSON at position 0", the "a" being "a"rray... from the response, so I believe it's going through as a string.
My PHP file:
<?php
$countryBordersJson = file_get_contents("../js/countryBorders.geojson");
$countryBordersJsonData = json_decode($countryBordersJson, true);
$dataLength = count($countryBordersJsonData['features']);
$countryNames = array();
for($i = 0; $i < $dataLength; $i++) {
$countryName = $countryBordersJsonData['features'][$i]['properties']['name'];
$countryIsoa2 = $countryBordersJsonData['features'][$i]['properties']['iso_a2'];
$country[$i]['countryName'] = $countryName;
$country[$i]['iso_a2'] = $countryIsoa2;
array_push($countryNames, $country[$i]);
}
sort($countryNames);
$data = json_encode($countryNames);
$decode = json_decode($data, true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['data'] = $decode;
header('Content-Type: application/json');
var_dump($output);
?>
My AJAX request:
$.ajax({
url: "libs/php/countryBorders.php",
dataType: "json",
type: "GET",
success: function(result) {
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn(jqXHR.responseText, textStatus, errorThrown);
}
})
I'm still getting to grips with JSON, PHP etc. so would appreciate any help.
Are you sending the data with var_dump ? It cannot work like that. You need to send a string :
echo json_encode($output);

AJAX datatype JSON and HTML

I am following a tutorial about ajax and I have made this script, where I get data as JSON and append them into a table:
$.ajax({
url: 'insert.php',
type: 'POST',
data: {data1: name, data2: phone, data3: address},
dataType: "json",
success:function(res){
//if(data=="success")
//{
//alert("Data added");
//console.log(arr.id);
$("#trId").before("<tr><td>"+res.emp_name+"</td><td>"+res.ph+"</td><td>"+res.add+"</td></tr>");
//}
},
error:function(res){
alert("data not added");
}
And here is the PHP code:
$insert = "INSERT into employee(emp_name, phone, address) VALUES (:emp_name, :ph, :add)";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":emp_name", $emp_name);
$insertStmt->bindValue(":ph", $pos);
$insertStmt->bindValue(":add", $address);
$insertStmt->execute();
//echo "success";
$lastid = $conn->lastInsertId();
$res = array('name'=>$emp_name, 'ph'=>$pos, 'add'=>$address, 'id'=>$lastid);
echo json_encode($res);
Our instructor asked us to transform this script, from JSON as datatype into HTML, and make the initial changes for it. But I can't figure out what should the PHP code returns now, and how to append the returned values into the table.
Secondly, why some people use HTML as datatype while JSON is better ?
Set dataType to html:
dataType: "html"
And render html on server:
$res = array('name'=>$emp_name, 'ph'=>$pos, 'add'=>$address, 'id'=>$lastid);
echo "<tr><td>" . $res['name'] . "</td><td>" . $res['ph'] . "</td><td>" . $res['add'] . "</td></tr>"";
So in a success callback you will receive html:
success: function(res) {
$("#trId").before( res );
}
Why use html instead of json - is an opinion-based or a case-based question.

functions.php script breaks when variable isn't hard coded

I have written a jQuery script that takes a JSON encoded list produced with this function is run in my theme's functions.php and creates a playlist for my jPlayer. However, the script only works when the $file variable is hard coded (for example, OH0400). But I need it to pick up the $file variable based on the page being loaded. But when I switch to this method (using URL), the script says the JSON is null.
I've run the script in multiple ways and the output between the hard coded $file and the variable based $file appear to be the same. Why do I get null when I make the switch?
Here's the PHP in my theme functions.php.
function MyjPlayerList(){
$url = explode( '/', $_SERVER['REQUEST_URI'] );
$file = strtoupper($url[2]);
//$file = 'OH0400';
$filename = '/dir/oralhistory/mp3files/'.$file.'*.mp3';
$FILES = glob( $filename );
foreach( $FILES as $key => $mp3 ) {
$mp3 = str_replace( '/dir/oralhistory/mp3files/', '',$mp3);
$FILE_LIST[ $key ][ 'title' ] = $mp3;
$FILE_LIST[ $key ][ 'mp3' ] = 'http://websiteurl.org/mp3files/'.$mp3;
}
$myjplayerdata = json_encode( $FILE_LIST );
header ( 'Content-type: application/json' );
echo $myjplayerdata;
exit;
die();
};
Here is my javascript:
ajax_player = function() {
jQuery('div#player').load('/js/player.html' , function() {
var cssSelector= {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "/js/Jplayer.swf",
supplied: "mp3",
smoothPlayBar: true,
keyEnabled: true
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
jQuery.ajax({
url: "/wp-admin/admin-ajax.php" ,
type: "POST",
dataType: "text json",
data: { action: "MyjPlayerList"},
success:(function(data) {
jQuery.each(data, function(index, value){
myPlaylist.add(value); // add each element in data in myPlaylist
console.log(data);
})
})//function (data) close
})//ajax close
})//jquery.load
}//ajax_player
Yes, check the character encoding you're using. That could be the problem.
thanks to the debugging of Marc,turns out that what I get when i run the script in page & what i get when I call the script w/ javascript are different. it's trying to glob admin-ajax.php instead of the URL.

AJAX POST return data not appearing

I have an AJAX call which runs on a form submit (with prevent default to stop standard submit):
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
$('#processingFile').hide();
$('#downloadFile').show();
$('#shareURL').val(data.url);
$('#downloadFile').attr('href', data.url);
$('#aboutFile').html('<b>File URL:</b> ' + data.url + '<br /><b>File Size:</b> ' + data.size + '<br /><b>Time Stamp:</b> ' + data.timestamp + '<br /><b>Client IP:</b> ' + data.ip);
}).fail(function() {
$('#saveFile').hide();
$('#error').show();
});
The file it submits to is a PHP file which is as follows:
// VARIABLES
$fileURL = $_POST['fileURL'];
$tmpURL = substr(md5(rand()), 0, 7);
$deleteCode = md5($tmpURL);
// COOKIE
setcookie($tmpURL, $deleteCode, time()+86400);
// SAVE FILE
if($fileURL){
file_put_contents("tmp/" . $tmpFile, file_get_contents("http://" . $fileURL));
}
// OUTPUT
$result = array(
'url' => "tmp/" . $tmpFile,
'size' => filesize("tmp/" . $tmpFile) * .0009765625 * .0009765625,
'timestamp' => date('H:i:s d-m-Y'),
'ip' => $_SERVER['REMOTE_ADDR']
);
echo json_encode($result);
When the script is run everywhere which uses data.x in the jQuery returns undefined. Any idea why that happens and how to fix it?
data is a string containing your returned JSON text; it isn't an object.
To parse the JSON object, you have a couple of options:
Call JSON.parse() yourself.
Pass dataType: "json" to tell jQuery AJAX to parse it for you.
Set Content-Type: application/json in the server's response so that jQuery knows to parse it for you.
Set dataType: 'json' and check! Look this doc and set your datType.

escape json to be read as array in php

i am stuck with this for quiet sometime now.
all i am trying to do is send a json text to php, process it and send a response bacl..
here is the data i am sending as my textarea value..
**asdasd #$**&**%^*( AAAA SADQWEASD /// '' \\\ '' l; "" **
below is the json sent to php (got it from console):
data={"Text":"asdasd #$&%^*( AAAA SADQWEASD /// '' \\\\\\ '' l; \"\" "}
i am using jquery ajax function as below:
function ajaxfunc(data, path){
$.ajax({
type: "POST",
url: path,
data: 'data='+data,
success: function(response){
}
});
}
in php, i am doing this.
$res = json_decode(stripslashes(escapeJsonString($_POST['feed'])), true);
function escapeJsonString($value) {
# list from www.json.org: (\b backspace, \f formfeed)
$search = array("\n", "\r", "\u", "\t", "\f", "\b", "/", '"');
$replace = array("\\n", "\\r", "\\u", "\\t", "\\f", "\\b", "\/", "\"");
$result = str_replace($search, $replace, $value);
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
echo $res["Text"];
issue is : & .. is not getting parsed at php and hence the response is null..
i also wanted to make sure, the new line characters are detected.. basically i am expecting "WYSIWYG" using json.. json_encode and json_decode
Based on the comment about just wanting to send form inputs to the server, use serialize() in the following way:
$.ajax({
type: "POST",
url: path,
data: $('form').serialize(),
success: function(response){
}
);
If all you want to do is access the form inputs on the server through the $_POST array then converting to JSON on the client is a waste of effort. serialize() should work perfectly for you.
But if you really want to use a JSON then use the JSON-js lib by Douglas Crockford here. Note that there is a lot of other info on this topic: Serializing to JSON in jQuery. Example below:
$.ajax({
type: "POST",
url: path,
data: 'data='+( JSON.stringify(data) ),
success: function(response){
}
);
if you want to send a data in JSON format, you can try this
data = {"Text":"asdasd #$&%^*( AAAA SADQWEASD /// '' \\\\\\ '' l; \"\" "};
data = JSON.stringify(data);
then send with your jquery.ajax or jquery.post

Categories