can i use PhoneGap Jquery to make ajax calls?
You certainly can use jQuery Ajax functions in your PhoneGap applications. Here is a demo:
-- JavaScript in App --
$('#some_page_id').bind('pageshow', function () {
$.get('http://domain.com/path/to/script.php?get_param=value', function (data) {
$(this).find('div[data-role="content"]').append(data);
});
});
-- PHP on Server --
if (isset($_GET['get_param']) && $_GET['get_param'] == 'value') {
$query = mysql_query("SELECT * FROM some_table WHERE some_col='something'", $db_handle);
if (mysql_affected_rows() > 0) {
while ($row = mysql_fetch_assoc($query)) {
echo "<div>" . $row['some_other_col'] . "</div>";
}
} else {
echo "No Data Found";
}
}
The above example will query the PHP script on the server every time the '#some_page_id' page is shown and append the data grabbed to the <div data-role="content">
tag. You can also use .html(data)
instead of .append(data)
to replace the HTML rather than add to it.
UPDATE
I found this in the jQuery Mobile documentation which gives some excellent information about making $.ajax()
calls in PhoneGap apps: http://jquerymobile.com/demos/1.0/docs/pages/phonegap.html
Kalaji
Updated on June 12, 2022Comments
-
Kalaji almost 2 years
can i use JQuery ajax calls in PHONEGAP to run a php file that gets records from a database ?! or shall i use Javascript Ajax ? what's the best way to achieve that in PHONEGAP ?
-
Toby D almost 11 yearsthis also works for me. However, have you ever tried to build a phone gap app that requires user login function?
-
Jasper almost 11 years@MyticMoon I don't have any experience with user logins inside of an app. Off the top of my head I think I'd want to manage the user session timeout on the app. side rather than the server side so that user's can't just turn-off the device's antenna to retain access. Do you have any specific questions?
-
code4jhon about 10 years@Jasper is JQuery using JSONP technique for achieving this? Doesn't Same Origin Policy apply to mobile apps ? I want to understand what makes possible an AjaxRequest from no domain to www.mydomain.com
-
Jasper about 10 years@code4jhon Look into
Access-Control-Allow-Origin
headers. Basically in your server-side response you add a header that tells the browser its OK to read the data as long as the domain the browser is using is white-listed. Also, JSONP will require using a JSON format, which is good, it's just different than my example above that returns HTML. The above example was for an application that had the same domain as the website, so no issues were had. -
Tolga Ozses over 8 yearsSame Origin Policy doesn't apply to mobile apps, but I only allow fiddle.jshell.net for testing purposes.