communication between PHP and Javascript - php

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.

Related

Load PHP page in Cordova phonegap with using AJAX

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.

Ajax request JQuery Sending div

I have an ajax request to save my mail template in the database.
However I can't send my div with the ajax request ? I've been looking on the internet for 2 hours now but I couldn't find a solution
the ajax file :
function saveEmail(){
var mail3 = $jQ('templateContent');
$jQ.ajax({
method: 'POST',
url: 'ajax/saveMail.php',
data: {mail2: mail3.html(), test: "test"}
}).done(function( data ) {
console.log(data);
});
}
saveMail.php :
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit();
The only POST value i get is test example:
<pre>Array
(
[test] => test
)
</pre>
some usefull info :
mail3 = `[prevObject: jQuery.fn.jQuery.init[1], context: document, selector: "templateContent", jquery: "1.10.2", constructor: function…]`
var mail3 = $jQ('templateContent');
Should be something like
$jQ('.templateContent'); or $jQ('#templateContent');
You forget to use templateContent as a element class or id
Try to use .templateContent or #templateContent.
So you can get content of element by using it's id or class.
The following gives the div's contents in the ajax data call. Note the jquery selector for the div i.e. var dataToSend = $("#templateContent").text();
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function myFunction() {
var dataToSend = $("#templateContent").text();
alert(dataToSend);
$.ajax({
method: 'POST',
url: 'ajax/saveMail.php',
data: {mail2: dataToSend, test: "test"}
}).done(function( data ) {
console.log(data);
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<div id="templateContent"><span><p>This is supposed to be sent in email!</P><span></div>
</body>
</html>

how to send json object in ajax to a php page

I am trying to send a json object to a php page demo.php using an ajax request
<script type="text/javascript" charset="utf-8">
$(document).ready(function ()
{
var data =
{'name':'Sam','ID':'1345'};
var test = {}
test["data"] = JSON.stringify(data);
$("#btnsend").click(function()
{
$.ajax({
type:"POST",
url:"/demo.php",
dataType:'json',
data:test,
success: function(data)
{
console.log('success');
}
error: function()
{
console.log('failure');
}
});
});
});
</script>
This is what I tried in jQuery,but it is not rendered on my php page.In php I tried the following:
<html>
<?php
$json = json_decode(stripslashes($_POST['data']), true);
echo var_dump($json);
?>
<body>
Hello World !!!
</body>
</html>
But it is printing a failure in console. Please help me with this.
Edit: My initial answer was wrong, the reason you get to the error function, is that you have specified:
dataType:'json',
So jQuery expects the output of your php script to be valid json. It is not, you are returning text / html so that is why your success function is never reached.
The way you have setup your php script (outputting html), you probably should just remove:
dataType:'json',
and then you will get to your success function.
By the way, nothing is rendered on your page until you do something (show...) the data variable in your success function:
success: function(data) {
console.log('success');
$('#some_element').html(data); // to put the output in #some_element
}
And in your php script you should only send back / echo out what you want to display in your html element, so no html or body tags.

Passing variable from jquery to php

i want to pass a variable from jquery to php but my code doesnt work .I tried very hard but no luck . When i click the button nothing happens.plz help thank you
one more thing i tried this without passing variable and i use only echo command then it works but when i pass variable nothing happens
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("button").click(function(){
var var_data = 5;
$.ajax({
url: "myscript.php",
data: { var_php_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
myscript.php contains the following code
<?php
echo $_GET['var_php_data'];
?>
Try wrapping your script in a document ready handler. Also you have a trailing comma (,) after the success callback that you should remove. Also you should use a , instead of ; after the data parameter. Specifying the HTTP verb for your AJAX request might also be useful:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
var var_data = 5;
$.ajax({
url: 'myscript.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
The reason you need to wrap your click registration in a document ready handler is because you put your script inside the <head> section of your markup and the button hasn't yet been loaded by the browser when you attempt to subscribe to its click handler.
You can install Firebug (Firexox plugin), or user something similar for your browser to see real HTTP request and response. If you will post them here it will be more simple to find the problem.
Track request in FireBug. You can find by FB did request success (200) as well as date send by request.
Also, try http://{your_host}>/myscript.php?var_PHP_data=echoText
Addition:
Darin Dimitrov described the problem right way

jquery.ajax post get issue

I am new to studying jquery.ajax. Through some tutorials, I tried some code by myself, but I met some trouble. So I ask for help.
I tried to do this: open a.php, send html data from div#send to b.php, then return the data and show in div#result.
a.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function () {
var params = "value=" + $('#send').text();
$.ajax({
url:'b.php',
type:'post',
dataType:'html',
data:params,
success:data
});
function data (html) {
var str=html.send;
alert(html);
$("#result").html(str);
}
});
</script>
<body>
<div id="result"></div>// I need return 'this is an apple.'
<div id="send">apple</div>
b.php
<?php
echo 'This is an '.$_REQUEST['value'].'.';
?>
You are not sending any valid parameters with the ajax request. If you want the textual contents of #send you need to use:
$('#send').text();
Although that only gives you a string, so it would have to be:
var params = "value=" + $('#send').text();
Apart from that, $_REQUEST is an array, so you have to use something like $_REQUEST['value']
A third point is that your success function is too complicated and wrong (html.send does not exist), it could just be:
success: function(msg){
$("#result").html(msg);
}
To return datas from b.php, you have to do an echo

Categories