Help with Ajax .... need some clarification - php

Can any one please explain this:
var js_var = 'hello';
$.ajax({
type: "POST",
url: "some.php",
data: "js_var="+js_var,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
I need to know what is returned by the PHP file in this case... The PHP file can be assumed to return whether jsvar exists in the db or not...

The PHP file will return whatever the result of processing the data params (js_var=hello) is. The output will be received by the client as a string (msg).

Your output from PHP script either with echo/print or even HTML is returned in the msg argument of success callback function.
For example, if you do this from PHP script:
echo 'hello world';
The msg will be equal to hello world

Assuming that this is in reference to PHP Javascript variable help then some.php can do whatever you need to do. The actual some.php was just a place holder for whatever script you needed run was named.
Instead of the output of that PHP file being sent and rendered in browser, it is sent and put into the msg variable. What you send back could be a block of HTML to be shoved into a div for rendering, a simple OK, or a JSON object, or XML. As you are writing the code on both ends of the communication, you can do whatever you want.
For example, if you were creating a user creation form, you could have a script, that after the user name box loses focus, goes and makes an AJAX call, then returns either OK or an error message, then you could display that next to the user name box.
EDIT:
As other people have mentioned, it would be best going through a few tutorials about jQuery and AJAX in general. A quick google turns up a few decent ones:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
http://www.ibm.com/developerworks/library/x-ajaxjquery.html
http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html
I've found that the IBM developerworks articles to be rather clear and concise time and again.

use firefox , firbug or ie fiddle to the see the output.
Firebug is really nice , there is a panel called net , open that and you can see the result from php.

Related

How to pass Javascript object to php to make sql query and return data as a downloaded csv file?

I use jquery to set a get query to a php script which then queries the database and writes to the screen, but I can't get it to trigger the download, even with headers.
The steps are as follows:
create a link that the user clicks to download the data
javascript sends the query parameters to php
php queries the database and writes the file
client downloads the file
But I can't get step 4 to happen.
Step 1: (this is a table object that also contains the parameters:
d3.select("#some-div").append('a")
.attr("href", "javascript: void(0)")
.on("click", function() { this.saveAsCSV() };
Step 2: Javascript file to make query:
var saveAsCSV = function(params) {
var tmp_params = $.extend({}, params);
tmp_params['State'] = "NM";
$.get('php/get_data.php', tmp_params);
}
php to return query:
...
header("Content-type: application/text-csv");
header("Content-Disposition: attachment; filename=query_result.csv");
while($row = $result->fetchArray() {
print "$row";
}
...
It works fine in that it correctly queries and will print the data in the javascript function (so it will print it to console.log if I add that into the get return function), but I can't figure out what I should do differently to make it just download it directly.
One thing I've tried is to do the following on the params object:
var param_string = encodeURIComponent(JSON.stringify(params));
location.href = 'http://www.mysite.com"+param_string;
But that both takes the user away from the page and fails to download the data.
EDIT: I should clarify that the php file does output the query well in csv format. The problem seems to be that using the $.get() function does not trigger a download regardless of the php headers. Maybe I need to just provide a simple link with the parameters in the URL address, but I'm not sure how to get a javascript object into a URL format so that the php script can interpret it.
You could open a popup/new window/tab/whatever with your URL php/get_data.php?State=NM (perhaps additional parameters). It should download the output.
But your output might be wrong because you just print the variable $row which is an array. If you try to print an array that way it will just show Array.
You will need to properly output your rows. Unfortunately I don't know the CSV structure well enough to help you with that problem.
You can make an AJAX call for this using something like jQuery and it will pop up the download box while keeping the user on the page. Do something like this:
$.ajax({data: {download: 'query_result.csv'}, type: 'GET', url: 'download.php', cache: false });
I've tried this a few times for a previous employer and it always worked great. Although I did it mostly with .zip and .docx files.
I figured it out!
Basically, my encoding was wrong. I don't want to encode with
encodeURIComponent(JSON.stringify(params));
The result isn't readable by the php script. However, it works to just use $.param().
To summarize, the download is triggered by creating the URL link and then using location.href to link to it. Hence everything else is the same, but instead of the $.get() in step 2, I do:
var url_params = $.param(tmp_params);
location.href = url_params;
Which generates the download. Thanks!

Ajax call to a php file returning JS code in that file instead of executing it

I am making an ajax call to a php file, But I dont want it to return anything.
My php file has HTML content or rather a JS code, which needs to be executed over there itself. Please help me with this. I dont Know why this is happening
This is my ajax code:
$.ajax({
type : "POST",
url : "<?php echo CALLBACKURL; ?>mobile_profile.php",
data : data,
success: function(response){
}
});
I am not giving any console.log but syill in the response its giving the whole of html
code.
I need to execute that js code there itself and I dont want anything as response Or if we cant do this atleast can i run the JS code return nothing
Where do you want your code to execute? In the browser or at the server?
If you do not want it to contact server and run there itself(inside browser), why are you using AJAX? You simply call a function which will do whatever you want.
on success what do you expect it to do? There is nothing inside the braces...
success: function(response){
}
Browsers cannot process php code. they can process only html and javascripts and some third party scripts with the help of add-ons.
Kindly be clear what you are expecting.
url: "<?php echo CALLBACKURL; ?>mobile_profile.php"
replace it with:
url: "mobile_profile.php"
and put those php tags inside that mobile_profile.php, if required.
If you wish, you can pass parameters to that php file by suffixing your? and a querystring so that the called php file understands what to do.
I think this helps.

Calling a php function using ajax/javascript

Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link

Why I can't write Javascript code inside Ajax reponse text?

the reponseText should be like this on PHP
echo "<script>alert('test')</script>";
But nothing happen. How do I return Javascript code?
An ajax call is up to the caller to decide what to do with it (depending upon what type of data is returned). In this case, if your caller isn't prepared to execute this, then nothing will happen with it. Depending upon what the real code wants to do here, there are a number of different possibilities for handling the returned result from the ajax call.It could be formatted as JSONP so it calls a function in your main page code to process the returned data. You could return full JS (without the tags) and do an eval() on it after the host page (generally not considered a wise idea due to some security risks) or it could be just added to the current page and let the browser just parse whatever you put in there.Usually, an Ajax call returns pure data and your host page code processes that data and holds the code for deciding what to do with it. This is the safest mechanism because there's no way for anything that hijaacked a connection to inject code into your page (all it can do is change the data).
You've returned it as text. Now all you need to do is insert that text onto the page somehow:
document.body.innerHTML += response;
There's a lot going on, and a lot of assumptions made, but that's the simplest way to do it.
(Well, that's not entirely true. The easiest way to do it would be to just return the JavaScript, and then eval it.)
here's a simple example. But don't include the <script> tags for this tough
$.ajax({
type: "GET",
dataType: "text",
url: "jsLoader.php",
success: function(data){
eval(data);
}
});

How to use jQuery's ajax function?

How can I use the $.ajax() function to display output in real time. Right now I am using it in this context:
$.ajax({
type: 'get',
url: 'process.php',
data: 'foo=boo',
success: function(output) {
$('div#results').html(output);
}
});
The above displays the output recived from the PHP script only AFTER the script has fully executed. So if in the php script you had the following:
echo 'Hello for the first time';
// some code
echo 'Hello again';
// some code
echo 'Are you still here?';
The output would be all those echos all at one. Instead, is there any way I can update the output received from the PHP script one after another as the requests are being fulfilled by PHP in real time?
I know how to update things in real time when working entirely in the realm of JavaScript, for example: checking if the input being typed is at least 10 characters long using the keyup() event as a trigger to check after every entered key and displaying a message to enter something more which disappears as soon as the 10th character is typed.
But how to do something like this when the output is coming from a PHP file? is it even possible?
Reason why I need to do this is because I would like to have a status screen that shows how much progress has been made and what part of a task the script is currently handling, like how desktop apps have.
It is not possible. You should split this task in to parts - one is long running task that updates it's status in database, and other task that just fetches status from database and displays progress to users.
Umm, nope. Thats not possible. The best you can do is, Try breaking down your php file and calling multiple ajax requests for each of those files.

Categories