I am having a problem with my code as my php variable is not being echoed on page when using ajax jquery. Here is my code...
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function() {
jQuery("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
i am trying to send "username" to page url "load.php"... i called it this way but nothing is being echoed...
if(isset($_POST['user'])) {
echo $_POST['user'];
}
pls help out thanks... :)
edited...
when i tried using this code i.e adding passing response as parameter in success function like this ...
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function() {
jQuery("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
.... the data (username) gets displayed every second.. like a blink toggling on and off the page... how do i make the data display static in order to use the variable on the ajax page. Thanks :)
Where the response variable you get? Should be :
success : function( response ) {
jQuery("#load_msgs").append(response+'<br>');
},
please take a datatype as json in ajax call
and in loads.php function add two line as below..
if(isset($_POST['user'])) {
$data['user'] = $_POST['user'];
}
echo json_encode($data);
also change in success function.
success:function(response) {
jQuery("#load_msgs").append(response.user);
}
A bit more simplified would be:
$.post(URL, { data: somefield }, function(result) {
result = JSON.parse(result);
If(result && result.status === 'true'){
}
)};
Depends a bit on the return at server side.
You missed response in success function.
Try this:
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function(response) {
$("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
Related
I'm currently learning basic php and jQuery.
I've created script which is getting url on mouse hover, and sends it to php.
The problem is, if I want to pass this data to php variable, it seems like it doesn't work because it echos only "'This is our JS Variable :'"
Script:
<script type="text/javascript">
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
console.log(hrefValue)
});
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
});
</script>
functions.php:
function our_tutorial(){
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
echo 'This is our JS Variable :'.$testing;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'lms_enroll',
[
'ID' => $testing
]
);
}
die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');
Solution:
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
type: 'post', // define type
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
functions.php:
// post to et value
$test = $_POST['php_test'];
The problem was - when page loaded, value of a variable was empty. So solution is to call ajax in the moment of mouseover.
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
//console.log(hrefValue)
$.ajax({
url: frontendajax.ajaxurl,
type: 'POST',
data: {
'action': 'image',
'php_test': hrefValue
},
success: function(data){
$('#featured-image').html(data);
//console.log(data);
}
});
});
});
I have 2 divs: one is a data from php variable:
<div id="data"><?php echo "$strstr"?></div>
Second is the div for ajax request:
<div id="divButton">[CLICK ME]</div>
Here is js code:
$("#divButton").on("click", function() {
$.ajax({
type: "POST",
url: "test.php",
dataType: "json",
data: {simpledata:12345},
success : function(data) {
if (data.code == 200)
console.log("Success!");
else console.log("Error!");
}
});
And finally php code:
<?php
$strstr = "A";
if ($_POST) {
$strstr = $strstr."A";
}
?>
As you can see I need dynamic update of first div, by clicking on second div.
What am I doing wrong?
You can't change the value of $strstr variable by just updating the value of it in you if condition. You need to make an action in your ajax when return is success. Like this
$("#divButton").on("click", function() {
$.ajax({
type: "POST",
url: "test.php",
dataType: "json",
data: {simpledata:12345},
success : function(data) {
$('#data').text(data)
}
});
});
And in your php if condition you must return a string like this
<?php
$strstr = "A";
if ($_POST) {
$strstr = $strstr."A";
echo json_encode($strstr );
}
?>
HTML code Should be
<div id="data"><?php echo "$strstr"?></div>
<div id="divButton">[CLICK ME]</div>
Ajax Call Code
$("#divButton").on("click", function() {
$.ajax({
type: "POST",
url: "test.php",
data: {simpledata:12345},
success : function(data) {
$("#data").html(data);
},
error : function() {
console.log("Error!");
}
});
test.php Code Should be
<?php
$strstr = "A";
if ($_POST) {
$strstr = $strstr."A";
}
echo $strstr;
//It is advisable that do not close php tag
I'm trying to use AJAX GET function in my code instead of POST.
i have a few hyperlinks which look like this:
<a class=netro" href="mypage.php?search=dog"></a>
<a class=netro" href="mypage.php?search=cats"></a>
<a class=netro" href="mypage.php?search=donkey"></a>
<a class=netro" href="mypage.php?search=apples"></a>
and in mypage.php I have this:
if (isset($_GET['search'])) {
$search = $_GET['search'];
////rest of my code////
}
without AJAX, the page page works fine and it gets the results bases on $search properly.
but with AJAX, i get nothing back in response that I get from AJAX.
this is my ajax code:
$(document).ready(function() {
$(function() {
$('.netro').click(function(event) {
event.preventDefault();
var urlssg = "mypage.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urlssg,
dataType: "html", //expect html to be returned
success: function (response) {
$("#col1").html(response);
//alert('sent');
}
});
});
});
});
could someone please advise on this issue?
Thanks in advance,
You need to provide the search parameter along with the request. Try this:
$(document).ready(function() {
$('.netro').click(function(event) {
event.preventDefault();
var $a = $(this);
$.ajax({
type: "GET",
url: $a.attr('href'), // note that this will include the querystring param
dataType: "html", //expect html to be returned
success: function (response) {
$("#col1").html(response);
}
});
});
});
Here is a clean, simple approach:
HTML
<a class="netro" id="dog">Dog</a>
<a class="netro" id="cats">Cat</a>
<a class="netro" id="donkey">Donkey</a>
<a class="netro" id="apples">Apples</a>
JS/JQUERY
$(function() {
$(".netro").click(function(e) {
e.preventDefault();
var sId = $(this).attr("id");
$.ajax({
type: "GET",
url: "mypage.php?search="+sId ,
data: { search: search_id },
dataType: "html",
success: function (data) {
//Do something with the response data....
}
});
});
});
I am doing a simple longpolling using jquery and php.. It's going on great.. but when I am sending and extra variable.. then the longpolling is not showing the current value that it's supposed to show... My code is below..
The one which is working :
function getContent(time)
{
var queryString = {'time': time};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
The one which is working on page refresh.. but longpolling is not happening...
function getContent(time)
{
var name = '<?php echo $name; ?>';
var queryString = {'time': time, 'name':name};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
PHP side...
while (true) {
$last_ajax_call = isset($_GET['time']) ? (int)$_GET['time'] : null;
$name = $_GET['name'];
//rest of the code...............
}
else{
sleep(1);
continue;
}
What is wrong:
$('#click01').click(function(){
$a = 14;
$.ajax({
url : 'msg.php',
type : 'post',
data : {a:$a}
});
window.location = 'msg.php';
});
msg.php contains:
var_dump($_POST['a']); // NULL, but expected: 14
$('#click01').click(function(){
var a = 14;//not $a since this is javascript
$.ajax({
url : 'msg.php',
type : 'post',
data : {'a':a}
});
window.location = 'msg.php';
});
$('#click01').click(function(){
var a = 14
$.ajax({
type: "POST",
url: "msg.php",
data: {a:a},
beforeSend: function () {
// do action
},
success: function(html){
window.location = 'msg.php';
}
});
});
Rather than set the window.location you want to set a 'success' function on the ajax call so that when it finishes it takes the response and puts it into your page.
E.g. something like:
$('#click01').click(function(){
$a = 14;
$.ajax({
url : 'msg.php',
type : 'post',
data : {a:$a},
success: function(data, textStatus, jqXHR) {
$('#placeToPutTheResponse').append( data );
}
});
});
The above assumes that you have added an HTML node with the id="placeToPutTheResponse"
It is worth reading this other post on SO for a decent overview: jQuery Ajax POST example with PHP
It uses done rather than success, and slightly different syntax, but it's a great overview.
$(document).on('click','#click01',function () {
var a = 14;
$.ajax({
url: 'msg.php',
type: 'post',
data: {a: a},
success: function(e){
console.log(e);
},
error: function(e) {
console.log(e);
}
});
});
Try this
$('#click01').click(function(){
var a = 14;
$.ajax({
url : 'msg.php',
type : 'POST',
data : {a:a},
complete: function (data) {
console.log( data ); // this will tell you the output of var_dump.
window.location.href = 'msg.php';
}
});
// window.location = 'msg.php';
});
also this line window.location.href = 'msg.php'; in function complete will actually redirect you to the msg.php, so if you dont want any redirects remove those lines..