I have been playing with jQuery .load function to grab a particular div from a page.
$('#result').load('ajax/test.html #variable123');
This works like it should, however it is taking forever because the Response still contains the complete document even though all that is returned in #result is the div that I defined.. in this example #variable123
Is there another way I could accomplish this but only have the response contain that actual div? What would be the fastest way to return this result?
To further clarify, the id that I am searching for is generated from a foreach loop on each page.
<img name="<?php echo $_product->getId() ?>"
and then an onclick event for them to make the ajax request for that related div id.
$('img').click(function () {
$('#result').load('ajax/test.html .' + $(this).attr("name"));
});
The page test.html also has a foreach loop that generates div blocks with the same id as was passed in the name. David and Juan both suggested sever side solutions. Can someone please explain this a bit more to me?
Since you can't fetch arbitrary parts of a file:
$('#result').load('ajax/test_with_only_variable123_in_it.html');
You can, of course, use a server side program instead of generating a bundle of static files.
As others suggested, you need to implement the functionality server side, not client side. It is not possible to use javascript to load part of a html file, so you'll either need to have an individual html file for every result you'll require (as David suggested), or create a server side script to manage this for you. For example:
Your html/js file would look like this:
$('img').click(function () {
$('#result').load('ajax/test.php?id=' + $(this).attr('name'));
});
I would probably use .get() or .ajax() over .load() to pass the data, but for this example, .load() should work as above.
In your test.php file, get the ID, and load the required content (something like this):
<?php
// load class/model/whatever you need to do
$id = $_GET['id'];
$product = $productmodel->get($id); // or however you load a single product from your class/model
// echo data from $product
?>
If the second part doesn't make sense, please let us know how your products are stored ( whether you're using a simple OO approach, or using a php framework such as codeigniter) and we'll try to give a more detailed example of the server side code.
you could try to call to a function like this:
$('#target').load("functions.php",{action:"that_div"});
if($_POST){
$action = $_POST['action'];
if($action == "that_div"){
exit( "<div>Your div</div>" );
}
if($action == "another_div"){
exit("<div>Your another div</div>");
}
}
as David sugested
Related
I need to redirect users to a unique url when they visit a specific link which corresponds to a certain/row/column in the mysql database.
Here is what I mean:
The mysql database has a table table123 with a row id 123 and inside a column name "column123".
This row and column correspond to the webpage1.html
Normal javascript redirection is like this:
<script>location.replace('http://website.com/webpage2.html');</script>
What I need to do is extract the value from column123 of the webpage1.html and add it to the redirection url, so it would redirect specifically with that value.
For example:
<script>location.replace('http://website.com/webpage2.html/go/dbtable123row123column123value');</script>
This redirection script will be placed on top of the php page that will call the other php pages, so it has to be dynamic every time, thus the redirection script has to use dynamic placeholder, not static value, except the domain name.
Thanks
If the table really is mysql table and the javascript has no way to access that information, follow other suggestions and deal with it on the server-side. If somehow, the table data are printed on the html document where you want the redirect to take place then you can consider the following. (Though, it would really make more sense to manage this server-side).
Assuming you have given unique id to your column and assuming that the table is on the web page that you have your location.replace call on.
location.replace("http://website.com/webpage2.html/go/" + $('#column123').text())
Without jQuery, you could use
document.getElementById('#column123').innerHTML (or text?)
If it is not practical to assign an id to the column, you can possibly use some jQuery selector magic with :eq
location.replace("http://website.com/webpage2.html/go/" + $('#dbtable123 > tr:eq(1) > td:eq(3)').text())
(none tested)
Assuming you can't redirect in PHP for whatever reason, here's what I'd do. Grab the proper web page from your database using AJAX. I'd suggest using a library such as jQuery to help you do that. If you use jQuery it'll look something like this:
$(function() {
$.get(
'/script/that/queries/db.php',
'your=query_string&goes=here',
function(data) {
if(data.url.length > 0) {
location.href = data.url;
}
},
'json'
);
});
You didn't specify when you want this redirect to fire, so I just put it in the standard body onload. Anyway, after you write that $.get() function call, then in your /script/that/queries/db.php, you'll want to perform your database query based on the get variable(s), and print a JSON encoded array with the valid page you want to redirect to:
$json = array('url' => '/webpage2.html');
print json_encode($json);
Of course I've just written some pseudo code, but hopefully it'll help get the idea across. You'll want to make sure you validate/sanitize all info being querying the database, etc.
Do it simply.Make dynamic url with php script.
header('Location: http://website.com/'.$table123row123column123);
I'm writing a PHP application which uses AJAX to submit forms via POST when required. When javascript is not able to be used, I submit the form via HTML/PHP as per normal.
What I really want to do is return JSON or XML to the AJAX call and I don't want to write all of the form processing logic twice or repeat myself at all really.
I'm trying to determine the best way to write the form processing logic as a single interface which can then be used by both an AJAX call and the PHP script.
I have come up with two options, which both seem like hacks. Hoping I can be given some cleaner/better/more correct solutions or have my two solutions evaluated to determine which one is preferred.
Form: form.php
Processor: process.php
AJAX: JS intercepts submit click in form.php, POSTs to process.php which returns JSON result back to JS. JS updates HTML accordingly using JSON result.
PHP:
Option 1
form.php posts to process.php which outputs HTML if a certain variable is passed with the POST data. e.g.
if ($_POST['output'] == 'html') {
//output as html
} else {
//output JSON
}
Option 2
form.php posts to intermediate.php which will then include('process.php'), catch the JSON output and use the JSON output to display the HTML as required. e.g.
ob_start();
include('process.php');
$json = json_decode(ob_get_contents());
ob_end_clean();
//use json to create HTML to display to waiting user here
Both of these options seem a little hacky. The second seems cleaner (although I never feel like I'm doing something cleanly when I use ob_start) because it doesn't require me to write process.php any differently - which emulates an external web service better - although this is not a concern since process.php is fully under my control.
Thoughts?
Thanks as always,
Aaron
I would choose option 1. Just like in popular frameworks like Yii. The typical workflow is like this one:
if (isAjaxRequest()) {
// Ouput JSON and finish script
die(json_encode($output));
}
else {
// This is not AJAX request, proceed
}
And isAjaxRequest is:
// Taken from Yii framework method
function isAjaxRequest() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}
You don't need to set certain variable to indicate that the request is via AJAX because browser sends HTTP_X_REQUESTED_WITH header and you just need to check if it's been set.
Maybe something along the lines of option 1?
Just before the ajax script fires, use javascript to change the form variable from HTML to JSON and then the PHP script can capture it right?
If the ajax script fails, it will never change the variable.
You could even use javascript to change the form action to JSON_process.php or something like that
I'd recommend using an MVC framework. In the controller, set all the data you'll need. Then, set up two view templates, one for JSON (which could just do a simple json_encode of the data), and one for HTML. You can then just set the view based on an output parameter as in your Option 1.
Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a page where I want to display some points on map. I have small templates (like Smarty, but lighter) and there in template I have variable $points, that consists of coordinates of points I need. I need to pass them to javascript (because only javascript can render that map with points).
I have 3 variants of doing it. Can you tell, what is best?
1th way: (Template inserting javascript-tags with global variable)
tpl.php file:
<script>
MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
.js file
function renderMap(){
var points = MAP_POINTS; // using global. Is it really bad? or who cares? =))
}
2nd way: (Passing variable through the HTML element)
tpl.php.file
<input type="hidden"
value="<?php echo json_encode($this->points); ?>"
id="map_points_container">
.js file
function renderMap(){
// without globals, but needed to be parsed on local side
var points = $.parseJSON ( $( "#map_points_container" ).val() );
}
3rd way: (AJAX-way)
I don't pass $this->points from template file at all. I have another .php file that handles all my AJAX requests:
Ajaxing.php
function get_map_points($params){
// some operations
return json_encode ($map_points);
}
And than on local side I'll have something like this:
.js file
$.post ( 'ajaxing.php', params,
function(points){
renderMap(points);
}, 'json');
The third way is usual, but if I already pass some values from template to local page, then I can pass and map points too. In fact, I don't need to make another request for only this map points (that's why I don't like third way)
But may be you can advise me another way? a better way?
The way I choosed:
1th way with little remarks. All my 'map-rendering' code is in another file and it's like:
$(function(){
MAP_APP = {};
MAP_APP.some_prop = null; // some properties
MAP_APP.some_method = function(){}; // some methods
});
So in template file I only have to extend my MAP_APP object:
<script>
MAP_APP.points = <?php echo json_encode($this->points); ?>;
</script>
Yes, global variable. But it's like namespace of whole application.
Thanks to everybody.
The first way is definitely the least complicated and fastest.
The second one adds an additional processing step (the parseJSON()) that isn't necessary.
The third way is good if you're dealing with lots of data that is optional (i.e. is needed only if the user requests it, and it isn't 100% sure whether that will happen) or dynamic. It creates a new request though, and is not going to be immediately available.
If you don't want to use globals, you could e.g. wrap your JavaScript functions into an object, and populate an object property from PHP:
<script>
MyObject.MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
There is another funky way of passing variables in a js external file :)
Your PHP file:
<script type='text/javascript' src='script.js?id=0&some=<?php echo $whatever?>'></script>
and inside your script.js you can retrieve those values:
var scripts = document.getElementsByTagName('scripts');
// get your current script;
for (var i=0,l=scripts.length;i<l;i++){
if(scripts[i].src.indexOf('script.js') !== -1) { // or your script name
var query = scripts[i].src.substr(scripts[i].src.indexOf('?')+1);
// now you can split the query and access the values you want
....
}
}
The first one is most efficient and fastest. The second one is funky. The third one is also fine.
The first because it does not require any other requests. The second one is a bit odd, I would not use that kind of constructs, but that does not mean you can't. The third one is also fine, but you should think about if AJAX is the way to go. If you application requires multiple requests for points for different locations, then it might be the most efficient way to go.
I would go with your second method since you don't want to use AJAX for it (and it seems odd to use AJAX for something you already have in the current page). You want to limit the number of global variables in your JavaScript because everything in your JavaScript will create an instance of each global variable and thus decrease your performance.
I forgot the name of the person, but the man who was heading on optimization at Yahoo! and then went to work for Google gave a lecture about JavaScript optimization, and this was one of his points.
EDIT: Found the link: http://sites.google.com/site/io/even-faster-web-sites
Speed wise 1st way is the best way.
But the best way is to create an XML output from PHP and loading that xml into Javascript via Ajax. The best example of this is article given on google maps documentation - http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
Another way:
In script_that_defines_renderMap.js:
function renderMap(points) {
// take "points" as an argument
}
And then:
<script src="script_that_defines_renderMap.js"/>
<script>
var mapPoints = <?php echo json_encode($this->points); ?>;
renderMap(mapPoints);
</script>
No global variable, no problem.
I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.