call php function with arguments using Jquery - php

I have a php file func.php where I defined many functions let's say :
<? php
function func1($data){
return $data+1;
}
?>
I want to call the function func1 using ajax. thank you for your help

You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});

You should call your php script through an ajax request, using jQuery like:
Javascript:
$.ajax({
url: "script.php",
data: { param1: "value1", param2: "value2" },
type: "GET",
context: document.body
}).done(function() {
// your code goes here
});
You could give your parameters through data property of ajax object.
Php
// you can do isset check before
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// validate // sanitize // save to db // blah blah // do something with params
More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/

It's a bit more complicated, but I will try to shrink it down to the basics.
You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:
The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.
The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.
Add the following code along with your functions:
if(isset($_GET['func']))
{
$func=$_GET['func'];
if(function_exists($func))
{
$args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
$result=call_user_func_array($func,$args);
}
else
$result=array('error'=>"Unknown Function $func!");
}
else
$result=array('error'=>"No function name provided!");
echo json_encode($result);
However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.
Your example function, for instance, should look something like this:
function func1(){
$data=func_get_args();
if(count($data)) // at least one -- rest will be ignored
return $data[0]+1;
else
return array('error'=>__FUNCTION__."() expects an argument!");
}
Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.

Yes you can !
here my code :
$.ajax({
type: "POST",
url: "ajax.php",
data: { kode: $(this).val(), func: 'my_func' },
success: function(response) {
//any success method here
}
});
and here the code in php to receive what function to call.
$post = (object) $_POST;
if(!$post)
return false;
$func = $post->func;
return $func($post);
function my_func($post) {
$json['any_data'] = false;
if($post->kode == 'ND'){
$json['any_data'] = 'ND-'.date('Y');
}
echo json_encode($json);
}
Hope it help you out bro... :D

Related

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST

Ajax return value with return not work

I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>

javascript to post to url and

I am writing a javascript which will post hostname of the site to a php page and get back response from it, but I don't know how to assign the hostname to adrs in url and not sure that code is correct or not.And this needs to done across server
javascript:
function ursl()
{
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
success: function (response)
if (response)=='yes';
{
alert("yes");
}
});
}
track.php
$url=$_GET['adrs'];
$sql="SELECT * FROM website_ad where site='$url'";
$res=mysqli_query($link,$sql);
if(mysqli_num_rows($res)==0)
{
echo"no";
}
else
{
echo"yes";
}
Your ajax function should be written thusly:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=' + window.location.hostname,
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
window.location.hostname will give you the host name. You are passing it to the ajax url by concatenating it. Alternatively, as katana314 points out, you could pass the data in a separate parameter. Your ajax call would then look like this:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
data: {adrs: window.location.hostname},
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
I'm not sure what you intend response to be, but this code assumes it is a string and will match true if the string is 'yes'. If response is meant to be something else, you need to set your test accordingly.
$.getScript() will load your external script, but since it's asynchronous you'll have to put any code that is dependent on that in the callback.
In this type of GET request, the variable simply comes after the equals sign in the URL. The most basic way is to write this:
url: 'http://example.com/en/member/track.php?adrs=' + valueToAdd,
Alternatively, JQuery has a more intuitive way of including it.
$.ajax({
url: 'http://example.com/en/member/track.php',
data: { adrs: valueToAdd }
// the rest of the parameters as you had them.
Also note that you can't put a script tag inside a script. You will need some other way to run the Javascript function mentioned; for instance, wrap its contents in a function, load that function first (with a script tag earlier in the HTML), and then call it on success.
And for the final puzzle piece, you can retrieve the current host with window.location.host
You'll need to change this line to look like so:
url: 'http://example.com/en/member/track.php?adrs='+encodeURIComponent(document.URL)
The full success function should look like so:
success: function (response){
if (response==="yes"){
//do your thing here
}
}
That should solve it...

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

jQuery IF statement not working

Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".
All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
}
});
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
Any code that relies on the response from the AJAX request, must be called inside a callback to the request.
function check_name() {
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function (html) {
$("#checkname").html(html);
// I placed your code here instead.
// Of course you wouldn't need to set and then get the HTML,
// since you could just do a direct comparison.
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml == compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
The reason is that by default, an AJAX request is asynchronous, which means that the code that comes after the request will execute immediately instead of waiting for the response to return.
Another possible issue when comparing HTML to keep in mind is white space. If you're doing a string comparison, it must be exactly the same, so if there's whitespace, you'll need to trim it first. You can use jQuery.trim()(docs) to do this.
You have to put the code inside of you AJAX requests success callback, otherwise it will be called before the AJAX call has completed. Putting it inside the success callback means that the code containing the IF statement will only run after the AJAX call has completed. Try:
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
You could probably solve the problem doing what patrick dw suggested (it's likely that the ajax call has not been completed yet (i.e. div content wasn't updated) and the check returns false), but since string comparison can really bring to many errors (like string not matching because of newlines, trailing spaces, case sensitiveness, etc...) I would suggest you use another comparison method.
For example you could add a class using .addClass() if the car is found, and then checking if that div has the "found" class using .hasClass()
I use .post(). The third argument of post() is the returned data from the file where the data was posted.
I pass to validate.php the inputed email address, validate.php checks it and if it is valid, it returns 1.
$('a.post').click(function() {
$.post('validate.php',{email : $("#email-field").val()},
function(data){
if(data==1)
{
//do something if the email is valid
} else {
//do other thing
});
});
Hope this helps.

Categories