jQuery ajax php function - javascript

I have never been in contact with ajax. Can I get some help?
I know how to call a php script.
Example:
<script>
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#mybox").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
How can I get a response from function? If my ajax.php has function
<?php
function example(){
return "blablalba.....";
}
?>
How should my script looks like?

How can i get a response from function?
The same way you get a response from any other PHP script. The Ajax is irrelevant.
header("Content-Type: text/plain"); // or whatever
print example();

The PHP script just needs to display content as it would if you loaded it directly in the browser, using echo or simply closing your PHP tag ?> and outputting HTML or similar.

You should not return, you should send actual output. For example: a JSON encoded string or array, with the correct content type. The result will populate to the variable mentioned in request.done, i.e. msg.

You will need to use echo rather than return.
ajax.php
<?php
function example(){
echo "blablalba.....";
}
?>

It depends on the content of which you are using.
Since you specified content is HTML, your response will be a string with HTML code (as if you wrote it in notepad).
But AJAX as far as I know wont get response unless "echo 'html code'" is used in php.
<?php
echo '<body><div>Response from php script</div></body>';
?>
So fix your php code first. Then in AJAX set "data" as function argument and use it inside function. Data will be your response from php.
.done(function(data){
var smth = data;
});

Related

Using ajax to call php

I'm trying to call a php function to do some SQL stuff.
I've read on stack that it's possible, but only if I use ajax. So I've tried.
Here is the ajax :
$.ajax({ url: './put_in_table.php',
type: 'get',
success: function(output) {
console.log(output);
}
});
Unfortunately, It does nothing, and the output returned by the request is containing the PHP source code.
Php code is just a very simple test :
<?php
echo "lol";
?>
Does anybody have an idea why the php is not executed? (It only contains an echo). Thanks in advance.
If your php code is not parsed but returned, install php on your server

Executing a PHP file using Ajax request

Still grasping Ajax, so I beg your patience. I am trying to run a php file from within javascript using an ajax call with the help of jQuery. I do not need to GET / POST any data, I just intent the PHP code to be executed and the message 'hello world' logged to the console (I intend to use this in a button with an onclick() function). The only thing that gets logged is the "success" message. I want the PHP code to execute without leaving the current page, but I think I may be missing how AJAX works. Or perhaps there is a better way to accomplish this. Thanks for helping out.
PS: I can see the resource "ajax.php" is being loaded as a XHR, by using Safari's web developer tools.
Content of the index file that calls ajax.php is:
<script>
$.ajax({
url : 'action/ajax.php',
type : 'POST',
success : function (result) {
console.log ('success');
},
error : function () {
console.log ('error');
}
});
</script>
Content of ajax.php is:
<?php
echo '<script>console.log("hello world");</script>';
?>
Appreciate that you are taking initiative to learn PHP, jQuery and AJAX.
Just some modifications and you are on track:
Javascript (jQuery):
<script>
$.ajax({
url : 'action/ajax.php',
type : 'POST',
success : function (result) {
console.log (result); // Here, you need to use response by PHP file.
},
error : function () {
console.log ('error');
}
});
</script>
Content of ajax.php is:
<?php
//echo '<script>console.log("hello world");</script>';
// Change above line to:
echo "hello world";
?>
Your data is stored in callback function
<script>
$.ajax({
url : 'action/ajax.php',
type : 'POST',
success : function (result) {
//this is where you need to call your data which is result and not success
console.log (result);
},
error : function () {
console.log ('error');
}
});
</script>
You need to execute the returned javascript if you want it to run
success : function (result) {
eval(result); //run the result code
console.log ('success');
},
Content of ajax.php will now be:
<?php
echo 'console.log("hello world")';
?>
But then you nead clean JS without the script tag

Want JS function to use ajax to run PHP and then output PHP on page

I am trying to have javascript run some PHP code and then print the results from the PHP code on the page. I found some code that does this using ajax and also putting the PHP code in an external file. The code I found seems to run the PHP code in an "alert" dialog box, and I cannot figure out how to have it just display the output of the PHP on the current page.
I am new to this so learning, the "success" function has alert(response) so I know why it is doing the alert; but I am trying to make it print it on the page instead and cannot get it to do that…
here is my JS with ajax:
<script type="text/javascript">
var answer = "gman wants a function to run php";
$.ajax({
type: 'GET',
url: 'http://jba.gtdsites.com/script.php',
data: 'answer=' + answer,
success: function(response) {
alert(response);
}
});
</script>
here is the external PHP file (script.php):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
echo "answer is: " . $answer;
?>
<br/>
<?php
echo "<br/>this is working.";
// ...
}
?>
I have been reading a lot trying to figure this out but not connecting the dots and not getting anywhere; so I am wondering if someone can tell me how to get it to just output the PHP stuff on the page instead of doing an alert?
Thanks so much...
If you have a div inside your document with id 'ajax_content' just replace
alert(response);
with
$('#ajax_content').html(response);
you can append/replace you ajax response in your required html element. Like if your html element inside which you want to print is:
<div id="div-to-print-ajax-response"></div>
then your JS function would be like this:
<script type="text/javascript">
var answer = "gman wants a function to run php";
$.ajax({
type: 'GET',
url: 'http://jba.gtdsites.com/script.php',
data: 'answer=' + answer,
success: function(response) {
$('div-to-print-ajax-response').html(response);
}
});
</script>

PHP/HTML/JavaScript: <script> not working when called asynchronously using echo

The innerHTML attribute of a div on my webpage is updated asynchronously (XMLHttpRequest) by getting PHP from the server: but it doesn't seem to call javascript.
This works absolutely fine:
<div id="mydiv"><script>alert('hello');</script></div>
And this works absolutely fine (updating inner HTML of that same div):
echo "<p>Hello</p>";
But this does not work:
echo "<script>alert('hello');</script>";
And I have no idea why! I have tried this in multiple documents, and my searching online seems to suggest it should work.
This is only a problem that occurs when the content is asynchronous. The following works perfectly:
<html>
<body>
<?php
echo "<script>alert('hello');</script>";
?>
</body>
</html>
I can easily design around this, but is it impossible to execute javascript code in this way? As far as I can see, this page suggests work-arounds but doesn't say explicitly that it's impossible: executing javascript in PHP through echo, via ajax.
Thank you!
What you are doing is echoing the script tags into the body of the html, but nothing is asking them the javascript to run. Either way, this is the wrong way to go about this.
You should just execute whatever javascript you want from the success function of your ajax request.
Usually I would pass a JSON object back from my PHP to the success handler, which would JSON.parse it and then do what you wanted with the return data, but you could also use Javascripts eval() although, this is discouraged in most cases due to security reasons.
Not using eval();
Javascript;
$.ajax({
url: "path/to/php.php",
type:'POST',
data: {
data: 'someString'
},
success: function(json){
var obj = JSON.parse(json);
if(obj) {
// run some javascript
}
},
});
PHP file (path/to/php.php);
<?php
// create return object to pass back to client javascript
$return = new stdClass();
// if you have incoming data from the ajax request to the server
$dataFromAjaxRequest = $_POST['data'];
// do somehting with this data;
if($dataFromAjaxRequest == "someString") {
$return->success = true;
} else {
$return->success = false;
}
// clean the buffer
ob_clean();
// encode your return obj to JSON and echo it and die
die(json_encode($return));
?>
Using eval to execute pure php generated Javascript;
Javascript;
$.ajax({
url: "path/to/php.php",
type:'POST',
data: {
data: 'someString'
},
success: function(javascript){
eval(javascript);
},
});
PHP file (path/to/php.php);
<?php
// if you have incoming data from the ajax request to the server
$dataFromAjaxRequest = $_POST['data'];
// do somehting with this data;
if($dataFromAjaxRequest == "someString") {
$return = "alert('success!');";
} else {
$return = "alert('failure!');";
}
// clean the buffer
ob_clean();
// encode your return obj to JSON and echo it and die
die($return);
?>
Hope this will work
<html>
<body>
<script>eval(<?php echo 'alert('hello')';?>);
</script>
</body>
</html>
For better cross-browser compatibility and less verbosity I'd suggest jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});

How to execute javascript inside a script tag returned by an ajax response

I'm sending a jquery get request like so:
$.get($(this).attr("href"), $(this).serialize(), null, "script");
The response I expect to receive will be wrapped in script tags.
I understand the browser doesn't execute the response unless its returned without the script tags. Normally I would remove the tags from the response but in this situation I don't have access to the code running on the remote machine so cannot strip out the tags at the source.
Is there a way I can strip out the script tags from the response client side and execute the javascript?
You should be able to do the following:
$.get($(this).attr("href"), $(this).serialize(), function(data){
var script = $(data).text();
eval(script);
});
Or:
var myScript = new Function($('script#myscript',responseText).text());
myScript();
If I understand your question right, this should suffice to get the text out of the script tags:
$(response).text()
Would this help you: http://docs.jquery.com/Ajax/jQuery.getScript ?
Jose Basilio's answer is okay, but I recommend replacing eval with jQuery's globalEval function...
$.get($(this).attr("href"), $(this).serialize(), function(data) {
script = $(data).text();
$.globalEval(script);
});
globalEval is the function that would normally be called when you call an ajax method with a return type of script.
This from the API documentation...
This method behaves differently from using a normal JavaScript eval()
in that it's executed within the global context (which is important
for loading external scripts dynamically).
Say our response is in the 'response' var:
script = response.replace(/<script>(.*)<\/script>/, "$1"); // Remove tags
eval(script); // Execute javascript
I did this slightly differently, and used php land to make it easier. (I don't like using eval, nor do I like huge conspicuous rewrites).
I placed all my jquery in a php string like so (there was a LOT more JavaScript in real life)
$out .= " $('#save_now').button(); \n";
$out .= " $('#save_now').click( function() {\n";
$out .= " return false;\n";
$out .= " }); \n";
then also in php land
echo "<script>\n";
echo " function onOpen(){ \n";
echo $out;
echo " } \n";
echo "</script>\n";
then in the jQuery $.ajax call I do this
$.ajax({
url: geturl,
type: 'post',
data: getparams,
success: function(data) {
mydiv.html(data);
onOpen();
},
cache: false
});
as you can see you don't nee the php land thing, it's just in my code base I did sort of need to do it. the trick is to do away with $(document).ready(function(){}); and roll your own

Categories

Resources