Call PHP Method with Ajax [duplicate] - javascript

This question already has answers here:
Call PHP Function using jQuery AJAX
(3 answers)
Closed 7 years ago.
I am trying to call another php file's function using ajax.
Here is the Ajax Call :
function getBaseURL() {
var pathArray = location.href.split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;
return url+"/PhpProject2";
}
function getPageSaverUrl() {
return getBaseURL()+"/manager/content_manager/page_saver.php/SaveTest";
}
function savePage() {
alert("Saving Page");
var url = getPageSaverUrl();
$.ajax({
type: "POST",
url: url,
data: "name=hello",
success: function(response){
alert(response);
}
});
}
But i am not getting any response from the script. Can we call php funciton from ajax url parameter?

You cannot call php function from ajax url parameter.
You can use parameter with ajax call, see following code -
function getPageSaverUrl() {
return getBaseURL()+"/manager/content_manager/page_saver.php?param=SaveTest";
}
then in file page_saver.php, you need to fetch parameter 'param', which will have value 'SaveTest', then execute this function.
Try this, let me know if you have any further query.

first of all the ajax and normal http request are both the same according to backend . They hit the server and explore the url you called .
if you call - "http://website.com/mypages/page1" .
It reaches the port 80 on the server website.com
if any software application listens that port will receive the request.
in case of php app . The apache server receives the request and explore the url "/mypages/page1" inside the Document root configured . And find the directory "page1" inside "mypages" directly if not any rewrite rules. If the index file you configured is index.php it searches for it , and run it . In that index file you get the data using php variable as per the request type. if it is post data "$_POST" or if query string "$_get" or some other php stuff . And you have to call the required function as per your need through php logics.
In the above ajax the data has to be
data:{name:"hello"}
or otherwise if you need to send the form data use
$(form).serialize()

Related

Get JSONP Response back to Original Function Call [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
In basic terms I am trying to make a cross domain AJAX call using JSONP. The JS and PHP files need to be on a different domain. I can't seem to get the returned data back to the original function.
To explain how the page works. A user will enter something into an input box. e.g. Surname.
Input and search.
After the user clicks search a the searchClick() function is called. This function takes the text the user has inserted into the input box and calls another function called getInfo().
function searchClick() {
var jsonOfData = getInfo($('#searchInput').val());
console.log(jsonOfData );
}
The getInfo() function has to be in a JS file on a different domain.
function getInfo(surname) {
$.ajax({
url: "https://www.otherdomain.com/api/lookup.php",
dataType: 'jsonp',
crossDomain: true,
data: {
surname: surname
},
success: (data) => {
console.log(data); // This works
return data; // This doesn't
}
});
}
This ajax call goes off to my PHP page and does a search on the database. It then created a JSON array and sends it back. From my research instead of ending the file with the usual echo json_encode($array); I ended the file with:
echo $_GET['callback'] . "(" . json_encode($responseArr) . ")";
This is the point at which I have my problem. As you can see, in the AJAX success function, the data is successfully displayed and logged to the console but I can't return it back to the original jsonOfData variable.
I hope this makes sense and i'll be so thankful to anyone who can help me out.
What you're trying to do won't work, because the $.ajax calls works asynchronously.
Instead of work with the return of the function call at this point:
var jsonOfData = getInfo($('#searchInput').val());
Try to build your logic inside the success function of your $.ajax call.

Making ajax calls to get response from two javascript files to a single php file

I am working with JQuery Ajax. The PHP file I require response from is on the server. The first JavaScript file is on the same directory on the server with PHP and the second file is saved with me locally which I am using inside my chrome extension. I have made a block of code in PHP, which I run through Ajax from local JavaScript file and get response, what I want is to get invoke the JavaScript on server , and can be solved by two methods.
1) To make Ajax call to same block of code of PHP, which saved in the same directory on the server.
2) Invoke the JavaScript on server from the local JavaScript file. When the local JavaScript get the response then use a method to invoke the JavaScript on server from this local one.
Basically I tried both of them, I have made a second Ajax call to same block of code, but as the server html file run first and load the JavaScript first, then It do not return anything from that Ajax request.
In the second method I have used postMessage API of chrome. But it blocks the cross origin message passing, from local to server. And the domain name conflicts stop passing my message to invoke the server JavaScript.
Local file JavaScript that request data and get response
function sendUrl(url){
console.log("Passed to sendURL : " + url);
$.ajax({
method:"GET",
url:"http://www.bitbaysolutions.com/connections.php?updateRow=true",
data:{
ajaxified : url
},
success:function(res){
console.log("PHP RESPONSE " + res);
}
});
}
I want to invoke the server JavaScript when I get response from this Ajax call. Simply on success.
When I use post Message API in the same Ajax call response
function sendUrl(url){
console.log("Passed to sendURL : " + url);
$.ajax({
method:"GET",
url:"http://www.bitbaysolutions.com/connections.php?updateRow=true",
data:{
ajaxified : url
},
success:function(res){
console.log("PHP RESPONSE " + res);
window.postMessage(res,"*");
}
});
}
And write this code on server JavaScript file to receive the message
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
console.log(e.data);
});
After running it I get the following error : GET chrome-extension://jifdgpnmlcmlcbpmemiecblbddpdejhe/Row%20Updated net::ERR_FILE_NOT_FOUND
Simply I would like to invoke the server JavaScript file when I get response on this local file. And if there is any other possible solution, I would appreciate that.
It looks like you should be using Chrome's Message Passing instead of window.postMessage.
So your Javascript in the extension would look something like this:
function sendUrl(url){
console.log("Passed to sendURL : " + url);
$.ajax({
method:"GET",
url:"http://www.bitbaysolutions.com/connections.php?updateRow=true",
data:{
ajaxified : url
},
success:function(res){
console.log("PHP RESPONSE " + res);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {thisCameFromTheServer: res},
function(response) {
//If your script on the page sends a response,
// deal with it here.
//console.log(response.farewell);
}
);
});
}
});
}
Your Javascript on the page that receives the message would have to be inserted as a Content Script by the extension, and that script can either manipulate the page directly, or call JS that's loaded from the server.
The Content Script would receive the message like this:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.thisCameFromTheServer) {
console.log(request.thisCameFromTheServer);
}
/* I *think* that you have access to the whole page DOM, and any JS
on the page, from here, so if there's a JS function you want to call
that's on the page you probably can. */
}
);

How can I store js output in php?

I want to store my javascript output in PHP. I mean, my js code is:
function loadCurrentUser () {
var url = APIPATH + 'load_current_user.php' ;
var result = $.ajax({
type : "GET" ,
url : url,
async : false
}). responseText ;
var resultJSON = processJSONResult(result);
}
What I want is to store the output I received (in json format) to my variable $json (in php). How can I do that?
based on the comments above it cannot be done as you think. But if you insist on getting response date to a php variable you will have to make another ajax call as ajax call occur at client side and php runs in your server not on the browser #briosheje had explained it nicely. may be what you need is session variable ($_SESSION['index']) to store your response data

Calling a php function with ajax

Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.

How to get URL variables from AJAX call in Javascript?

I am executing Javascript code from an AJAX call like this:
function loadViewViaAjax(url) {
Ext.Ajax.request({
url: url,
success: function(objServerResponse) {
var responseText = objServerResponse.responseText;
var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
while(scripts=scriptsFinder.exec(responseText)) {
eval(scripts[1]);
}
}
});
}
And I send parameters in the URL like this:
I get the values like this with PHP and Javascript:
alert('the URL from PHP: [<?php echo $_SERVER["REQUEST_URI"]; ?>]');
alert('the URL from javascript: [' + window.location.href + ']');
While PHP gives me the request URI so I have access to the URL variables (also via $_GET):
I cannot get the URL variables with Javascript by reading the window.location.href since it is the URL of the parent page instead of the AJAX call:
How with Javascript can I get the URL from the AJAX call instead of from the parent page?
This problem turned out to simply be a misunderstanding of scope: the javascript I am executing with eval has access to the variables in the main script so there is no need to pass values.

Categories