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>
Related
this is my first time writing an ajax below is my structure
submitted.php
<?php $a = $_POST['a']; // an input submitted from index.php ?>
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php echo $a; // will this work? ?>
ajax return blank... no error, my error_reporting is on.
No, there are a few things wrong with this:
You are posting a key - value pair where the key is key, so you would need $_POST['key'] in your php script;
You should use .preventDefault() if you need to prevent an event like a form submit that is caused by your button. If that is the case, you need to get the event variable from your event handler: $('button').on('click', function(event) {.If there is no event to prevent, you can simply remove that line;
If you do have a form (it seems so from your comment), you can easily send all key - value pairs using: data: $('form').serialize().
form.php
<button>bind to jquery ajax</button> <!-- ajax trigger -->
<span></span> <!-- return ajax result here -->
<script>
// NOTE: added event into function argument
$('button').on('click', function(event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function(msg) {
$('span').html(msg);
});
});
</script>
process.php
<?php
echo (isset($_POST['key'])) ? $_POST['key'] : 'No data provided.';
?>
This is the way to do it:
ubmitted.php
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
// no need to prevent default here (there's no default)
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php
if (isset($_POST['key'])
echo $_POST['key'];
else echo 'no data was sent.';
?>
This code, if click on text inside div class="example4DOMWindow" sends defined values to php and then get back php data and in popup window displays data received from php.
Here is example http://jsfiddle.net/rigaconnect/q3RcV/1/
This is ajax that sends and receives data
$(document).ready(function()
{
var one = $("#first_var").text();
var two = $("#second_var").text();
$.ajax({
type: "POST",
url: '__popup-window_ajax.php',
data: {var1: one, var2: two },
dataType: "json",
success: function(data) {
$('#load').html(data);
}
});
});
This part of code displays popup window (sample here http://swip.codylindley.com/DOMWindowDemo.html)
<body>
<div id="first_var" class="example4DOMWindow" style="width: 50px;">text one</div>
<div id="second_var" class="example4DOMWindow" style="width: 50px;">text two</div>
<script type="text/javascript">
$('.example4DOMWindow').openDOMWindow({
eventType:'click',
windowSourceID:'#example4InlineContent',
});
</script>
<div id="example4InlineContent" style="display:none">
<div>
<div id="load"></div>
</div>
</div>
</body>
And this is php file code
$p_one = $_POST['var1'];
$p_two = $_POST['var2'];
$test = $p_one. '<br>test<br>'. $p_two;
echo json_encode($test);
The code sends to php only var that is defined. Like var one = $("#first_var").text(); So if no var inside ajax code, nothing send. And sends all vars.
Necessary the code to send to php only clicked text. User clicks on text one, sends text one and do not send text two; clicks on text two, sends only text two.
Here https://stackoverflow.com/a/17622947/2360831 / http://jsfiddle.net/aGWGn/5/
clicked text is passed as value to javascript.
Tried to put all together like this
$(document).ready(function(){
document.body.onmousedown = whichElement;
var output = document.getElementById("load")
function whichElement(e) {
e = e || window.event;
var targ = e.target || e.srcElement;
if (targ.nodeType===3) {// defeat Safari bug
targ = targ.parentNode;
}
output.innerHTML = targ.innerHTML;
}
//var one = $("#first_var").text();
var one = targ;
var two = $("#second_var").text();
$.ajax({
type: "POST",
url: '__popup-window_ajax.php',
data: {var1: one, var2: two },
dataType: "json",
success: function(data) {
$('#load').html(data);
}
});
});
But the code does not pass var one = targ; to php file (var two also does not pass).
From my understanding the main question is how to pass var targ or var output(?) to var one....
Please, advice what is incorrect
Update
Changed data to data: {var1: output, var2: two },
and in popup window see
[object HTMLDivElement]
test
text two
text two
Changed to var one = targ.innerHTML; but does not work....
Changes to get to work
Changed var output = document.getElementById("load") to var output = document.getElementById("load1")
In html added <div id="load1"></div>
And changed
//var one = $("#first_var").text();
var one = targ;
var two = $("#second_var").text();
to var one = $("#load1").text();
Now seems work. But think the code need improvements
From what I understand, you need to pass only the clicked text to php, right?
If so, you don't need all that code from the moment you are using jquery. You just need to attach a 'click' event handler to .example4DOMWindow and send only the text of the clicked div.
index.html:
<body>
<!--
<script src="jquery-2.0.3.js"></script>
<script src="jquery.DOMWindow.js"></script>
-->
<div id="first_var" class="example4DOMWindow">text one</div>
<div id="second_var" class="example4DOMWindow">text two</div>
<div id="example4InlineContent" style="display:none">
<div id="load"></div>
</div>
<script>
$(document).ready(function() {
$('.example4DOMWindow').openDOMWindow({
eventType:'click',
windowSourceID:'#example4InlineContent',
});
$(".example4DOMWindow").on('click', function(event){
$.ajax({
type: 'POST',
url: '__popup-window_ajax.php',
data: { 'clickedText' : $(this).text() },
success: function(data) {
$('#load').html(data);
}
});
});
});
</script>
</body>
__popup-window_ajax.php:
<?php
$var = $_POST['clickedText'];
echo json_encode($var);
?>
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.
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
Can jquery.ajax post a value from an attribute Name? If can, I want send image's title apple to b.php, then return the data This is an apple from b.php to the div#result, Thanks.
a.php
<html>
<head>
</head>
<script src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function () {
var params = "value=" + $('#send').attr(title);
$.ajax({
url:'b.php',
type:'post',
dataType:'html',
data:params,
success:data
});
function data (html) {
$("#result").html(html);
}
});
</script>
<body>
<div id="result"></div>
<img id="send" src="apple.jpg" title="apple" />
</body>
</html>
b.php
<?php
echo 'This is an '.$_REQUEST['value'].'.';
?>
If you put quotes around the attribute name, .attr('title'), it should work. Otherwise, title will be treated as variable, and, as it is not defined, it will have the value undefined.
But better is to pass an object to data and let jQuery take care of proper encoding:
$.ajax({
url:'b.php',
type:'post',
dataType:'text', // actually, you are not outputting HTML
data: {value: $('#send').attr('title')},
success:data
});
You don't set the 'values' parameter in the same way you set a normal variable in this application. Instead you could create an object with a member called "value" and set that equal to your image title.
var params = new Object();
params.value = $('#send').attr('title');
Or you could create params as a literal like:
var params = {value: $('#send').attr('title')};