How to call a specific function in a PHP script via Ajax? - php

Lets say I have a file called functions.php, and it has two separate functions inside:
One would get the time
And the other would get the date
How will I, using JQuery AJAX retrieve data from the function that retrieves the date. How do I specify in the JQuery code which function on the server to pick.
I hope I am making sense. Thanks.

You could include a selector in the ajax request data. For example:
$.ajax({
url: "functions.php",
data: "function=time", // or function=date if you want date
...
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['function'] == 'time') {
// do time stuff
} elseif($_GET['function'] == 'date') {
// do date stuff
}
}

You don't specify in jQuery what function to execute in PHP. What you do is request a document, possibly with a query string, and read the results. Your functions.php script is responsible for executing whatever is requested.
So, you might from jQuery request functions.php?fn=time in one place and functions.php?fn=date in another. Then, in functions.php, you would examine the query string and execute the appropriate function for what was requested, returning the results to jQuery.

$(document).ready(function()
{
$(".link").click(function()
{
var data['func'] = "time";
var url = functions.php
$.get(url, data, function(result)
{
$("#feedback").html(result);
});
});
});
then your php file would be,
if(isset($_GET['func']))
{
if($_GET['func'] == "time")
{
showTime();
}
else
{
showDate();
}
}
function showTime()
{
//show time
}
function showDate()
{
//show date
}
Code is untested but should be a good starting point for you.

you can add a parameter to the url:
example:
function.php?g=1
now, on the serverside check for the get parameter:
if($_GET['g']==1)
{
echo date();
}
else
{
echo time();
}

What is the response your are getting. You are getting the response in XML or some other format. If your response is XML try with this option.
$.ajax({
url:path,
data:{projectId:inpprojectId},
dataType:"xml",
success:function(data){
$(data).find("CheckAmount").each(function(){
total = $(this).find("TotalAmount").text();
usdAmt = $(this).find("PettyCashAmount").text();
validateBudget(total,inp);
});
}
});

Related

PHP file not picking up $POST parameter from JQuery

Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.

How can I pass a variable from PHP to javascript

I have a php page with
<?php echo $_SERVER['DOCUMENT_ROOT']?>
Then my javascript is
var data = "Not Set";
$.get("test.php",function(returnData,requestStatus,requestObject){
data = returnData;
alert(data);
});
If I navigate directly to the php page on the site, it displays the data that I need.
I just can't seem to get the data into my javascript.
Am I on the right track and if so where am I going wrong?
Or is there an easier way to get the full filepath when working with a server?
Currently if I run document.location.href in my javascript it returns .
http ://127.0.0.1/etc
The code below will work on ".php" file. NOT ON ".html" file.
You can use the php variable with echo in javascript. For example
alert('<?=$phpvariable?>');
or
alert('<?php echo $phpvariable ?>');
It seems you are overthinking this. There is hardly any need to use ajax, but of course you can and just append() the data from the ajax call to your $('body') and jquery will automatically execute things inside a <script> tag.
var serverRoot = '<?php echo $_SERVER['DOCUMENT_ROOT']?>';
Try following
Instead of GET send $.post request and file don't return any thing just write
$.post("Requestedfile.php",
{
data :data
},
function(data) {
if(data == false)
{
//do something
}
else
{
//do somthing
}
}
);

Jquery replaceWith:replace one php file with another php file based on screen resolution

I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.

Getting through the DOM from the file to which I did a post request through ajax

I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)

Preventing to execute a JavaScript function more than once

I am using JavaScript, jQuery and PHP. How do I limit the JavaScript function to execute once?
My MainJQuery file has Ajax. display.php execute for a while:
....
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: function(data){
$("#response").html(data);
//Here Get_list should be execute only once.
get_list('get');
// Display should execute as usual
display();
}//success
}); //Ajax
.......
get.Php file writes a value to JavaScript:
<?php
print "<script language='javascript'>";
print " g_cost[g_cost.length]=new Array('STA-VES','East',4500);";
print " g_cost[g_cost.length]=new Array('STA-CRF','West',5400);";
print "</script>";
?>
My JavaScript function has the following value from PHP:
function get_list('get'){
for(var i=0;i<g_cost.length;i++)
var temp = g_cost[i];
var Name = temp[0];
var direction = temp[1];
var cost = temp[2];
..
some code
...
}
function display(){
for(var i=0;i<g_cost.length;i++)
alert(g_cost.length);
var temp = g_cost[i];
alert(temp[0]);
alert(temp[1]);
alert(temp[2]);
}
Is it possible to limit to execute a JavaScript function in the jQuery Ajax success portion?
In jQuery you can use the .one() function to bind a method that will execute only once. For example,
$("#someAnchorId").one("click", function(){
//Ajax method here
});
See jQuery one help topic.
You can replace the function with an empty function - this is essentially the same as Rene Saarsoo' solution, but looks nicer:
var get_list = function(param1, param2, ...) {
// your code here
get_list = function() {};
};
Three options:
Set a boolean flag in global scope, set it after a successful run, and check it before running
After a successful run, disable the button (or whatever control you are using to call the one-time method)
Slightly less preferred, but you can also do the validation on server side, i.e. call the method each time, but validate on server-side. The up side is that this will ensure data consistency on the server.
To create a function that executes only once:
get_list = (function(){
var counter = 0;
return function(param1, param2, ...) {
if (counter > 0) {
return;
}
counter++;
// your normal function code here
};
})();
This is almost the same as using a global variable for tracking how many times function is executed, except that instead of a global variable we create a variable, that only the inner function can see. After that you use it get_list as any other function.
This could probably be refactored into something more general in function prototye, so it could be used like this:
get_list = (function (param1, param2, ...) {
...
}).once();
Fastest way is to add one extra line to success declaration:
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: function(data){
if(!arguments.callee.stop){ arguments.callee.stop = true; }else{ return; }
$("#response").html(data);
//Here Get_list should be execute only once
get_list('get');
// display should execute as usual
display();
}//success
}); //ajax
Try disabling the Ajax trigger (link, button, etc.) after a successful call.
Example of a trigger:
<a id="ajax_trigger" href="#" onclick="yourAjaxCall(); return false;">Get List</a>
...
success: function(data){
$("#response").html(data);
//Here Get_list should be execute only once
get_list('get');
// Some code to disable, or hide #ajax_trigger
// in other words, make it unclickable or disappear.
$("#ajax_trigger").css('display': 'none'); // IIRC
// Display should execute as usual
display();
}//success

Categories