HTML Markup in PHP vs Javascript - php

I've been doing a lot of things that include making AJAX requests to get information from the backend of my site when i had an interesting question. Is it better to do the html styling in php, then send to the client, or is it better to send the data as json and then style in javascript?
Since this question is kind of vauge i'll give an example:
<?php
$data = array();
$data[0] = array("username" => "Supericy", "content" => "just a sample message 1");
$data[1] = array("username" => "Supericy", "content" => "just a sample message 2");
$data[2] = array("username" => "Supericy", "content" => "just a sample message 3");
// etc...
// now this is the choice:
if ($json)
{
return json_encode($data);
}
else
{
// or
$returnString = "";
for (...)
{
$returnString .= '<div class="username">' . $data[i]["username"] . '</div>';
$returnString .= '<div class="content">' . $data[i]["content"] . '</div>';
}
return $returnString;
}
?>
And then in my javascript:
// get the information as raw json
var data = ajax_request(json = true);
var author = document.createElement('div');
author.className = "author";
author.innerHTML = data[i]["username"];
var content = document.createElement('div');
content.className = "content";
content.innerHTML = data[i]["content"];
body.appendChild(author);
body.appendChild(content);
// -- OR --
// get the information as pre-formated html
var data = ajax_request(json = false);
body.innerHTML += data;

As other users have stated, it depends greatly on who your intended audience is. If you are trying to keep startup costs low and are developing for users who generally have a cable / constant internet connection, then you can do whatever floats your boat.
However, if you are designing application and would like it to remain relatively maintainable, you should probably look into JSON. If you do go with JSON, I would also suggest your pick up a javascript library like jQuery so that you can safely and easily handle decoding of the JSON object.
In fact, anymore, even when I am returning HTML from the AJAX page, I still wrap it in a JSON object. It seems a bit more standardized that way and I can easily reuse my previous javascript code.
Here are some basic tradeoffs:
Sending HTML Straight from PHP
HTML code is visible in the code and may be easier to find validation issues.
May be easier to maintain. (Key word MAY.) If you are generating complex html, it might be easier to build in PHP.
Sending JSON to PHP and letting Javascript Convert to HTML
Less data sent to browser. This is a big plus for mobile users who are on limited connections and pay for their bandwidth usage.
Generally more maintainable.
Lets the clients computer do the processing rather than the server (reduces server load).
Appears to be a standard format for communication with a server these days. Even Google Maps API uses JSON to interact with developers. You might even consider JSON the new XML.
By the way JSON stands for Javascript Object Notation. It follows the standard syntax for objects in javascript:
For example: var blah = {'variable_name':'variable_value'};
So my answer to you would be to use JSON, no matter what, but who your viewer is should determine how much data you are sending.

For extremely simple sites/examples it doesn't matter... for larger projects I would go with always having a json response which is more portable.
Using json makes both the server call and js view logic reusable.

JSON would be my preference. It's much easier to work with HTML properly in JavaScript, and PHP's json_encode is ever so convenient. Plus, it gives a nice, clean MVC feel.

I like back end styling because then you dont have to worry about browser compatibility (ie interent explorer).

Related

is returning div from Ajax request secure?

this is whats i have been using but i noticed no one else is using it, which is return HTML from ajax request.
//prepared statement
while($stmt->fetch()){
#$row .= '<div class="holder">
<div class="head">'.htmlspecialchars($head).'</div>
<div class="title">'.htmlspecialchars($title).'</div>
<div class="body">'.htmlspecialchars($body).'</div>
</div>';
}
echo json_encode(array('sucLog' => #$row));
this is what most people i see is doing. then they use jquery or Javascript to format the html
$json = new stdClass();
$json->head = $head;
$json->title = $title;
$json->body = $body;
echo json_encode($json);
am just wondering if my method is wright or not
It's not really a security issue. Both methods are used, as you've seen, but really the second method is preferable because it ensures your back-end is decoupled from your front end.
If you follow the principle of SOLID code, the S means "singe responsibility". In your example, that means the PHP code should focus on reading and writing raw data, and leave it to the presentation layer to make that look however it needs to – HTML in this case.
If you decide in the future that you want to support Apple News format, Facebook Instant Articles, etc, etc, having your back-end return pure data is a smart thing, because you can create other renderers that work with the same basic data format.
So: I would suggest you return pure data from your PHP code, then have your front-end (jQuery, React, etc) convert that to HTML.

I want to send requests from a UE4 c++ game to my php script, so that it interacts with a mysql database

i'm searching the inet for around 3 days now and i'm stuck at this.
I got a MySQL Database and a php Script, as well as a Game made in UE4.
UE4 uses c++.
So now i want to send requests from the c++ game to the php script and that shall interact with the database.
For example create an account or login. I also want to pass the mysql query result of the php script to my c++ class.
I tried using HttpRequest, but i can't get data from php to c++ with that.
Maybe you can, but i don't understand it at all.
What i accomplished by now is that you can send a POST request from the game to the php script and pass variables so that the script uses them to perform the mysql query.
But how can i pass data from the php file to c++ now? The response i get is always the whole site (head and body) and i don't know where i could save the query result to pass it to the c++ code.
I'm a full beginner here, so go easy on me. I read so many different posts and blogs that my brain hurts like hell ): I hope someone can tell me how to do this easily or at least give me a hint on what i have to google and what i could use. I don't need a full tutorial, just a name of a library better than the Http.h (if simple HttpRequest cant manage this) would be enough. ): I'm really frustrated...
eXi
The PHP script should retun a HTTP response reduced to a bare minimum. It doesn't even need to be a HTML document:
<?php
// file: api.php
$param = $_POST['myparam'];
$foo = bar($param); // $foo contains e.g. "1,ab,C"
echo $foo; // if you opened http://myhost.com/api.php in a browser
// all you would see is "1,ab,C"
// (which is not a valid HTML document, but who cares)
?>
Then parse this HTTP response (a plain string, that is) from your game. You can use your own data format, or use a well-known format of your choice (XML or JSON are good candidates).
The json object in unreal is pretty good, so I would recommend outputting json from your php script. Json in php is a pretty natural workflow.
<?php
$obj['userid'] = 5476;
$obj['foo'] = 'bar';
echo json_encode($obj);
php?>
That will echo out
{"userid":5476,"foo":"bar"}
If that's all you output in your script then it's pretty straightforward to treat that as a string and populate an unreal json object with it.
FString TheStuffIGotFromTheServer;
TSharedPtr<FJsonObject> ParsedJson;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(TheStuffIGotFromTheServer);
if (FJsonSerializer::Deserialize(JsonReader, ParsedJson))
{
FString foo = ParsedJson.GetStringField("foo");
double UserId = ParsedJson.GetNumberField("userid");
}
Check out the unreal json docs to get a feel for what you can do with it.

call php from ajax javascript

I have a PHP-based template website that has been heavily modified.
I am in the process of adding some RSS feeds, most of which are easy to "interpret" and display satisfactorily but one is in caps with "pre" formatting as well.
I want to modify the content. I look at all the mods I make as education and invariably am able to google satisfactory solutions to the problems I come across but, despite an earlier extensive programming background, without a thorough grounding in Javascript, Ajax, PHP, CSS and HTML, there are sometimes things that just frustrate the hell out of me.
All I want to do is pass a block of text from javascript code to PHP code, massage it and get the result back.
I am at a point in a ajax/jscript function where...
items[i].content
...contains the block of text that I want massaged and I have a piece of code that I got from here, I think, that ostensibly calls the PHP code...
function compute() {
var params="session=123";
$.post('wxspellch.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
...and, unfortunately, it isn't documented so I don't have a clue what has to be customized. All I have done so far is enter the name of my PHP script.
The PHP script is written like this...
$pspell = pspell_new('en','american','','utf-8',PSPELL_FAST);
function spellCheckWord($word) {
global $pspell;
$autocorrect = TRUE;
// Take the string match from preg_replace_callback's array
$word = $word[0];
etc......
}
function spellCheck($string) {
return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}
echo spellCheck("...... the data .......")
The PHP tests out fine with hard-coded data.
I just need to know what further customizing I have to do to the javascript and php in order to facilitate the passing and recovery of the block of text.

Send Complex Object FROM Flex to PHP

I want to be able to send complex data from Flex to PHP and be able to parse that data via PHP script. I'm able to send a basic key value pair object but anything more complex than that doesn't translate accordingly.
This works...
ht.send({label:"FOO", label2:"FAA", label3:"FII", label4:"FEE"});
It translates as expected
This doesn't work...
ht.send({obj11:{label:"FOO", label2:"FAA"}, obj2:{label3:"FII", label4:"FEE"}});
It is posted as a string [object][object].
Is it possible to send complex data to PHP? I've tried JSON.encode(object). Do I need to send XML instead?
I believe Json didn't work because you didn't set it up correctly
var myComplexObject:Object ={obj11:{label:"FOO", label2:"FAA"}, obj2:{label3:"FII", label4:"FEE"}}
var dataToSend:Object = { data: JSON.encode(myComplexObject) }
ht.send(dataToSend);
// on the php side you will have something like so
$data = json_decode( $_POST['data'] );
echo '<pre>';
print_r( $data );
I would highly recommend using AMF instead of JSON, given it's native support in Flex.
If you are working with large datasets, I have found AMF more effective, but at the end of the day it boils down to what you're most comfortable with. AMF will be easier to work with in Flex, though.
Interesting reads:
http://web.archive.org/web/20090129160211/http://www.5etdemi.com/blog/archives/2006/12/clearing-the-fud-on-amfphps-speed-versus-json-and-xml/
http://web.archive.org/web/20090210160254/http://blogs.adobe.com/mikepotter/2006/07/php_and_flex_js.html

how to hide a json object from source code of a page?

iam using json object in my php file but i dont want my json object to be displayed in source code as it increases my page size a lot.
this is what im doing in php
$json = new Services_JSON();
$arr = array();
$qs=mysql_query("my own query");
while($obj = mysql_fetch_object($qs))
{
$arr[] = $obj;
}
$total=sizeof($arr);
$jsn_obj='{"abc":'.$json->encode($arr).',"totalrow":"'.$total.'"}';
and this is javascript
echo '<script language=\'javascript\'>
var dataref = new Object();
dataref = eval('.$jsn_obj.');
</script>';
but i want to hide this $jsn_obj objects value from my source,how can i do that??? plz help !!
I'm not sure there's a way around your problem, other than to change your mind about whether it's a problem at all (it's not, really).
You can't use the JSON object in your page if you don't output it. The only other way to get the object would be to make a separate AJAX request for it. If you did it that way, you're still transferring the exact same number of bytes that you would have originally, but now you've added the overhead of an extra HTTP request (which will be larger than it would have been originally, since there are now HTTP headers on the transfer). This way would also be slower on your page load, since you'd have to load the page, then send the AJAX request and run the result.
There's much better ways to manage the size of your pages. JSON is just text, so you should look into a server-side solution to zip your content, like mod_deflate. mod_deflate works beautifully on dynamic PHP output as well as static pages. If you don't have control over your web server, you could use PHP's built in zlib compression.
Instead of writing the JSON date directly to the document instead you can use an XMLHttpRequest in or use a library like JQuery to load the JSON data during script runtime.
It depends largely on your json data. If the data you're printing inline in the html is huge you might wanna consider using ajax to load the json data. That is assuming you wanted your page to be loaded faster, even without data.
If the data isn't that big, try to keep the data inline, without making extra http requests. To speed up your page, try using YSlow! to see what other areas you could optimize.

Categories