I have seen some answers to this question in previous posts, but no one has given a real working example, just psuedo code. Has anyone ever done this before?
Basically, what i have is a variable in javascript (jquery), and i want to use this variable to drive a query (for an overlay window) i am going to run in php.
From what i have read you can do this using an ajax call to the same page so it doesnt refresh itself, but i must be missing something because i can't get it working...
Any examples out there?
Thanks.
UPDATE 6/21/2010:
Ok, i tried to work through but still having some problems...here is what i have. The page I am working on in edit_1.php. Based on Firebug console, the page (edit_1.php) is receiving the correct 'editadid'.
When i try to echo it out though, i get an 'Undefined variable' error though...anything y'all can see i missed here?
Here is the javascript:
var jsVariable1 = $(this).parent().attr('id');
var dataString = 'editadid=' + jsVariable1;
$.ajax({
url: 'edit_1.php',
type: 'get',
data: dataString,
beforeSend: function() {
},
success: function (response) {
}
});
Here is my php:
if(isset($_GET['editadid']))
{
$editadid = (int)$_GET['editadid'];
}
echo $editadid;
It's hard to help without seeing the code you're currently using.
In jQuery:
var jsVariable1 = "Fish";
var jsVariable2 = "Boat";
jQuery.ajax({
url: '/yourFile.php',
type: 'get',
data: {
var1: jsVariable1,
var2: jsVariable2
},
success: function (response) {
$('#foo').html(response);
}
});
Then your PHP:
<?php
$jsVariable1 = $_GET['var1'];
$jsVariable2 = $_GET['var2'];
// do whatever you need to do;
?>
<h1><?php echo $jsVariable1; ?></h1>
<p><?php echo $jsVariable2; ?></p>
It's fairly generic... but it'll do stuff.
An important thing to note, and a very common mistake, is that any additions you make to the DOM as a result of an AJAX request (i.e in this example I've added a h1 and a p tag to the DOM), will not have any event handlers bound to them that you bound in your $(document).ready(...);, unless you use jQuery's live and delegate methods.
I would say instead of looking for an example you must understand how ajax works. How can you hit a URL via ajax and pass query parameters along with them (these can be the javascript variables you are looking for) How server side response is captured back in javascript and used into manipulate existing page dom. Or Much better you can post what you have tried and somebody can correct it for you.
Related
Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.
You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});
Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I have two dropdown list which is question and answer.
At first the answer dropdown list is empty, after the user choose a question, then it will pass the question_id to controller to run a function to get the answer. After the controller get the result, it will pass to the correspond view. Now how can I pass the result to the index view?
the index view:
$("#id_question").change(function() {
var data = $("#id_question").val();
var dataToSend = {question: data}
var href= '<?php echo $this->baseUrl('admin/comment/checkanswer'); ?>';
$.ajax({ type: "POST",
url: href,
data: dataToSend,
success: function(response){
//do what u wana do
}
});
});`
the controller:
public function checkanswerAction()
{
$this->_helper->layout->disableLayout();
$question_id = $this->getRequest()->getParam('question');
$answer_model = new Admin_Model_DbTable_Answer();
$answer = $answer_model->getAnswersByQuestionId($question_id);
$this->view->answer = $answer;
}
the checkanswer.phtml:
foreach ($this->answer as $key => $value)
{
echo '<option value="'.trim($value['id_answer']).'">'. trim($value['answer_text']) .'</option>';
}
The content that should be displayed in checkanswer.phtml will be affected to your javascript var response. So if you want to display this in your page, you have to make something like this :
success: function(response){
//do what u wana do
$('#yourSelectID').html(response);
}
There's a bug in your action: $this->getRequest()->getParam('question');. It gets a parameter passed using GET but you are passing using POST. So you should use $this->getRequest()->getPost('question');. If you add HTML like others suggested it should work. If it doesn't, use firebug or chrome developer tools to see what was returned by server and whether wrong output is returned by the server or there's a bug in parsing it with JS.
But this approach won't work out all the time (outputting formatted HTML) because it's simply inflexible. For instance, you want to use this ajax endpoint in other application (or different platform even, such as Android), or you want to modify the data in client side before printing, etc.
The solution here is to use context switching. Won't go into a lot of details now because I believe the link contains enough information, let me know if you have any questions.
with ajax you should always use these two things
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true); // this you have not used.
And in ajax resonse
success: function(response){
$('#id_answer').html(response);
}
i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.
i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.
I don't know how to ask this question that's why I'm going to simulate what I need, some developers make what I need by rendering javascript with php. A simple sample file would look like:
my_javascript_file.php
<?php include "my_class.php"; ?>
$(document).ready(function(){
$.ajax({
url: "<?php $my_obj->post_url(); ?>",
success: function(){
alert("Post successful")
}
});
};
which outputs following:
$(document).ready(function(){
$.ajax({
url: "/post_handler.php",
success: function(){
alert("Post successful")
}
});
};
my question comes there, is there any way to achieve that with pure js techniques?
Thanks,
Sinan.
P.S. This is just a simple example of course I can hardcode post url here, or get url by location object etc with javascript I hope you get what I mean...
EDIT: Sorry for confusions by the terms I used, it is just getting some information from my application and writing to my javascript dynamically. I don't mean comet or data encode etc.
What I want to know is how to use server-side data on javascript files(if there is any way). Like what php method does on my example, it simply echoes a string which comes from my application. Is there a way to do that by a javascript library or a framework, like a template engine you assign vars and use it in that template system. Hope it's more clear now.
Yes there is a way, but its odd. You can use the jaxer server. It lets you run javascript on the server.
EDIT:
As I said in my comment I don't think you want to be downloading extra js to the client in order to implement a templating engine. Its probably a separation or decoupling that you're talking about. In which case you could have the following in a separate js file:
var myObject = {
var1 : '',
var2 : 0,
init : function(options) {
var1 = options.var1;
var2 = options.var2;
$('#someElem').click(function() {
// do stuff
return false;
};
}
};
and then call it like this from your html page
<head>
<script type="text/javascript">
var options = {
var1 : <?php echo "hello" ?>,
var2 : <?php echo 1 ?>
}
myObject.init(options);
...
i am not sure i know what you mean by "push" ... if it is a real server push, you should look at comet servers ...
also, to me it's unclear what "pure js techniques" are ... you can do this without jQuery of course ... but pure JS, as the languages primarily designed to manipulate the DOM will not suffice of course ... you need AJAX-like approaches ... however there was a proposal for push in HTML5, but yeah, this is gonna take some time ...
so i hope this helps ... but maybe you should clarify your question a little, i am sure you will get better answers ... :)
greetz
back2dos
You could ask the server for the URL using .get or .ajax (assuming your urls.php will handle this properly and return a proper string - or JSON, in which case you might as well use .getJSON - with the URL in it). For example (untested of course):
$.get("urls.php", { operation: "post_handler" },
function(data){
$.ajax({
url: data,
data: eventData,
success: function(){
alert("Post successful");
}
});
});
================= Edit: New Potential Answer =====================
Say you manage to retrieve JavaScript Data Objects from the server, do you wish to inject the JavaScript data you obtained in your HTML markup, client-side?
If that's the case you might look at IBDOM: http://ibdom.sf.net/
I wrote it, we've had it in production on a number of a sites for a couple of years.
================= Old Answer Below ====================
So you want "eventData" to be "something" which can be consumed by JavaScript.
I'd recommend first taking a look at JSON in PHP:
[REMOVED link to JSON in PHP, not needed]
Then your PHP Code might resemble this:
<?php include "my_class.php"; ?>
$(document).ready(function(){
$.ajax({
url: "<?php $my_obj->post_url(); ?>",
data: <?php json_encode ($my_obj->getData()); ?>,
success: function(){
alert("Post successful")
}
});
};
So the idea here, is that the value of your "data:" field would become a JSON Object graph generated by PHP on the server.