PHP Echo doesn't display in html - php

I post data to sa.php via AJAX and on it I use $_POST['data'] to grab the post and echo it. Now when I hit F12 to see the transfer it shows success. The $_POST['data'] shows up on the sa.php but when you look at the screen no text shows.
retrieve code:
Now here is my AJAX code:
$.ajax({
type: "POST",
data: {"data": data},
dataType: "text",
success: function(data){
console.log(data);
},
statusCode: {
404: function() {
alert( "page not found" );
}
},
complete: function (data) {
console.info(data);
}
});
});
I'm trying to echo the $_POST['data'] but it won't display in html.

As most comments point out you are not updating the HTML but rather just logging to the console....try this... create a div with an id "status"
In your page
<div id="status"></div>
and update your javascript
$.ajax({
type: "POST",
data: {"data": data},
dataType: "text",
success: function(data){
$('#status').html(data); //puts the response in a div with id status
console.log(data);
},
statusCode: {
404: function() {
alert( "page not found" );
}
},
complete: function (data) {
console.info(data);
}
});
});

I presume that you would have a container div for where you want to echo your $_POST['data']? If you do, you can use that div as a selector using jQuery, where you can insert your AJAX data into it. To do that you add to your AJAX success function, something like the following:
success: function(data) {
$('#containerDiv').html(data);
}
Note: .html overwrites whatever is in your selector
Have a look at the first answer of this question, i think this might help achieve what you need:
https://stackoverflow.com/a/2972645/5525510

Related

Can't display ajax result WordPress

I have the following simple HTML structure
<button class="aardappel" value="im a value">HENK!</button>
<p class="leeg" value="niks"></p>
What's supposed to happen is once I click the button the p tag gets replaced with the result from my php function
I have the following jQuery
jQuery(".aardappel").on("click", function(){
jQuery.ajax({
url : ajax_testing.ajaxurl,
data: {
action : "test_printer",
buttonvalue : jQuery(this).val()
},
type: "POST",
//dataType: "html",
succes: function(data){
console.log(data);
//jQuery(".leeg").html(data);
},
error: function(){
console.log("foutje");
},
completed: function(){
console.log("doe ik iets?");
}
})
and this is the function ajax is calling
add_action( 'wp_ajax_test_printer', 'test_printer' );
add_action( 'wp_ajax_nopriv_test_printer', 'test_printer' );
function test_printer()
{
$result = <<<HTML
<p>{$_POST["buttonvalue"]}</p>
HTML;
echo $result;
exit();
}
When I press the button I recieve the admin-ajax.php file with the following content
But also when I press the button nothing get logged in the console, in other words, error, succes and completed are not triggering and thus I can't display the result on my page. What am I doing wrong?
Try this script. typo error. it is success function not succes;
<script>
jQuery(".aardappel").on("click", function(){
jQuery.ajax({
url : ajax_testing.ajaxurl,
data: {
action : "test_printer",
buttonvalue : jQuery(this).val()
},
type: "POST",
//dataType: "html",
success: function(data){
console.log(data);
//jQuery(".leeg").html(data);
},
error: function(){
console.log("foutje");
},
completed: function(){
console.log("doe ik iets?");
}
});
});
</script>

jQuery ajax post inside each function, success continue in each

So I have this simple jQuery ajax function, but it's inside each function because it's inside each post on site
$('.post .button').each(function() {
$(this).click(function() {
$.ajax({
url: 'action/update.php',
type: 'POST',
data: {
postID: $(this).closest('.container').find('.postID').val()
},
success: function() {
$(this).css({'color' : 'green'});
}
});
});
});
But after success I want change some css of that element that has been clicked.
Basically I want to post this without need of refreshing the site using basic html post.
Is it even possible? Can you help me out?
you may try this :
$('.post .button').on('click',function() {
var $this = $(this);
$.ajax({
url: 'action/update.php',
type: 'POST',
data: {
postID: $this.closest('.container').find('.postID').val()
},
success: function() {
$this.css({'color' : 'green'});
}
});
});

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

Pass Jquery variables to PHP using AJAX

I'm trying to make an app where if you click on a div, the data-id will be put into a variable, which will give PHP the select parameters to look for. Here's my code to better explain it.
HTML:
<div class="box" data-id="caption"></div>
JQuery:
$('.box').click(function () {
var caption = $(this).data('id');
});
After Googling I found the best way to do this is through AJAX, which I then proceeded to try:
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: ({ caption }),
success: function(data){
console.log(data);
}, error: function() {
console.log("error");
}
});
However, this doesn't seem to work. If there's a better way to do what I mentioned above, I'm open to new ideas.
EDIT
Here is my PHP code.
if(isset($_GET['caption'])){
echo $caption;
$select = "SELECT * FROM pics WHERE text = '".$caption."'";
}
?>
Look through the api at jQuery.
Your data key should contain a json object -
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: {caption: caption},
success: function(data){
console.log(data);
}, error: function(error) {
console.log(error);
}
});

Jquery pass ajax call with post attribute

Checked several topics here on stack overflow and the jquery documentation but still getting stuck.
I basically want this to post (with ajax/jquery) to update a div's content.
function loadSubCats(value)
{
$.post("load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
function(data) {
$('#sub_categories').html("Data Loaded: " + data);
});
}
But im getting no responses what so ever. The page contains the sub_categories div, and this is called onclick for a form event.
<select name='cselect3' onChange='loadSubCats(this.value)' class='e1'>
So basically, it should past the value of the field (cselect3) and load_sub_cats.php should just echo $_POST[catid]; thats it. But im getting zero activity on it so it think its something simple i've screwed up.
you have a problem with $.post syntax. Here's how it should be:
function loadSubCats(value)
{
$.post("load_sub_cats.php",{ "catid": value },
function(data) {
$('#sub_categories').html("Data Loaded: " + data);
});
}
as simple as it is.
function loadSubCats(value)
{
$.post("load_sub_cats.php",
{ catid: value },
function(data) {
$('#sub_categories').html("Data Loaded: " + data); }
);
}
You send catid not "catid"
You're mixing the syntax of $.post and $.ajax which are different. If you want to use the object syntax then call $.ajax, because $.post takes its arguments as a simple un-named list.
function loadSubCats(value)
{
$.ajax({
url : "load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
success: function(data) {
$('#sub_categories').html("Data Loaded: " + data);
}
});
}
You could also directly attach the change event instead, of inline and do away with the loadSubCats() function:
$(document).ready(function(){
$('select[name=cselect3]').change(function(){
$.ajax({
url : "load_sub_cats.php",
data: { "catid": $(this).val() },
type: "POST",
contentType: "application/x-www-form-urlencoded",
success: function(data) {
$('#sub_categories').html("Data Loaded: " + data);
}
});
});
});
two things:
you are using type in post which is not required.
Even after removing it is not working just try to alert it-
function loadSubCats(value)
{
$.post("load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
function(data) {
alert(data)
$('#sub_categories').html("Data Loaded: " + data);
});
}
By alert you will come to know -
1) if there is any php error it will alert that,
2) If php is working fine that it will alert with your values.
updating my post as per latest comments:
Try to use like below:
$(document).ready(function() {
$('.e1').change(function() {
$.post("load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
function(data) {
alert(data)
$('#sub_categories').html("Data Loaded: " + data);
});
})
});

Categories