Using ajax to call php - javascript

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

Related

jQuery ajax php function

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;
});

Sending data from javascript to php using via Ajax using jQuery. How to view the data back?

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!

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>

Load php in background with javascript, not passing variables

I'm working on this function that loads a php file in the background:
<div id="content1"></div>
<script type="text/javascript">
<!--
$("#content1").load("/bm_products_filter.php");
//-->
</script>
The original php code is this:
<?php require('/bm_products_filter.php');
?>
With the original code the page works fine, with the java code it gives errors. This is because the php doesn't use the variables in the current page. I know how to pass variables to the external php but is there a way that it uses all the variables on the current page?
I am not sure if I got you wrong but you cannot load PHP files with JavaScript or JQuery.
JavaScript is client sided and has no access to the server if you want to load some data on a point of time when the template builds / is built without PHP oyu have to use an Ajax request which is also pretty simple with JQuery.
Please check out:
http://api.jquery.com/jquery.ajax/
If you can rewrite the bm_products_filter.php to return a JSON output, you can use a function as below to get values returned from the php.
jsonKey1 I have used below is one of the JSON keys returned from the php.
function getToken() {
var requestStr = "./bm_products_filter.php";
$.ajax({
url: requestStr,
type: "GET",
cache: true,
dataType: 'json',
success: function (data) {
bmProductsData = data.jsonKey1;
}
});
}
Hope this helps.

Is it possible to send the JS variable to parameter of the php function

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.

Categories

Resources