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
Related
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
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;
});
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>
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);
});
Is it possible the Javascript variable value to the php url parameter? please see following code and give a suggestion how to do this?
Html code:
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
in this code i call JS function deleteRole?():
script:
function deleteRole(myvar) {
if (confirm('<?php echo $delConfirmJS ?>')) {
location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
In my controller page i receive the myvar as string not the value?
controller.php
public function delete($id){
echo $id;
exit;
$delete = roleinfo::delete($id);
$this->redirect('/role/add_role'); }
this echo print "myvar" only not a value? Please suggest me its write way or not ? else how to do this?
thanks
Kumar
You can't send or assign a JS variable directly to PHP function or variable, because of JS is a client side language and PHP is a server side language.
If you want to send you JS variable, one way is - you can send a ajax request to server, and then your variable will be available in php, and can use it.
Here is sample ajax format:
$.ajax({
cache: false,
url: base_path + '{file_name_where_you_want_to_receive_that_value}',
type: 'post',
data: {
myvar: myvar
},
success: function(data) {
// when you provided url procedd the req. then success will call.
}
})
And in [file_name_where_you_want_to_receive_that_value] assing that value to some variable and use it.
Do you have a form or smthg? I suppose the easiest way would be with a hidden field where you just modify the value via JS and send it to PHP with POST. Its not a clean or professional way, but easy to implement and does its job.
The most simple AJAX request you can make is the following (using jQuery for simplicity, you can search for how to do an AJAX request without jQuery):
function deleteRole(myvar) {
$.ajax({
url: "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>",
}).done(function(data) {
console.log(data);
$( this ).addClass( "done" );
});
}
This will create a new request to the specified URL, and basically run the controller action. You will have the request response in the javascript variable data.
More info here.