Load PHP page in Cordova phonegap with using AJAX - php

I want to show my php page in android mobile app. I use cordova and i added a php page in my project with this directory "php/load.php". I tried to show this page on index.html i tried like this but it doesn't work.
<button type="submit" onclick="show();">Show it</button>
<script type="text/javascript">
$(document).ready(function() {
function show(){
$.ajax({
method: 'GET',
url: 'php/load.php',
dataType: 'text'
})
.done(function(data) {
alert(data);
})
alert("Pause");
}
});
});
</script>
And this is my php file:
<?php
$a = "AAAAAAAA";
echo $a ;
?>

You've got syntax errors in your JavaScript that's likely causing most of the problem. Have a look at this and give it a try.
<script>
$(function() {
$("#btn_show").on("click", function() {
$.ajax({
method: 'GET',
url: 'php/load.php',
dataType: 'text'
}).done(function(data) {
alert(data);
});
});
});
</script>
<button type="submit" id="btn_show" >Show it</button>

Four important points:
Listen to the cordova deviceready event
Your url in your ajax request is not local and it can't be local because on your device is no server running. So it has to be something like: https://www.example.com/load.php
You have to whitelisten all your external sources.
You should use https.

I would suggest using json_encode function in php.
For example:
<?php
$a = "AAAAAAAA";
echo json_encode($a) ;
?>
this would return a json array object which you can use to be rendered by javascript then put on to those html element.
changing the url for ajax For example: "url:localhost/website/load.php" i think it must be done too for ajax to work properly.

Related

How to access AJAX file from different folder in CodeIgniter

I have one form with Jquery validation which is working perfectly, Even AJAX is also working perfectly if I use my validation code with AJAX on the same page.
Now What I did, I create a file called as validation.js and I added my validation code with AJAX in it and I added a script like below in my view page.
<script type="text/javascript" src="<?php echo base_url() ?>js/validation.js"></script>
Then I clicked on submit button It's checked my validation even it also goes to AJAX URL which I entered but this time I haven't got output.
I am getting in Network tab in the browser my URL like this
<?php echo base_url("index.php/user_control/admin_submit_from"); ?>
I am using sublime text editor If I used above URL on the same page then the base_url color is showing in blue and If I used in validaion.js the color is showing in yellow.
Above URL Is not working from the validation.js file. Would you help me in this?
My Jquery validation with AJAX
$(document).ready(function() {
$("form[name='admin_form_submit']").validate({
rules: {
firstname: {
required: true,
minlength:3,
maxlength:50
},
lastname: {
required: true,
minlength:3,
maxlength:50
},
role:{
required: true
},
inst_name:{
required: true
}
},
submitHandler: function(form) {
//// form.submit();
$.ajax({
type: 'post',
url: '<?php echo base_url("index.php/user_control/admin_submit_from"); ?>',
data: $('form[name="admin_form_submit"]').serialize(),
success: function (data) {
alert(data);
}
});
}
})
});
The reason why the code worked in the first method was because it was included within a PHP file. Within a php file, you can embed HTML, CSS, JS, and that's why when you write something like this:
<script src='<?php echo $something; ?>'></script>
the value of that $something is echoed.
On the other hand, you cannot embed a php code inside a javascript file. The entire code will be treated as a string, and the reason why it is parsed that way.
So to solve you issue (if you still want to put your js in a separate file), one of the ways to do that is to add a hidden input with your desired value, in your form, and use js to get it.
In your form:
<input type="hidden" name="my_url" id="my_url" value="<?php echo base_url("index.php/user_control/admin_submit_from"); ?>">
Then you target it from your js file like so:
var myUrl = $('#my_url').val();
then update your ajax to:
$.ajax({
// other objects and properties
url: myUrl,
});
you can't execute php in a js file
create a global js variable in your php file with the url and reference that in your js file
index.php
<script>
var url = '<?php echo base_url("index.php/user_control/admin_submit_from"); ?>';
</script>
validation.js
$.ajax({
type: 'post',
url: url,
data: $('form[name="admin_form_submit"]').serialize(),
success: function (data) {
alert(data);
}
});
}

communication between PHP and Javascript

I want to send some data to Javascript from PHP.(these two file is different file in same folder)
For example, If I calculate some value in PHP side, I want to send the data to javascript and I use the data.
How can I do this??
There's complete technology for that called AJAX with a lot of tutorials on the internet.
And there's already a great and easy-to-deploy implementation - within jQuery.
In practice, you can use this:
FILE: index.php
<HTML>
<body>
<input type="text" id="test" value="123"><br>
<input type="button" id="btn" onclick="send_to_php()" value="send to php">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
function send_to_php() {
$.ajax({
url: 'js_php.php',
type: 'POST',
// Form data
data: function(){
var data = new FormData();
data.append('test', $("#test").val() );
return data;
}(),
success: function (data) {
var obj = JSON.parse(data);
$("#test").val( obj.result );
},
error: function (data) {
console.log(data);
},
complete: function () {
},
cache: false,
contentType: false,
processData: false
});
}
</script>
</body>
</HTML>
FILE: js_php.php
<?php
//FILE: js_php.php
$test = $_POST["test"];
$test .= "456";
$arrResult = array(
'result' => $test
);
print json_encode($arrResult);
die();
?>
The file "index.php" is the communication between JavaScript and PHP using jQuery Ajax method.
When click the "send to php" button will run the "send_to_php ()" that will take the value of the input id "test" and send through ajax, for "js_php.php" file.
In turn, the file "js_php.php" will receive this variable as POST, modify and print the value in JSON format.
The method implemented by ajax function "send_to_php ()" will be "listening" all that "js_php.php" print.
After the success of the return, javascript convert the text "js_php.php" printed on a JSON object and then the JS able to process within the javascript code:
success: function (data) {
var obj = JSON.parse (data);
$("# test").val(obj.result);
},
<script type='text/javascript'>
var myVar = <?php echo $myVar; ?>;
</script>
in a nutshell. There are more sophisticated way to communicates though.
Have a Look at this AJAX Tutorial: http://news.php.net/php.general/219164
Assign a JavaScript global variable in a script tag in the PHP page, and include the other javascript files after.
Sample:
<html>
<head>
<script type='text/javascript'>var testGlobal = <?php echo $globalJSValue ?></script>
<script type='text/javascript' src="url"></script>
<script type='text/javascript' src ="url"></script>
</head>
</html>
testGlobal variable will now be available to both javascript files.

Get div content with jQuery for PHP

UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.

bit.ly API use issues (shorten, lookup, and clicks)

as part of my time isn't dedicated to PHP dev, I'm having an issue which is probably easy to solve, but having absolutely no logs (PHP logs, browser firebug logs...) I'm pretty stuck.
Here's my code; as I'm testing stuff, it's pretty raw.
The index.php file :
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.4.2).
google.load("jquery", "1.4.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
$("#shrelock").submit(function(){
var url = $(this).attr('action');
$.ajax({
url: url,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
<form id="shrelock" action='stats.php' method='get'>
<input type="text" name="url"/>
</form>
Now the stats.php file :
include("bitly.php");
if ( isset($_POST["url"]) ){
$urlToCheck = $_POST["url"];
$bitly = new bitly('myLogin', 'myKey');
print $bitly->shorten($urlToCheck);
}
I'm not sure what your question is, but I do see a few problems with your code.
The ajax request you perform uses GET while the serverside code seems to expect a POST
and also you forgot to send the 'url' parameter in the ajax call.
$.ajax({
url: url,
type: 'POST',
data: 'url=' + $('#shrelock input[name="url"]').val(),
success: function(data) {
alert(data);
}
});

How load a PHP page in the same window in jQuery

I have a PHP file, Test.php, and it has two functions:
<?php
echo displayInfo();
echo displayDetails();
?>
JavaScript:
<html>
...
<script type="text/javascript">
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: function(data){
$("#response").html(data);
}
});
</script>
...
<div id="response">
</div>
</html>
It returns the response from jQuery. The response shows as <a href=Another.php?>Link</a>. When I click the Another.php link in test.php, it loads in another window. But I need it to load the same <div> </div> area without changing the content of test.php, since it has displayInfo(), displayDetails(). Or is it possible to load a PHP page inside <div> </div> elements?
How can I tackle this problem?
If I understand correctly, you'd like for the a link to cancel navigation, but fire the AJAX function?
In that case:
$("#mylink").click(function() {
$.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) {
$("#response").html(data);
});
return false;
});
Krof is correct,
One possible unwanted behavior of this however is that it will query the data every time the link is clicked. You can set the event to only call the ajax query once by using one.
$("#mylink").one('click', function() {
// ajax call
return false;
});
Don't forget to set href="javascript:{}" in your link so after the event is fired once the link wont do anything;
You could just use MooTools and class Request.HTML.

Categories