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.
Related
I have a question here, I try to transfer a variable to my PHP script in order to retrieve data from Bing Search API.
I use the following AJAX code:
var bingquery = 'bingquery=' + $('#query').val();
console.log(bingquery);
$.ajax({
method: "POST",
url: "hw8.php",
dataType: "json",
data: bingquery,
success: function(jsondata){
console.log('***Test for News Feeds***');
console.log(jsondata);
}
});
And my PHP is:
if (isset($_POST["bingquery"])){
// Replace this value with your account key
$accountKey = '***myaccountkey***';
$WebSearchURL = 'https://api.datamarket.azure.com/Bing/Search/v1/' + 'News?$format=json&Query=';
$cred = sprintf('Authorization: Basic %s', base64_encode($accountKey . ":" . $accountKey) );
$context = stream_context_create(array(
'http' => array(
'header' => $cred
)
));
$request = $WebSearchURL . urlencode( '\'' . $_POST["bingquery"] . '\'');
//if I hard code the request URL here, it does work.
$response = file_get_contents($request, 0, $context);
echo $response;
}
I wonder if there is something wrong with my URL encoding? Because the console says file_get_contents(0%27MYSYMBOL%27) fails, MYSYMBOL is the string I want in the search.
Thank you so much for your help!
There is nothing wrong about the encoding at all, urlencode is supposed to make the input string url safe, and that is exactly what it is doing, \ has special meaning in a url and hence it is being encoded by the function.
UPDATE
You are adding up two strings, in PHP . is used to concatenate two strings, make the following changes,
$WebSearchURL = 'https://api.datamarket.azure.com/Bing/Search/v1/News';
$request = $WebSearchURL .'?Query='.urlencode($_POST["bingquery"]).'&$format=json;
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.
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
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);
//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/