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
Related
I'm trying to implement a function that will do something based off of the response text given by a certain ajax call. But I can't access the response text field. Here is my code:
var response = $.getJSON('/add_participant',{
email : uemail,
password : upassword
})
and I've tried to access it this way:
response.responseText
But when I log it out to the console, it says it's undefined.
I think it has something to do with the ajax call needing to resolve first, before I access the response text. That's because if I save it to a global variable, when I pull up the webpage and use the inspection tools, I am able to access the responseText in that way.
How can I get that response text during my function? Is there a way I can have the script wait for it to resolve or whatever?
Thanks in advance!
Since this gets executed asynchronously, you need to handle it in .done callback. Here is the sample code.
var response = null; // assign to [] if you think you will receive an array
$.getJSON('/add_participant',{
email : uemail,
password : upassword
}).done(function (data) {
response = data;
console.log('response: ', data);
})
Hey I figured out what was wrong with my code, and it was actually a problem with the python code I was calling. I'm setting up my website with the Flask library in Python, and I was using the ajax call to use a python function in the back end and get the output it returned. The problem was that when I returned the output in the python function, I was returning a string, just like this:
return ("It worked!")
The rest of the function was still operating and doing the things I wanted it to do, and I could still check out the response when I used the inspection tools. But the returned value was in the incorrect format. It seems that this resulted in something along the lines of the Javascript code on the front end not getting the message from Python that the Python function had finished. And for that reason, nothing in the .done(function (data) { } ) block would get executed.
To fix this, I had to instead return a jsonified dictionary. jsonify is a function from the flask library. Here's how it should look:
return(jsonify({'result': 'It worked!'}))
And then if you want to access that data back in the javascript, access the result property of the data object inside the
.done(function (data) { } ) block. For me, it looked like this:
var response = $.getJSON('/add_participant',{
email : uemail,
password : upassword
}).done(function (data) {
if (data.result ='It Worked!'){
console.log("It worked!!");
// Do whatever else you wanted
}
else{
console.log("It didn't work.");
// Do something else
}
})
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()
Before the following URL gave a JSON output:
http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=Query
now it outputs the following:
window.google.ac.h(["Query",[["query",0],["query optimization",0],["query in access 2013",0],["query processing and optimization",0],["query optimization in dbms",0],["querying microsoft sql server 2012",0],["query in access 2010",0],["query letter",0],["querying microsoft sql server 2012 tutorial",0],["query access",0]],{"k":1,"q":"4-l7QUSZEiiQKaSq-yXfrtfHpd0"}])
Curious as to how i can parse this into JSON
That's JSONP.
If you were to call this using JSONP technique (adding <script> tag to your page with the src= attribute set to the URL) then you would need to declare the function window.google.ac.h before making the JSONP call to process the result.
If you were to call this using ajax or on the server then you have two options:
declare the funciton window.google.ac.h to process the result then eval the response. (Because, that's what adding a <script> tag does, it evals the javascript file in your page. So you're basically just emulating JSONP)
function window.google.ac.h (json) {
// process your response here
}
var s = document.createElement('script');
s.src = 'http://suggestqueries.google.com/complete/search?' +
'client=youtube&ds=yt&q=Query';
document.body.appendChild(s);
alternatively, if you receive the response via other means:
function window.google.ac.h (json) {
// process your response here
}
eval(response);
Remove the outer window.google.ac.h( .. and .. ) from the response then parse it as JSON.
var json = response.replace(/^.*?\(/,'').replace(/\)$/,'');
So I'm learning Ajax and I followed this tutorial: https://phpacademy.org/course/submitting-a-form-with-ajax to create a function that works for any form. This is the complete function:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
alert(url + ' ' + response);
}
})
return false;
});
As you see all I'm doing is alerting the response, which in this case is php echo. That's where my problem starts, I need a flexible and secure way to handle the javascript/php communication. Preferrably one function for all forms, maybe with if () statements instead of alert(url + ' ' + response); depending on the form url.
The function I need is not very complicated, based on the response I get I will just update the current form with errors.
Aslong as I know what to use in the communication I'm fine from there, echo '1'; as I have now doesn't feel like the ideal solution but it's all I could handle.
So, what type of response should I send from the php page, and where (in the javascript) and how is the best way to handle it? I've heard of json but having a hard time wrapping my head around it. Could someone show a json response sending a basic integer thats easy for my response to pick up as an int?
You can send back a simple JSON response via PHP and check it in your success callback. Make sure you're setting the type to json and in your AJAX call, and using json_encode on the PHP side:
$response = array('response' => 1);
echo json_encode($response);
Output should be:
{ 'response' : 1 }
I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).