jquery ajax and php wont cooperate - php

i followed this tutorial and also the official one about jquery using ajax and php and had no luck whatsoever. If I use an xml file instead of a php file for pulling data with jquery everything works splendidly.
(All this on a LAMP server, php works for sure(running joomla with the same configuration))

This is standard ajax usage
$.ajax({
url : url
success : function(data) { //do stuff with data here }
})
Decide what kind of data you are passing and what is returned from ajax.

Related

Sending data from database using Jquery Ajax JSON

I restarted my old project and have a question regarding old code. 3 years ago I had this type of code to sent data from database to JavaScript arrays using php:
echo json_encode($result_array);
and JQuery:
$.ajax({
type : "POST",
url : "poli.php",
success : function(data) {
poli_owner = $.parseJSON(data);
},
async : false
});
to populate JavaScript array.
My question is - is it still good code or not recommended anymore. If the code is not OK what code is better to use to take data from database and populate JavaScript array using php and JQuery? Thank you.
Yes, it is still good. All the web is still using Ajax and JSON.
Depending on your use case, you can load your data via a separate Ajax request, or just make your server-side language generate data for JS and include it in the page source code.

Execute php from javascript

I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.

Replace an API call using $.ajax() and JSONP with a server-to-server API call

I have a javascript application calling an ajax function that looks like this
$.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) {
if (data.ok) {
//do things
}}});
the ajax url im trying to access is through etsyapi
everything works fine and dandy until i try to access the application in chrome with adblock on. it makes the ajax call fail completely, returns an error with a Failed to load resource-"theActualURL" message.
I couldn't figure out how to get past this in javascript and was told that i need to do a php call to get this working.
Unfortunately, i dont know the first thing about php- ive tried to understand even the basic structure for it, and i havent been able to find any work arounds in javascript, so i think it has to be done with php.
Is there simplest way to call the ajax function in php with a dynamic url(which is passed to the php page from javascript) and have it pass the array back to javascript to maniuplate?
ive gotten this far with the php-
<?php
$json = array();
????????????????????????
$jsonstring = json_encode($json);
echo $jsonstring;
?>
but dont understand how to access a dynamic url from javascript.
If it's genuinely using jsonp you shouldn't need php. Replace your $.ajax... with:
var newScript = document.createElement('script');
newScript.src = apiURL;
document.head.appendChild(newScript);
Ignore the above, I'm out of date with jQuery. Even so, you shouldn't need php if the API endpoint is really responding with jsonp. It sounds like the url was wrong/bad if you're getting an error. Have you tried simply opening apiURL by putting it in your browser's address bar?
jsonp is a work around for cross domain ajax restrictions that wraps the returned data in a javascript function call. This allows you to load it in a script tag and the function is run with the data as a parameter when the script is executed.

Jquery toolbar help: accessing external php script

Hi i'm currently working on a toolbar and have run into a problem. I have two files, the toolbar and a PHP script. The PHP script simply pulls an array of titles out of a database. What I am trying to do is get the toolbar to call this script and return this array, and then use this array to create a drop down menu with the titles as the options.
I'm assuming I need to use Ajax in some form but have no idea how to achieve this.
Many Thanks.
UPDATE: I am having problems getting .getJSON work cross browser because of the same site policy. The problem is the javascript file making the call produces a toolbar which is appended to a remote site, this toolbar is supposed to call a php script back on my own server to get data from a db.
How can I get around this issue?
Yes. If you want to have PHP and Javascript working together the answer is: JSON. You will have to JSON encode your array in php. Use Javascript Ajax to call the PHP file and then parseJSON the response. Then you have your array in use in Javascript. After that you can render it in Javascript and just attach the result to the element you want.
There are plenty of examples in jQuery documents. If you are unfamiliar with ajax, read the documentation: http://api.jquery.com/jQuery.ajax/ In the end there are simple examples. You can also use .getJSON.
jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] )
- url A string containing the URL to which the request is sent.
- data A map or string that is sent to the server with the request.
- success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds.
Basically:
$.getJSON("url of the php file",
data to send to the php file if any,
function(data) {
console.log(data);
}
});
Inside that function where is the console.log you can do anything you want with your data.

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

Categories