I am developing one website using cakephp and jquery technologies.
Server-side there are some functions which handles SQL queries.
As per requirement I want to modify server side functions on client side using jQuery AJAX call.
E.g. : Below is the function on server side to modify users information.
function modifyUser(username,userid) {
//update query statements
}
Then jquery AJAX call will be like this:
$.ajax({
url: 'users/modiyUser',
success: function() {
alert("Updation done") or any statements.
}
});
and I want to modify above i.e. server side function depending upon client input criteria.
$.ajax({
function users/modiyUser(username,userid) {
// I will write here any other statements which gives me some other output.
}
});
Above AJAX call syntax may not present, but i think you all understood what I am trying to do I simply wants to modify/override server side functions on client side.
Please let me know is there any way to resolve above mentioned requirement.
Thanks in advance
You cannot call a PHP functions from the client directly. You can only make an HTTP request to a URI.
The URI determines the PHP script run. Input can be taken via $_GET, $_POST, and $_COOKIE (among others, but those are the main ones).
You can either write separate scripts for each function or determine what to do based on the user input.
You could have a server-side function in a separate PHP file to do this, and make an AJAX call call into that function first to perform the modification. But client-side changes to server-side code are just not possible.
I can't actually imagine why you would want to do this, though.
why override a function???
can i suggest this?
in PHP
try {
// functions here....
function modifyUser($username,$userid) {
//update query statements
if(!is_string($username)) throw new Exception("argument to " . __METHOD__ . " must be a string");
if(!is_string($userid)) throw new Exception("argument to " . __METHOD__ . " must be a string");
// do some modification codes....
}
function delete($userid){
// do stuff blah blahh...
}
// $_POST or $_GET etc. here
if(isset($_GET["modify"])){ // I make use of get for simplicity sake...
$username = $_GET['username'];
$userid = $_GET['userid'];
modifyUser($username,$userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been modified";
echo json_encode($ret);
} else if(isset($_GET["delete"])) {
$userid = $_GET['userid'];
delete($userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been deleted";
echo json_encode($ret);
}else {
// the client asked for something we don't support
throw new Exception("not supported operation");
}
}
catch(Exception $e){
// something bad happened
$ret = array();
$ret["error"] = true;
$ret["msg"] = $e->getMessage();
echo json_encode($ret);
}
in jQuery ajax
$.ajax({
url: 'ajax.php',
data : { modify : true, // sample for modify... can also be delete : true,
username : $('#username').val(),
userid : $('#userid').val() },
type: 'GET',
dataType: 'json',
timeout: 1000,
error: function(){
alert('error in connection');
},
success: function(data){
if(data.error)
alert('Something went wrong: ' + data.msg);
else {
alert('Success: ' + data.msg);
}
}
});
Related
For me this is something new, so I am just researching this and trying to understand it.
As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.
Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck.
I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?
The problem is that when I attach a database to it, I would need to consider all inputs that can happen.
How do I specify a specific php function when using jquery & ajax?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:
url: "function.php?action=functionname"
or:
data: {
name: 'myname',
action: 'functionname'
}
Then in PHP, you can access that attribute and handle it:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
Implementation example:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
You are actually quite close to what you want to achieve.
If you want to specify which function will be called in PHP, you can pass a variable to tell PHP. For example, you passed request=save in AJAX, you can write the PHP as follow:
$request = '';
switch(trim($_POST['request'])) {
case 'save':
$player_name = (isset($_POST['playername']) ? trim($_POST['player_name']) : 'No Name'));
saveFunction($player_name);
break;
case 'load':
loadFunction();
break;
default:
// unknown / missing request
}
EDIT: You can even pass along with other parameters
This may not be exactly what you are looking for but it can help some others looking for a very simple solution.
In your jquery declare a variable and send it
var count_id = "count";
data:
{
count_id: count_id
},
Then in your php check if this variable is set
if(isset($_POST['count_id'])) {
Your function here
}
I have an Ajax script that makes a call to a php file on my server every twenty seconds.
The server then runs a simple mysql query to return the contents of a particular field.
If that field is blank I want the php file to echo the word "pending", which when caught by the success handler will recall the initial function. However if that field is not blank, it will contain a URL to which I want to redirect the user to. That field will update any where between 5 seconds and 5 minutes from the start of the first call and that time cannot be changed.
I think the main issue may be with my php file, in that I dont think it is echoing the data in a way that the success handler recognises. However I have detailed both parts of my code as whilst the success handler seems to be constructed correctly I am not 100% sure.
Very new to this, so apologies if I have not explained myself correctly but if anyone could assist that would be great:
UPDATE - for clarity what I am looking to achieve is as follows:
Ajax call to my php file.
PHP file queries database
If field queried contains no data echo the word "pending" to the ajax success handler (IF) which in turn recalls the original function / ajax call.
If field queried contains data (will be a URL) echo this result to the ajax success handler (ELSE)in a format that will redirect the user via window.location.assign(data).
FURTHER UPDATE
I managed to solve this question with using a combination of the advice from #mamdouhalramadan and #martijn
I also have changed setInterval to setTimeout as the poll function was causing responses to stack up should the server be running slowly and as such cause errors. I also added in cache: false and a further option in the success handler to take into account slightly different behaviour in IE:
AJAX
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
cache: false,
async: false,
success: function(data3) {
//alert("pending called " + data3)
if(data3.indexOf("pending") >-1 ){
setTimeout(poll, 20000);
}
else if ( (navigator.userAgent.indexOf('MSIE') != -1) ) {
//alert("Submit success - MSIE: " + data3);
parent.window.location.replace(data3);
}
else{
//alert("process three called " + data3)
window.top.location.assign(data3);
}
},
error: function(xhr, error){
//alert("Error");
//alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
}
setTimeout(poll, 20000);
PHP
$query = ("SELECT column FROM table WHERE id = '$lead_id'") or die(mysql_error());
$result = mysql_query($query);
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return = 'pending';
if($row['column'] != '')
{
$return = $row['column'];
}
}
echo $return;
I believe using json might help you out here, not to mention it is safer, like so:
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("pending") >-1 ){
//rest of the code.....
then in your php:
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return['res'] = 'pending';
if($row['column'] != '')
{
$return['res'] = $row['column'];
}
}
echo json_encode($return);
Note: use PDO or MYSQLI instead of mysql as it is deprecated.
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.
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).
I was wondering if it's possible to long poll using $.getJSON and what the proper front and back end logic would be.
I've come up with this so far but haven't tested it yet since I'm pretty sure there is wrong and/or missing logic.
Here is the JS:
function lpOnComplete(data) {
console.log(data);
if (!data.success) {
lpStart();
}
else {
alert("Works!");
}
};
function lpStart() {
$.getJSON("http://path.to.my.URL.php?jsoncall=?", function(data) {
// What happens when no data is returned
// This is more than likely since there
// is no fall back in the PHP.
lpOnComplete(data);
});
};
PHP:
$time = time();
while((time() - $time) < 30) {
// only returns data when it's new.
$data = checkCode();
// What would be the proper way to break out
// and send back $data['success'] = false
// so the JS loop can continue?
if(!empty($data)) {
echo $_GET["jsoncall"] . "(" . json_encode($data) . ")";
break;
}
usleep(25000);
}
From what you've got there, the Javascript is going to make multiple requests to the server and each one is going to spin up that infinite loop, and never go anywhere. I'd suggest something like: js:
$.getJSON("http://my.site/startAsyncWork.php", null, function(data){
waitUntilServerDone(data.token, function(response){
alert("done");
});
});
function waitUntilServerDone(token, doneCallback){
$.getJSON("http://my.site/checkIfWorkIsDone.php", {"token": token}, function(response){
if(response.isDone){
doneCallback(response);
}
else{
setTimeout(function(){
waitUntilServerDone(token, doneCallback);
}, 1000);
}
});
}
I don't know php, so I'm not going to write sample code for that side, but basically, startAsycWork.php makes up a random token that associates to the request. Then it spawns a thread that does all the work needed, and returns the token back to the response.
When the worker thread is done, it writes the results of the work out to a file like token.dat (or puts it in a cache or whatever).
checkIfWorkIsDone.php checks for the existence of token.dat, and returns false if it doesn't exist, or returns the contents if it does.