How to get URL variables from AJAX call in Javascript? - 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.

Related

how do i give path to the controller action while ajax call from .js file

function sendData(types,data){
var datas={types:types,data:data};
console.log(datas);
$.post({
url:'../../controllers/news/ajax',
data:datas,
success:function(response){
console.log(response)
}
});
}
this is my new.js file and need to do ajax call to action of newController.php file.
You need to find workaround as below
.js files are not parsed by asp.net mvc view engine, you cannot use any server side (c#) code in there. You can use custom-data-attributes to workaround this. create one <div> make it display:none and on set multiple URLs in different different data-attributes for all ajax call of your page. (like save,delete,load etc.)
<div id="allUrls" style='display:none' data-url-save="#Url.Action("SaveAction", "Controller")"
data-url-delete="#Url.Action("DeleteAction", "Controller")" ></div>
and after that in New.js file in ajax call you can access this div and get url as below
var url = $("#allUrls").data('request-url-save');
alert(url); // set this url in your AJAX call
Thanks
you have to give full path in ajax like this
var datas={types:types,data:data};
console.log(datas);
var url = '<?php echo base_url();?>';
$.post({
url:url+'/news/ajax',
data:datas,
success:function(response){
console.log(response)
}
});
you can use base url function for that

Call PHP Method with Ajax [duplicate]

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()

call regular asp from javascript in other domain

I have used dojo/dom from a javascript file before to call a php file on another domain that handles some database queries and returns the result to the javascript file.
The call to the php file was (i offcourse hope i can use the same call to asp)
postdata = dojo.toJson({ action: "get", userid: 1 });
require(["dojo/_base/xhr", "dojo/dom", "dojo/domReady!"],
function (xhr, dom) {
var xhrArgs = {
url: "http://otherdomain.com/file.php",
postData: postdata,
handleAs: "text",
load: function (result) { }
};
var deferred = dojo.xhrPost(xhrArgs);
In the php file i had
$foo = file_get_contents("php://input");
$postvalue = json_decode($foo, true);
to read the values from the dom call.
The reason i need to do this is because i get an error from the browser about a security risk because of the cross domain request.
So i think i need to use Jsonp
How do I write the php code in asp? NOT asp.net
Since your post data is JSON, the Request.Form won't be filled in, so you will have to use Request.BinaryRead and convert this result as a string.
See here to convert this JSON string into an object.

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.

Categories