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.
Related
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.
I have a function that creates an array that contains the return value from the HTML DOM method : window.document.getElementById()
function makearray1(){
var array1=[1,window.document.getElementById('divID'),['a','b'],[1,2]];
}
then I pass the array into another function
use(array1)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
and 'a' is written in the appropriate div
later I decided to put the array in a form and post it to a txt file on the server using php and:
JSON.stringify(array)
So now I use AJAX to call the data from the txt file after the rest of the page has loaded etc... and the original function used to make the array is not included at all.
so my php is basically this:
$a1='use(';
$data1 =file_get_contents("text_file.txt") ;
$a2=')';
echo $a1.$data1.$a2;
and the response text:
var n= XMLHttpRequestObject.responseText;
eval(n);
which pretty much means this:
use(text_file)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
the problem is that the array in the text file looks like this:
[1,null,['a','b'],[1,2]]
instead of:
[1,window.document.getElementById('divID'),['a','b'],[1,2]]
My question: Is there any way that I can do the equivalent of what I'm trying to do here, which is immediately replicate the return value of the HTML/DOM method in an array using AJAX/php?
To clarify: this is a simple example. I actually have a huge, multidimensional array that already has established pointers, or prefetched DOM nodes in it. Now I'm trying to replicate the array when a text version is loaded using ajax. I'm looking for a recursive approach to changing all of the null assignments with something that will immediately fetch the appropriate DOM node. Most likely I will need to do it with the response text, but was hoping I could do it with the php portion.
You're trying to stringify a reference to a javascript object in the memory of whatever computer is evaluating getElementById first, and that has no chance to represent something on the end client's computer.
Send the id instead:
function makearray1(){
array1=[1,'divID',['a','b'],[1,2]];
}
then, in the client:
function use(xxx){
window.document.getElementById(xxx[1]).innerHTML=xxx[2][0];
}
If you really want to eval it at the end, you can use this, I guess
function makearray1(){
array1=[1,"window.document.getElementById(\"divID\")",['a','b'],[1,2]];
}
I've no idea why you would want to do that though
Assuming the dom element exists in the second page, it should look something like this.
JS:
function packDomData(){
return {
"MySpecificYetBriefProperty0":1,
"DomID":"divID",
"MySpecificYetBriefProperty1":['a','b'],
"MySpecificYetBriefProperty2":[1,2]
};
}
function useDomData(domData){
document.getElementByID(domData.DomID).innerHTML=domData.MySpecificYetBriefProperty1[0];
}
PHP:
//Make sure the contents of this file is the json from packDomData. use json_encode in php or JSON.stringify in js
echo file_get_contents("text_file.txt");
var myData = JSON.parse(XMLHttpRequestObject.responseText);
useDomData(myData);
I used to code like you. Here are some tips that have helped turn my coding horror into a fun job:
Use objects with descriptive properties instead of arrays whenever you aren't actually looping through the array - I promise it will save you and others headache! "DomID" is much more flexible than 1, and if you change the order in the array, javascript gods help you that array is everywhere - including however many random text files on your server!
Also use descriptive names for functions
Always return a value from a function instead of using globals whenever possible, even where the result is then used as a nasty global. Trust me.
Never put javascript function names in an ajax call. Use JSON instead and keep the functions and other script in the javascript file where it belongs.
Mysql will save your life!!
Disclaimer - I didn't run this code but it should basically work when you get everything hooked up right.
I am extremely new to PHP and, although I am quite familiar to javascript, I am learning how to use the massive jqGrid plugin right now. I am trying to understand how jqGrid serializes the grid data and how PHP parses this data. Currently, I am not even connecting to MySQL, but I am simply trying to echo the serialized jqGrid data as "fake" results. I have the following code for js in the head of my PHP file:
<script type='text/javascript'>
$(function(){
$('#list').jgGrid({
url:'grid.php',
mtype:'POST',
colNames:['json'],
colModel:[{name:'j',index:'j',searchoptions:{sopt:['eq']},search:true}],
pager:'#pager',
rowNum:10,
viewrecords:true,
gridview:true,
serializeGridData:function(postData){
return postData;
}
})
});
</script>
I then send this information to my 'grid.php' file, which has the following code:
<?php
$jason = $_POST['postData'];
$page = $jason->{'page'};
echo '<rows>';
echo '<page>1</page>';
echo '<total>1</total>';
echo '<records>1</records';
echo '<row id="1">';
echo '<cell>'.$page.'</cell>';
echo '</row>';
echo '</rows>';
?>
When I remove the serializegriddata option from the JS, everything works fine (I also add in the default $_POST['page'], $_POST['rows'], $_POST['sidx'], $_POST['sord'] back into the PHP). The problem comes in when I add the serializegriddata.
I am looking for any examples of how to use the postData on the client side (are the any other functions I need to add to the serializegriddata or can I just return the postData) and how to properly parse this in PHP (how to $_POST the data and then how to parse and use this data). I know this is probably an extremely simple solution, but everything I find just talks about the client and says nothing about the server side. Thanks in advance.
Okay, I am a little slow, but I partially answered my own question. All of the jqGrid documentation read as if your entire postData was parsed as a JSON string if you set multipleSearch:true. I thought that I had to parse every variable into a postData JSON variable, then pass this to PHP. Although the solution took a little work to properly implement, the thing that I was missing was the fact that with multipleSearch:true, this adds just a 'filter' variable to the AJAX call. This filter variable is parsed as follows:
$filters = $_POST['filters'];
$json = json_decode($filters,true);
and the result of $filters is:
{"groupOp":"AND","rules":[{"field":"Customer","op":"eq","data":"eosp"}]}
This is as opposed to the multipleSearch:false option of:
$sField = $_POST['sField'];
$sValue = $_POST['sValue'];
$sOper = $_Post['sOper'];
Once I got this, I was able to loop through all instances of my search parameters and create my $where variable. One thing that almost became a big problem for me was the old example I was able to find about properly constructing a (link below) is that you can only have WHERE is a mysql_query only 1 time.
http://blog.brzezinka.eu/webmaster-tips/jquery/how-to-enable-the-search-functionality-in-jqgrid
I hope this might help someone in the future (it drove me crazy for almost 2 days straight).
I'm pretty new to HTML and javascript. I know this code already exist on internet but I can't have it working for me. I'm stuck on this issue for 2-3 days. I would be really glad if you could help me out.
Here is my problem
I want to populate the optCategory select list based on the selected entry of optPostAppliedFor. For that I called a function change_categoriees(key) when I click the optPostAppliedFor list. The code is here as follows
<tr>
<td width="40%" align="right" nowrap>
<strong>
Post Applied for<span class="text11red">*</span> :
</strong>
</td>
<td width="60%">
<select name="optPostAppliedFor" class="flat" onclick="change_categories(0);" />
<option value="">--Select--</option>
<?php
foreach($App['post_applied_for'] as $key => $val){
echo '<option value="'.($key).'">'.$val.'</option>';
}
?>
</select>
</td>
</tr>
Here is php code for default enteries of optPostAppliedFor and optCategory
$App['post_applied_for'] = array(
'Lecturer' => 'Lecturer',
'Business Analyst' => 'Business Analyst',
'Deepender good' => 'Deepender good'
);
$App['category'] = array(
'Category1' => 'Category1',
'Category2' => 'Category2',
'Category3' => 'Category3'
);
Please tell me how can I make this function, so that my purpose is achieved. I tried this but all in vain.
function change_categoriees(key) {
alert('asdasd');
var z = document.getElementById('optCategory');
var x = document.getElementById('optPostAppliedFor');
var y = document.createElement('option');
var display = x.options[x.selectedIndex].text;
var option = x.options[x.selectedIndex].value;
y.text = display;
y.value = option;
try {
z.add(y,null);
} catch(ex) {
z.add(y);
}
z.options[0].text = '* '+(z.length-1)+' selected *';
}
I'm not really sure, but...
These two lines in your change_categoriees method look problematic:
var z = document.getElementById('optCategory');
var x = document.getElementById('optPostAppliedFor');
For these statements to return some value, your HTML needs to have id attributes with the names optCategory and optPostAppliedFor:
<select id="optPostAppliedFor">
Also note that the PHP code runs on the back end, in the server. There's no way that the javascript running in the browser can call PHP directly.
If I interpret your code correctly, you do have a slight problem : you're putting variable in the PHP code, that you'd like the client (the browser) to use. It's not the way it works. Variable in PHP are only stored on the server-side. So the Javascript (which is on the browser side) cannot use it in any way, if you only store them as variables : they'll be on the server memory, not on the client's. There are two solutions here :
1°) You put the variable you're going to use in the web page that PHP generates. You could go with hidden fields, for instance, and then "unhide" the relevant fields. But if you got a lot of variables, it's not very practical.
2°) You could go with an AJAX solution : basically, the idea is that through Javascript, you call a PHP script that is going to send back information (formatted as pure text, XML or JSON). Here, when the user clicks on the first list, you send a request (POST or GET) where you'll inform the server about the choice of the user. For instance, you'll ask for the categories connected to the "Business Analyst" choice. The PHP script we'll analyse the "post applied for" and send the content of the category list accordingly. Since everything is done through Javascript & PHP, the page will not be reloaded during this time, so it's relatively fluid.
I would recommend the use of a Javascript library to make things a bit easier. JQuery being one of the most popular choice, you will find a lot of help and example on the web.
May be you are searching for AJAX methods? E.g. you send request to some of your PHP files with GET or POST variable for your key (which user selects in optPostAppliedFor) and that PHP script echo'es the needed result, so JS could use it.
For example, with jQuery this would look like this:
$("select[name=optCategory]").load("myUberScript.php", { key: $("select[name=optPostAppliedFor]").attr("selected") });
myUberScript.php:
<?php
$key = $_POST['key'];
if (isset($key))
{
if ($key == 'moo')
echo "<option>moo</option>"; else
if ($key == 'foo')
echo "<option>foo</option>";
}
?>
I think this would be the best way, but i'm really not sure with my .attr("selected") selector. And i recommend you to read something 'bout AJAX and jQuery - these are very useful when web-developing =)
So, what does this JS do? It finds your select tag with name optPostAppliedFor, gets all its 'selected' items (be sure to verify that code - i am not sure about it), sends POST request to myUberScript.php passing that values as $_POST['key'] argument, gets response, finds div named optCategory and sets its inner HTML code to PHP's response. Pretty nice, huh? =)
I recommend this way beacause it is not always good for user to get all the internal data within javascript - user could see that data and if there is a lot of data, the page would load slooowly. Second: you can manage/edit/update/modify (choose the right one) your PHP code whenever you want. Third: PHP code has more features for secure verifying user' data and lots more. But there is one great disadvantage: if user disables JS support in his browser, you would not be able to do this sort of trick. Notice: this is a very rare case when user disables JS =)
As a first problem, in your PHP code, you improperly close the select tag, like this,
<select ... />
...
</select>
That will probably cause some errors. It should be like this, without the extra /,
<select ... >
...
</select>
As another problem, you spell your function call like this,
onclick="change_categories(0);"
but you misspell your function name like this,
function change_categoriees(key) {...}
Notice the extra "e" in "categoriees". So you're not actually calling the function properly.
It looks like other people have some answers too, so I'll just finish by offering some suggestions for dev tools and documentation. For development tools, Firefox Firebug is excellent, it will let you debug css, html, and javascript. I've also heard good things about the development tools in Chrome. In fact, all the newest browser versions have development tools of some sort, and they're all pretty good.
Next, the Mozilla docs are a good resource for web-development. You might also be interested in checking out the resources mentioned at w3fools.com.
Also, in the future, when sharing code on Stack Overflow, you should consider sharing a live example with jsFiddle.
Oh wait, before I forget, you should also use a text editor or an IDE that does syntax highlighting, and maybe even syntax correction, for you. I use a simple text-editor called Notepad++ for Windows, though there are many others.
Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug