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.
Related
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);
I've been able to sent FormData from angularJS to php, but I don't know how to do the reverse. I'm currently trying to get the $base64 variable into my angularJS, but I'm quite stumped on how to go about doing so. The documentation in the official angularJS doesn't help me much either
https://docs.angularjs.org/api/ng/service/$http
JS
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(){
// some magic code here that grabs the $base64 variable from php
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
PHP
<?php
$imgname = $_POST["FileName"];
$inputDir = "../../uploads/" . $imgname;
$outputDir = "../../processed/" . $imgname;
$MakeGray = "./makegray " . $inputDir . " " . $outputDir;
$runExec = exec($MakeGray, $out);
$type = pathinfo($outputDir, PATHINFO_EXTENSION);
$data = file_get_contents($outputDir);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "$base64";
?>
You can add a parameter in success callback to fetch the response from server if available.
var base64 = '';
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(response){
base64 = response; //response will contain whatever server echos to it's standard output
})
.error(function(){});
you can get the response from server by using
.then(function (data) {}
and in "data" variable you can find the value you're looking for
JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here
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.
//Jquery code to send the data with AJAX
$.ajax({
type: "POST",
url: "test.php",
data:
"fname="+ fname +
"& lname="+ lname +
"& address="+ address +
"& city="+ city +
"& state="+ state +
"& zip="+ zip +
"& phone="+ phone +
"& useremail="+ useremail +
//the following values are not being receieved by the php correctly
"& subtotal="+ subTotal +
"& quantity="+ quantity,
success: function(){
$('#oderBtn').hide(function({$('#orderTest').fadeOut();});
}
});
//PHP CODE TO RECEIVE THE AJAX DATA
$fname = htmlspecialchars(trim($_POST['fname']));
$lname = htmlspecialchars(trim($_POST['lname']));
$city = htmlspecialchars(trim($_POST['city']));
$state = htmlspecialchars(trim($_POST['state']));
$zip = htmlspecialchars(trim($_POST['zip']));
$address = htmlspecialchars(trim($_POST['address']));
$email = htmlspecialchars(trim($_POST['useremail']));
//these do not post correctly, i do not know why
$subTotal = htmlspecialchars(trim($_POST['subtotal']));
$quantity = htmlspecialchars(trim($_POST['quantity']));
So the problem is that fname, lname, city, state, zip, address, and email are all working but subtotal, and quantity are not working, firebug has them all POSTing in the same way, it seems like the PHP is just not recieving the data properly.
Adding echo file_get_contents("php://input"); to the php does get everything sent echoed back, including subtotal and quantity but just doing $_POST['subtotal'] will not get the value.
Thanks for any assistance in this matter.
Well, first, you don't need to build a string like that. You can simply pass an object literal:
$.ajax({
type: "POST",
url: "test.php",
data: {
fname: fname,
lname: lname
...
},
success: function(){
$('#oderBtn').hide(function({$('#orderTest').fadeOut();});
}
});
And jQuery will serialize it as necessary. I think it's impressive that it's honoring your POST request at all since you're passing it a query string.
Also, it looks suspicious that it stops working after the email. can you paste the result of print_r($_POST); in PHP?
Have you tried using $_GET[] rather than $_POST[]? That would be the first thing I'd try, since $_GET is designed for getting data from a URL, whereas $_POST is designed more for getting data passed in from a form submit.
$fname = htmlspecialchars(trim($_GET['fname']));
$lname = htmlspecialchars(trim($_GET['lname']));
$city = htmlspecialchars(trim($_GET['city']));
$state = htmlspecialchars(trim($_GET['state']));
$zip = htmlspecialchars(trim($_GET['zip']));
$address = htmlspecialchars(trim($_GET['address']));
$email = htmlspecialchars(trim($_GET['useremail']));
$subTotal = htmlspecialchars(trim($_GET['subtotal']));
$quantity = htmlspecialchars(trim($_GET['quantity']));
An example of this output as a JSON array:
$data = array(
'fname' => htmlspecialchars(trim($_GET['fname']));
'lname' => htmlspecialchars(trim($_GET['lname']));
'city' => htmlspecialchars(trim($_GET['city']));
'state' => htmlspecialchars(trim($_GET['state']));
'zip' => htmlspecialchars(trim($_GET['zip']));
'address' => htmlspecialchars(trim($_GET['address']));
'email' => htmlspecialchars(trim($_GET['useremail']));
'subTotal' => htmlspecialchars(trim($_GET['subtotal']));
'quantity' => htmlspecialchars(trim($_GET['quantity']));
);
echo json_encode($data);
EDIT:
You may also need to use encodeURI() in your jQuery to ensure that no ampersands or other characters mess up the URL string.
$.ajax({
type: "GET",
url: "test.php",
data: encodeURI(
"?fname=" + fname +
"&lname=" + lname +
"&address=" + address +
"&city=" + city +
"&state=" + state +
"&zip=" + zip +
"&phone=" + phone +
"&useremail=" + useremail +
"&subtotal=" + subTotal +
"&quantity=" + quantity
),
success: function(response){
alert(response); // Will show the JSON array
$('#oderBtn').hide(function({$('#orderTest').fadeOut();});
}
});
Fiddle: http://jsfiddle.net/xNSLX/