0

I want to call a php function from Ajax and have the contents returned to the webpage.

Say I have a file called latest.php that returns some very simple html.

$result = "<div> text </div>";
echo $result;

how can I write an Ajax script that calls this php file, returns the html and stores it in a javascript variable?

1
  • What did you try? Are you getting stuck anywhere? Commented Apr 9, 2013 at 4:28

2 Answers 2

1

Javascript variable:

var myVar;
$.get("latest.php", function(data) {
    myVar = data;
});

Insert into document:

$.get("latest.php", function(data) {
    $("#myElement").html(data);
});

or

$("#myElement").load("latest.php");
Sign up to request clarification or add additional context in comments.

4 Comments

What are the security implications and efficiency differences with $("#myElement").load("latest.php"); vs. $.get("latest.php", function(data) ?
There are no differences between get and load in this context. Both are just helper functions and call ajax internally. In terms of security, it is you who have to make sure that data provided by latest.php is save and doesn't reveal sensitive information.
it most certainly contains sensitive info in the code; it connects to a mysql database and returns the contents of a query. Is there an standard way of making sure that no one can see the code of the php file as it is requested via ajax?
No, there is no standard. Generally speaking, no one will be able to access your PHP files as long as your web server is configured properly. But this discussion is beyond the scope of the question.
1

the simple way, is using jQuery.load() or jQuery.ajax()

or, use the old school method using XMLHttpRequest

2 Comments

I went with jQuery.load() and it seems to work just fine, but if I had database credentials inside of update.php, would they be secure in comparison to other solutions?
secure or not, it's depend on what algorithm do you use. I think if you only pass the public data and compare the database credential in your update.php, it will be more secure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.