I'm looking for some guidance on how if I have an already existing php variable, that is not a web element, just a string, how can I pass that as a variable to ajax?
here is a santized snippet of what I'm doing.
I want to be able to pass $my_php_var to ajax.
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
var my_php_var = $my_php_var;
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:my_php_var},
dataType:"text",
success:function(data);
{
alert(data);
}
})
What you can do is, print it there inside another PHP tag:
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:<?=$my_php_var?>},
dataType:"text",
success:function(data);
{
alert(data);
}
})
Where <?=$var?> is short version of <?php echo $var; ?>.
Related
Simply i want to pass Numeric id to Php page and Using $_POST['id'] i want use it, But Getting Undefined error. check screen shot https://imgur.com/a/M1v4mEX and check code below
===>edit.php
$('#update').click(function(){
var serialData = new FormData($("#regForm")[0]),
s = location.search.split('='),
searchId = s[s.length-1];
console.log(serialData);
console.log(searchId);
serialData.append('id',9);
$.ajax({
method:'POST',
url:'update.php',
dataType:'json',
data: {id:9},
success:function(jsonObj){
console.log(jsonObj);
}
});
});
==>update.php
<?php
if(isset($_POST['submit'])){
var_dump($_POST['id']);
exit();
}
?>
You forgot to change the id value to send in parameter to the dynamic value from the location.search
Also think about adding e.preventDefault(); because you work on form submission.
I think that serialData can be removed cause it doesn't have affect the current code logic
Here is the working script
<script>
$('#update').click(function(e) {
e.preventDefault();
var s = location.search.split('=');
var searchId = s[s.length-1];
// Verify the current ID passed on search parameter
console.log(searchId);
$.ajax({
method:'POST',
url:'update.php',
dataType:'json',
data: { 'id': searchId },
success:function(jsonObj){
console.log(jsonObj);
}
});
});
</script>
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.';
?>
I want to update my session variables on textbox's onchange event, without page reload
How to do that.?? thanks!
You must use ajax for it, on on change event of textbox like,
$('textbox').on('change',function(){
$.ajax({
url:'yoururl.php',
data:{data},
success:function(){
alert('success');
}
});
});
I would use on blur, that way it wont set the variable everytime the user types, only when he clicks somewhere else....
$('textbox').blur(function(){
var thevalue = $(this).val();
$.ajax({
url:'yoururl.php',
type: "post",
data:{"value":thevalue},
dataType:"html",
success:function(data){
console.log(data);
}
});
});
THen in your php...
<?php
$_SESSION['yoursessionkey'] = $_POST['value'];
echo "success";
?>
It can be done by combination of javascript and PHP.
Make a function() and insert PHP code in it.
Pass the current argument as in session variable in javascript function..
<script type="text/javascript" language="JavaScript">
$(document).ready(function(){
$("#field").change(function(){
$.ajax({
url: "http://yourserver.com/ajax.php",
data: { value: $("#field").val() }
});
});
});
</script>
...
<input type="text" id="field" />
And in ajax.php:
<?php
$_SESSION['var'] = $_GET['value'];
?>
How can I load my php on my domain using my javascript that was loaded dynamically.
my sample code
sample.html(Client-side)
<div onClick = "getThis()"></div>
my.js(Client-side)
function getThis(){
var url = "http://www.sampledomain.com/test.js"
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
}
test.js(Server-side)
$.get("index.php", function(data) {
alert(data);
});
index.php(Server-side)
<?php
$_SESSION['user'] = "rob098";
?>
<script>
var data = '<?php echo json_encode($_SESSION['user']) ?>';
</script>
but it doesn't alert any.
Use ajax and json:
sample.html
<div onClick = "getThis()"></div>
my.js (inside sample.html)
function getThis() {
$.ajax({
url: '/test.php',
dataType: 'json',
success: function(data){
alert(data.user); //should alert rob098
},
});
}
test.php
header('Content-type: application/json');
echo json_encode(array("user" => "rob098"));
you have to append your js file to this
$(document).ready(function(){
$.get("index.php", function(data) {
alert(data);
});
});
so when script file loaded it will execute code inside jQuery ready function
I think you are using jquery $.get() the wrong way. Well I've never seen used that way at least, so you need to change your index.php to this:
<?php
$_SESSION['user'] = "rob098";
echo json_encode($_SESSION['user']);
header('Content-type: application/json');
?>
Let me know if I helped.
So I have this:
<?php
echo '
<script>
$(function(){
$("a#yeah").click(function(){
$.ajax({
url: "ajax.php?action=yeah&id='.$id.'",
success: function(html){
$("a#yeah").html("your cool")
}
})
})
})</script>';
?>
basically I am using the PHP variable $id which can be find in the document, how could I get this same variable but without echoing the jQuery(so I could keep my editor syntax highlight in the JavaScript part)?
never echo any client side code - just type it as is.
PHP especially good in this http://www.php.net/manual/en/language.basic-syntax.phpmode.php
<script>
$(function(){
$("a#yeah").click(function(){
$.ajax({
url: "ajax.php?action=yeah&id=<?php echo $id?>",
success: function(html){
$("a#yeah").html("your cool")
}
})
})
})</script>
You can add the php inline like:
<script> var yourVariable = '<?php echo $phpVar; ?>'; </script>
Just echo around the variable, as that appears to be the only piece requiring processing:
...stuff...
url: "ajax.php?action=yeah&id=<?=$id?>",
...more stuff...
If your server doesn't have short_open_tag enabled, then <?php echo $id; ?>