Dynamically call PHP Function with ajax - javascript

I had a question;
How would one call multiple PHP functions and output them onto the page?
Now i have found a way, could anyway let me know how i could improve my answer.
It works perfectly, I just want to see what could be a better way.
AJAX CALL;
$.ajax({
url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
data: {call: 'Login', parameters: {Username, Password}}, //CALL the function name with an array of parameters
type: 'post'
}).done( function( Output ){
try{
Output = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
} catch (e){
alert('Error calling function.');
}
});
PHP "functioncalls.php" page
if(isset($_POST['call']) && !empty($_POST['call'])){ //check if function is pasted through ajax
print call_user_func_array($_POST['call'], $_POST['parameters']);//dynamically get function and parameters that we passed in an array
}
PHP FUNCTION - make sure your function is either on the page or included
function Login($Username, $Password){
// function control
return json_encode($return);// return your json encoded response in value or array as needed
}
And that's that, Nothing else needed you can call any function and use it in your done ajax promise.
Note: Your parameters have to be passed as an array.
Thank you

change your ajax request like this
$.ajax({
url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
data: {call: 'Login', parameters: JSON.stringify([Username, Password])}, //CALL the function name with an array of parameters
type: 'post'
}).done( function( Output ){
try{
Output = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
} catch (e){
alert('Error calling function.');
}
});
in php you have to do something like this:
$params = json_decode($_POST['parameters']);
login($params[0], $params[1]);

Related

Javascript processes 200 response before server sends the 200

I have a timing problem with an ASP.NET core 5 system I'm working on. My page shows a DataTable with id='outsideDataTable', and when an item is selected a modal bootstrap dialog is shown. The submit button invokes method submitModal() which does this:
$.ajax({
type: 'POST',
url: '/api/Submit',
dataType: 'json',
statusCode: {
200: SubmitDone()
},
error: 'SubmitError',
data: $('#ModalForm').serialize()
});
The /api/Submit function calls the server's Submit function which does an update to the database. None of the C# code uses async coding. The database interface is NPoco. At the end of the update the function calls Ok() which I believe returns the status 200 to the ajax call.
[HttpPost("api/[action]")]
public IActionResult Submit(
int recordId,
... other formdata ...)
{
if (recordId == 0)
{
var sr = new Record() { ... fill with form data ... };
db.Insert(sr);
}
else
{
var sr = db.Single("select * from Records where recordId=#0", recordId);
if (sr == null)
return BadRequest($"Couldn't find record with ID={recordId}");
... update sr with form data ...
db.Update(sr);
}
return Ok();
}
The OK() function returns status of 200 back to the client, which should now execute the js SubmitDone() function.
function SubmitDone() {
$('#ModalDlg').modal('hide');
$('#outsideDataTable').DataTable().draw();
}
The problem is that when the outsideDataTable is redrawn from within the SubmitDone function, it will retrieve the data, which does not yet include the changes put into the database by the submit action routine. Why is that? In my opinion the database should have done its thing by the time the status 200 is returned to the ajax call, ergo when the redraw happens the database should have the new data.
As a matter of fact, in fiddler I see that the list load from the redraw happens before the ajax to the submit function.
I have not isolated this into working code I can share, but can do so if needed - unless someone knows what I'm doing wrong.
When you assign the SubmitDone function to the statusCode.200 callback you shouldn't use parentheses because this is making the function execute immediately. Instead, it should be like this:
$.ajax({
type: 'POST',
url: '/api/Submit',
dataType: 'json',
statusCode: {
200: SubmitDone
},
error: 'SubmitError',
data: $('#ModalForm').serialize()
});

AJAX call using IIFE? Can't seem to get .done to work the same as a regular function

I currently have an AJAX call out to a PHP file that works, that is the following:
//Load map from database
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap(JSON.parse(r.mapArray), JSON.parse(r.mapProperties)); //call loadedMap(r) if loading a map from DB
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
That works within a single javascript file that successfully passes r.mapArray and r.mapProperties to my main loadedMap function.
I'm trying to learn about the IIFE Javascript Module model, and split my work up into separate files.
So, I currently have main.js:
(function() {
// let's get our map
var gameMap = mapGen.getMap().done();
console.log(gameMap);
})();
and mapGen.js:
var mapGen = function() {
return {
getMap: function() {
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
}
};
}()
If I console.log(gameMap), I see the responseText JSON object with my data. I just can't seem to access it. console.log(gameMap.responseText) is undefined. as is gameMap.responseJSON (though I see both of them in the console).
Looking the code over it looks as the the separation of the files was not the issue and that looks to be implemented correctly. The issue is with how you are handling the AJAX request. The function mapGen.getMap() actually returns a jqXHR Object as opposed to the response that you are trying to access.
Just as you had in your previous file, you will need handle the response of your request.
(function() {
// let's get our map request
var gameMap = mapGen.getMap();
gameMap.done(function(r){ ... }).
fail(function(x){ ... });
})();
You will be able to access the response data you are looking for within the done() function.

Check return value when parsing json array in javascript

I'm a beginner in ajax and json so I'm sorry if this question is a bit stupid. I'm retrieving the data(city id and name) and put them in an array then use json_encode. Then I call the getCities function but I'm not sure if I'm getting the correct cities. I tried using document.write but there's no output. How can I know if I'm getting the correct ones? Thank you for your help.
Here's the getCities.php:
$json = array();
$query = "SELECT cityID, cityName FROM city";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$coord = array('id' => $row['cityID'],'city' => $row['cityName']);
array_push($json, $coord);
}
$jsonstring = json_encode($json);
And here's the javascript part:
function getCities(){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json'
}).responseText;
return JSON.parse(string);
}
$(document).ready(function (){
var city = getCities();
while (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
There are 2 easy ways to do this. First of all I use Google Chrome (or Firefox) to facilitate testing. Look at the docs and you will see that your $.ajax call will also accept a success function. You could put it in the ajax call under dataType like this:
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success: function(data) {
console.log(data);
}
});
string.done();
Notice how I changed the end of the ajax call. It is now saying, when this call is done, call the success function. You can also put an error function in the ajax call if you want to have something print out in case of an error. The success function will then be called when the data returns. It will print in the console of your Chrome debugger. Google that term to find out how to show it, super easy stuff. You can also put a break point on the console.log function call (Google how to do that also) and you will be able to inspect the object that is returning from your ajax call.
Also, the console.log will not work in IE as far as I know.
Have fun.
function getCities(callback){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success:callback
});
}
$(document).ready(function (){
getCities(function(data){
console.log(data);
var city = JSON.parse(data);
if (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
});
Ajax is asyn, you cannot use var city = getCities();. Because when you call that, ajax response has not arrived yet. You need to pass in a callback function, and when ajax response has arrived, call that function to get the response.

Setting string in javascript function in ASP.NET MVC give NullReferenceException

Inside my MVC view I have javascript that is executed by a button click. I'm trying to set a string to a random set of characters which I can get to work fine but when I try and set that string to 'randomchars' string inside the javascript I get a NullReferenceException when I try and run the view.
Below is the code snippet, the CreateRString is where the model parameter (RString) is set to the random string.
<script type="text/javascript">
function showAndroidToast(toast) {
var url = '#Url.Action("CreateRString", "Functions")';
$.ajax({ url: url, success: function (response) { window.location.href = response.Url; }, type: 'POST', dataType: 'json' });
var randomchars = '#(Model.RString)';
}
</script>
Is the syntax correct? I'm not too sure why it's getting the NULL.
The javascript is executed after the page been delivered to the client (i.e. web browser). Your razor code here is executed on the server before the page is sent to the client. Therefore, the ajax method will execute after you try to access Model.RString
To fix this you can either call CreateRString on the server, or you can set randomchars by using the response in the success callback.
To explain option 2 a bit further. You could do something like this:
//Action Method that returns data which includes your random chars
public JsonResult CreateRString()
{
var myRandomChars = "ABCDEF";
return new JsonResult() { Data = new { RandomChars = myRandomChars } };
}
//The ajax request will receive json created in the CreateRString method which
//contains the RandomChars
$.ajax({ url: url, success: function (response) {
var randomchars = response.Data.RandomChars;
window.location.href = response.Url;
}, type: 'POST', dataType: 'json' });
More specifically, the razor calls #Url.Action("CreateRString", "Functions") and #(Model.RString) execute first on the server.
Then showAndroidToast executes in the client's browser when you call it.

Waiting for a function to return a value before firing jQuery Ajax request

I'm trying to fire an Ajax request with some data being returned by a function call and, as far as I can tell, the Ajax call isn't waiting for my function call to return.
I'm calling getSelectedMessages to get the values of a variable number of checkboxes before firing an Ajax request with an array of the values returned by getSelectedMessages.
getSelectedMessages looks like this:
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
And the Ajax request that's invoking it looks like this:
$.ajax({
type: "POST",
url: "/api/messages/",
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
I've done a little bit of searching around and all I'm turning up are answers on how to return a value from a call and to it.
use
beforeSend attribute with ajax
try
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
$.ajax({
type: "POST",
url: "/api/messages/",
beforeSend : function () { return jQuery.isEmptyObject(getSelectedMessages); }
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
Reference
beforeSend
isEmptyObject
Call getSelectedMessages() outside the ajax function of jquery (?)
The function is executed before the request is sent.
The real problem is that the getSelectedMessaged() returns an array.
This results in undefined=undefined after serialization in jQuery's internals.
And that gets ignored by the $.ajax(), so it looks like it's not sending in your vars but it's ignoring them because they're undefined.
If you concatenate a string with the values and make it a query string parameter yourself it should work.
I assume you want to send something like ?var[]=something&var[]=somethingelse to the server, so it ends up in PHP as an array?
Than you'll have to build up the string yourself in the getSelectedMessages function.
Hope it helps,
PM5544

Categories