Hi I would like to output the code in [json['information'] as actual converted html code.
At the moment it seems to be just outputting the entire string as pure text (unformatted html, so you can see all the tags etc)
Im still learning about json so am unsure what is supposed to be done with the content recieved to make it proper html.
Thanks in advance
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_for : 'engineering'},
dataType: 'json',
success: function(json){
$('#engineering-content').html(json['information']);
},
error: function(json) {
alert('fail');
}
});
});
EDIT, heres the PHP ...
public function homepage_info() {
$this->load->model('catalog/information');
$json = array();
if (isset($this->request->post['info_for'])) {
if ($this->request->post['info_for'] == 'engineering') {
$information_info = $this->model_catalog_information->getInformation(10);
$json['information'] = $information_info['description'];
}
$this->response->setOutput(json_encode($json));
}
}
Your HTML strings seem to be encoding special characters as HTML entities, like < to <, etc. From the PHP you've shown, it's probably encoded in the database (maybe you're encoding before saving).
You should be able to fix it with html_entity_decode:
$json['information'] = html_entity_decode($information_info['description']);
// or, a few lines later:
// $this->response->setOutput(html_entity_decode(json_encode($json)));
Looks like you are using Open cart for you php controller. In order to send back a a response with the proper json headers the Open Cart way is as follows:
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
Hope that helps.
Related
I am trying to do an ajax request to my php, but for some unknown reason it seems to fail as i don't get to the success part where I have a console.log
Can anyone please give me some hint what might be wron with this, I am stuck for too long now??
Here is how my jQuery looks :
getPending();
function getPending(){
var usernameLS = localStorage.getItem('userNameLS');
var userTypeLS = localStorage.getItem('isAdminLS');
if (userTypeLS!=1) {
console.log("inside");//i am getting here
$.ajax({
type: "POST",
dataType: 'json',
url: 'get-pending.php',
data: {
data: usernameLS //this is a string, "user2" for instance
},
success: function(data) {
console.log("Thanks!!!",data);//i never got here
},
failure: function() {
console.log("Error!");
alert(' Fail');
}
});
}
And here is my php :
<?php
$string = file_get_contents("appointments.json");
$usernameAjax = $_POST['data'];
var_dump($usernameAjax);
$json_a = json_decode($string, true);
$isPending;
foreach ($json_a as &$json_r) {
if ($usernameAjax==$json_r['userName'] && $json_r['status'] = "Pending") {
$isPending = 1;
}
else{
$isPending = 0;
}
}
var_dump($isPending);
echo $isPending; //i tried with a hardcodede 1 or 0 zero. Didn't work.
?>
Seems like your output is not correct JSON format, so client-side cant understand what was recieved.
First - remove var_dump, it breaks json format anyway;
Second - jou just output 1 or 0 - that is not correct json too; use json_encode to format reply properly;
Third - php files often contains trailing symbols after ?>, that are appends to output too and could break output format. Dont close php with ?> at all; additionally you could use die($output) instead of echo($output) to avoid any output after your data was written
I am trying to make an image upload where the JavaScript posts DataURI of an image via AJAX and the PHP receives it to decode it into an image.
The problem is, everything is working fine except that the end product is not an image file.
Please have a look at the following example code.
JavaScript:
dataString='encodedimg='+e.target.result.match(/,(.*)$/)[1]+'&type='+type;
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
data: dataString,
success: function(data){
//print success message
});
PHP:
$encodedimg = $_POST['encodedimg'];
file_put_contents('asdf.png', base64_decode($encodedimg));
There is no problem with $_POST['encodedimg'] as it produces the right image using online base64 converter. So I am assuming that there is a misuse with file_put_contents() or base64_decode().
Appreciate the help!
To read image on PHP i used a function like this
function rcd($data) {
$p = strpos($data, ',');
$d = base64_decode(substr($data, $p+1));
$rfn = md5(mt_rand(1,123123123));
file_put_contents($rfn, $d, LOCK_EX);
return $rfn;
}
Usage example:
$img_file_name = rcd($_POST['image_data']);
On JS part it is tricky (different browsers, etc). First of all You need to have the image data. Now You do not precise how this is sourced and the code example does not give a hint. We can assume some options
Simple You get dataString properly populated by whatever means neccesary, then Your example should basically work
imgdata = .... // any means of getting the data
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
});
Not so simple You have a Canvas object on the screen which was populated by any means and You want to send that data. Whatever above is true, however the way to get image data would be
var canv = document.getElementById('id_of_canvas');
imgdata = canv. toDataURL('image/jpeg', 0.88); // last arg is quality
However, as some browsers (mobiles) might not be so lucky to support this, you might want to find JPEGEncoder for JS and add it, along with the code below, to Your project.
var tdu = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function(type,param1)
{
var res = tdu.apply(this,arguments);
if(res.substr(0,11) != "data:image/")
{
var encoder = new JPEGEncoder();
return encoder.encode(this.getContext("2d").getImageData(0,0,this.width,this.height), (param1 ? param1*100 : 88));
}
else return res;
}
Hope this helps!
FOr #Marcin Gałczyński:
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
}
})
I think jQuery.ajax didnt have image_data jQuery.ajax
i like to retrieve a string with an Ajax call but i keep getting the whole html page in my response.
What is the way to just retrieve the string?
$.ajax({
url: '{$domainpath}{$language}/reservations/updatestartdates',
data: {property:property,stayduration:stayduration},
type: 'POST',
dataType: 'json'
}).done(function(response){
alert(response);
});
private function updateAvailableStartDates(){
if(isset($_POST['property']) && !empty($_POST['property']) && isset($_POST['stayduration']) && !empty($_POST['stayduration'])){
$property = $_POST['property'];
$stayduration = $_POST['stayduration'];
}
//handle code
echo json_encode('only this string');
}
It will retrieve all the output from url: '{$domainpath}{$language}/reservations/updatestartdates',
So if you want string then only echo string in your server page(Remove all html output)
Also Change echo json_encode('only this string'); to echo json_encode(array('only this string'));
Typically a good idea to exit right after printing JSON to prevent content (maybe \n) from breaking the response.
echo json_encode('only this string');
exit();
I think your function send response with layout enabled mode, so that string comes with wrapped layout. May be you need to disable layout in the controller for the calling function
(url: '{$domainpath{$language}/reservations/updatestartdates').
I'm still in AJAX stuff since morning so maybe thats the reason why some things does't work as they schould - let's forget about it. To sum up, my problem is coincident with passing HTML via JSON. An example of the PHP code:
$list = "<strong>This is test</strong>";
$response = array('success'=>true, 'src' => $list);
echo json_encode($response);
Basicly that's the main part of the code which is responsible for passing the HTML to AJAX. Now, let's have a look on part of AJAX code:
success: function(output)
{
alert(output);
json = $(output).find(".content").text();
var data = $.parseJSON(json);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
Some of you will ask what am I doing in this part:
json = $(output).find(".content").text();
The answer is: I retrieve the json string from the ".content" box, so when I alert variable "json: i get:
{"success":true,"src":"1. dsfasdfasdffbcvbcvb<\/span>Edytuj<\/span> <\/a>Usu \u0144<\/span><\/div>2. vbnvbnm454t<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div>3. ndfhgndgfhndfhgndfhd<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div><\/div>"}
The problem is that I do not get this HTML... I get only text witout any HTML tags, styles etc...
String which I get, rather than HTML:
"1. dsfasdfasdffbcvbcvbEdytujUsuń2. vbnvbnm454tEdytujUsuń3. ndfhgndgfhndfhgndfhdEdytujUsuń"
Please don't try to look for anything smart or gunius in the above string because u won't - it's only a test string.
Acording to the part of PHP code - in my case I get "This is test" rather than "This is test".
To sum up my question is, how to pass these HTML tags or whole HTML code via json from PHP to AJAX.
I think you're misunderstanding how jQuery.ajax() works. You just need to tell it that dataType: 'json' (meaning that you're expecting JSON output from the server), and it takes care of the rest. You don't need to use jQuery.parseJSON(). The success() method will be given a JavaScript object representing the server response.
success: function(output)
{
// output is a JS object here:
alert(output.success); // true
// ...
},
To get your HTML from that point, you would just access output.src.
You can specify dataType: 'json' in your ajax request and receive an object(i.e. json already parsed) in your success call. eg
$.ajax(url, {
dataType: 'json',
success: function(output)
{
if(output.success == true)
{
obj_a.parents(".row").append(output.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
if you can't change dataType you would call $.parseJSON on output
function(output)
{
alert(output);
var data = $.parseJSON(output);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}