Why I can't write Javascript code inside Ajax reponse text? - php

the reponseText should be like this on PHP
echo "<script>alert('test')</script>";
But nothing happen. How do I return Javascript code?

An ajax call is up to the caller to decide what to do with it (depending upon what type of data is returned). In this case, if your caller isn't prepared to execute this, then nothing will happen with it. Depending upon what the real code wants to do here, there are a number of different possibilities for handling the returned result from the ajax call.It could be formatted as JSONP so it calls a function in your main page code to process the returned data. You could return full JS (without the tags) and do an eval() on it after the host page (generally not considered a wise idea due to some security risks) or it could be just added to the current page and let the browser just parse whatever you put in there.Usually, an Ajax call returns pure data and your host page code processes that data and holds the code for deciding what to do with it. This is the safest mechanism because there's no way for anything that hijaacked a connection to inject code into your page (all it can do is change the data).

You've returned it as text. Now all you need to do is insert that text onto the page somehow:
document.body.innerHTML += response;
There's a lot going on, and a lot of assumptions made, but that's the simplest way to do it.
(Well, that's not entirely true. The easiest way to do it would be to just return the JavaScript, and then eval it.)

here's a simple example. But don't include the <script> tags for this tough
$.ajax({
type: "GET",
dataType: "text",
url: "jsLoader.php",
success: function(data){
eval(data);
}
});

Related

Is it possible to 'echo' a sequence of responses from an ajax call

I'm learning and experimenting with jquery/ajax as I develop a website. I have a page that updates a database. I would like a 'sequence' of responses to display on the screen when the user submits their data (I've seen this done on many other sites).
For instance... user submits form and the page displays:
Received Input
Checking Database - recond number xy
Updating Database
Retrieving Information
etc etc
This is just an example but you get the idea.
I have an ajax call that is initiated on 'click' of the submit button (getFormData just serialises all the form data for me and works fine):
var toSend = getFormData($upgrade_db_form);
var formMessageBox = $("#displayResults");
$.ajax({
url: ajaxurl,
data: {
action: "database_action",
formData : toSend
},
type: 'POST',
dataType: 'TEXT',
beforeSend: function() {
//$form.fadeOut('slow');
formMessageBox.html("starting it up");
},
success: function (data) {
formMessageBox.empty();
formMessageBox.html(data);
error: function (xhr) {
// formMessageBox.html("Oops error!");
}
});
I have a function which gets called by ajax:
function upgrade_database_function() {
echo "testing ";
for($i = 0; $i < 99; $i++) {
echo "percent complete ".$i."%";
}
echo "done ";
die(); // this is required to return a proper result
}
I'm using Wordpress and all the ajax side of things works fine, it passes the form data correctly etc, it's just that I get one long output as though it's cache'ing all the echo's up instead of outputting them in sequence.
I've gone through the jquery ajax documentation and couldn't find how to make it behave the way I want it to. I can live with it the way it is but I think it would look a lot better if I could get it working the way I would like.
Can this be done this way or do I need lots of sequential ajax calls to make it work?
I don't know PHP, but i'm guessing that the echo is just writing to the response buffer... so when all the echos are done the whole response will be returned and you would get the effect that you are seeing... You would need to go with a polling system or something along those lines to get the latest status' from the server and display them I would think... Maybe there is some system in PHP that allows this, but as I said, I don't know PHP.
An Example of Long Polling can be found in this article.
http://www.abrandao.com/2013/05/11/php-http-long-poll-server-push/
WARNING: You may have to do some manual managing of locking of the session in PHP so that your long running call doesn't lock your polling ajax calls: See here:
http://konrness.com/php5/how-to-prevent-blocking-php-requests/
Note that you would likely be wanting to:
create one ajax call that starts the execution of some coded that will take a while... you could put messages that have been generated into a session variable for example in a list of some sort. You would need to lock/unlock the session as mentioned to prevent suspension of AJAX polling calls.
you would create a polling method like in the article that might check the session every 500ms or something to see whether there are any more messages, lock the session, remove those messages and return those messages to the client side and display them.
WARNING: Again, I'm not a PHP person, I may have done this once in my life in PHP (can't remember exactly) but I may be wrong and this may not work, from what I've seen though it looks like it is achievable. Hope this gets you on your way!

Sending php variables to Javascript variables

Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

Help with Ajax .... need some clarification

Can any one please explain this:
var js_var = 'hello';
$.ajax({
type: "POST",
url: "some.php",
data: "js_var="+js_var,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
I need to know what is returned by the PHP file in this case... The PHP file can be assumed to return whether jsvar exists in the db or not...
The PHP file will return whatever the result of processing the data params (js_var=hello) is. The output will be received by the client as a string (msg).
Your output from PHP script either with echo/print or even HTML is returned in the msg argument of success callback function.
For example, if you do this from PHP script:
echo 'hello world';
The msg will be equal to hello world
Assuming that this is in reference to PHP Javascript variable help then some.php can do whatever you need to do. The actual some.php was just a place holder for whatever script you needed run was named.
Instead of the output of that PHP file being sent and rendered in browser, it is sent and put into the msg variable. What you send back could be a block of HTML to be shoved into a div for rendering, a simple OK, or a JSON object, or XML. As you are writing the code on both ends of the communication, you can do whatever you want.
For example, if you were creating a user creation form, you could have a script, that after the user name box loses focus, goes and makes an AJAX call, then returns either OK or an error message, then you could display that next to the user name box.
EDIT:
As other people have mentioned, it would be best going through a few tutorials about jQuery and AJAX in general. A quick google turns up a few decent ones:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
http://www.ibm.com/developerworks/library/x-ajaxjquery.html
http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html
I've found that the IBM developerworks articles to be rather clear and concise time and again.
use firefox , firbug or ie fiddle to the see the output.
Firebug is really nice , there is a panel called net , open that and you can see the result from php.

JSON response is null, but the URL is echoing correctly

I have a form being AJAX'd in by jQuery on a page with multiple forms. I'm performing the following function, which is a wrapper for the $.ajax function:
function do_json_get(uri){
var ret = '';
var url = AJAX_URL + uri;
$.ajax({
type: 'GET',
url: url,
async: false,
success: function(data) {
ret = data.html;
},
dataType: 'json'
});
return ret;
}
When I go to the AJAX server directly (which is rendering the form in PHP), I get the raw JSON response - so I know the server is outputting to the browser, and the AJAX server is doing other things like setting the proper cookies, so I know that the connection is good (I get a 200 response code). Yet the data object is coming back null.
Here's a guess. If you're serving the page from the file system, Firefox (and I think Chrome) will see it as originating from a different domain. You'll get the 200 response, but no data.
Try Safari, or maybe give jsonp a shot in place of json.
EDIT:
Since you're getting the data from a different domain, it won't work. I think it is not allowed by the XMLHTTPRequest.
Oh boy. This question again.
AJAX: Asynchronous JavaScript And XML*. Asynchronous. Asynchronous. Asynchronous.
Your function, do_json_get() returns ret before the success handler function in the AJAX call executes. The order of operation is not proceeding, here, from top to bottom. In other words, you just can't do it that way.
Because of its asynchronous nature, AJAX operates on callbacks, not return values. You need to change your paradigm. The success handler function needs to do whatever is required with data.html itself, or pass it off to another function.
* Yes, I know the XML part of the original acronym is largely vestigial these days

Categories