I know that this question has already been answered in other topics but for some reason it doesn't work for me and I don't understand why.
I call a template with ajax and inside it there are set some php variables and i need to get those values.
first-template.php
<?php
$advert = array(
'ajax' => 'Hello world!',
'advert' => 'Bye',
);
echo json_encode($advert);
?>
second-template.php
?>
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
This is how it is shown here but the function returns error.
First, maybe, you can change the request type to GET, because you don't post anything, but tried to get the information.
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function () {
alert("error");
}
});
});
</script>
EDIT:
Here is a functional script:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
See the modifications:
GET instead of POST
console.log(result) to see the result
In my browser console:
Object { ajax: "Hello world!", advert: "Bye" }
Just to be sure, do you load your JQuery properly and do you work on a WAMP/LAMP server?
Can you post the entire files code?
EDIT2:
Check error in console and post it here, this is more easy to find the problem in the future with it.
Related
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>
$.ajax({
type : 'POST',
url : '<?=site_url("aplikasi_tambah_merchant/input_merchant/get_mdr_master");?>',
data : 'kode='+arr_value[0],
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
var res = JSON.parse(data);
datamdr = Number(res.mdr_debit);
$('#ajax-loader').hide();
}
});
$.ajax({
type : 'POST',
url : '<?=site_url("pameran/update_mdr_pameran");?>',
data : 'datamdr='+datamdr+'&app_id='+app_id+'&on_off=2',
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
alert("tes "+datamdr);
alert("balik "+data);
$('#ajax-loader').hide();
}
});
this is the ajax code to send my data.
the first ajax is to get the value of datamdr = Number(res.mdr_debit);then i send datamdr value again to the controller, but in controller here
public function update_mdr_pameran() {
$this->config->set_item('compress_output', FALSE);
$datamdr = trim($this->input->post('datamdr'));
$app_id = trim($this->input->post('app_id'));
$on_off = trim($this->input->post('on_off'));
$out = $this->aplikasi_model->update_mdr_app_id_onoff($datamdr, $app_id, $on_off);
echo json_encode($datamdr);
}
those datamdr value is undefined, while the other 2 variable is still readable as string? how is it possible? i've tried parse the first json to string and int but still no luck to send the data again
Ajax works asynchronously by default so what is happening, is that both your requests execute at the same time and at that moment, the value you set on completion of the first ajax call, is still undefined.
You should wrap your second ajax call in a function and call that from the success handler in your first ajax call.
Or you combine both requests in one as they seem to be going to the same server any way.
A third option would be to make the ajax calls synchronous but that would block the execution of your script so I would not recommend that.
What #jeroen suggesting is this:
$.ajax({
type : 'POST',
url : '<?=site_url("aplikasi_tambah_merchant/input_merchant/get_mdr_master");?>',
data : 'kode='+arr_value[0],
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
var res = JSON.parse(data);
datamdr = Number(res.mdr_debit);
$('#ajax-loader').hide();
update_mdr_pameran();
}
});
function update_mdr_pameran(){
$.ajax({
type : 'POST',
url : '<?=site_url("pameran/update_mdr_pameran");?>',
data : 'datamdr='+datamdr+'&app_id='+app_id+'&on_off=2',
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
alert("tes "+datamdr);
alert("balik "+data);
$('#ajax-loader').hide();
}
});
}
I have a trouble receiving data sent using ajax in a php file. It seems that ajax sends data, cause I get a success message, but php page shows me an error "Notice: Undefined index: ab".
Here is my jquery code for sending data using AJAX:
$('#download-btn').click(function(){
var ab="abc";
$.ajax({
url:'generate_url.php',
data:{'ab':ab},
type:'post',
success:function(data) {alert("sent");},
error: function(request, status, error) {alert(request,status);}
});
}
And that's how I extract data in a generate_url.php:
<?php
$a = $_POST['ab'];
echo $a;
?>
Thanks in advance for your help!
You are missing the ); from your code. For simple POST I'll advice you to use $.post (there's nothing special about $.post, it's a shorthand way of using $.ajax for POST requests.
$('#download-btn').on('click', function(){
var ab="abc";
$.post('generate_url.php', {'ab':ab}, function(data){
console.log(data);
});
});
You are missing ); at the end of the ajax code.
<script type="text/javascript">
$(document).ready(function($) {
$('#download-btn').click(function(){
var ab='abc';
$.ajax({
url: 'generate_url.php',
type: 'POST',
data: {'ab':ab}
})
.done(function(respose) {
//todo
})
});
})
</script>
You were missing ')' in your javascript code
This will work:
$('#download-btn').click(function () {
var ab = "abc";
$.ajax({
url: 'generate_url.php',
data: {'ab': ab},
type: 'post',
success: function (data) {
alert("sent");
},
error: function (request, status, error) {
alert(request, status);
}
});
});
I am trying to send a confirmation message to my API after click on activation link , I am trying lot but failed ,
http://polestarllp.com/users/useractive.php?contranumberid=23215
<script type="text/javascript">
$(document).ready(function () {
var person = "<?php $data; ?> ";
$.ajax({
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
//type: 'Post',
data:person,
success: function (data, xhr) {
alert(data.ErrorMessage);
if(data.Success)
{
document.location.reload();
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});
</script>
<style>
So far from what you said I have understood that you're trying to send a POST request whenever a user accesses your URL. Is that correct?
In that case try something like this:
<script type="text/javascript">
$(window).ready(function(){
$.ajax({
type: 'post',
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
data: {'id' : 23215},
success:(function(data){
alert('Success ' + data);
}),
error:(function(data){
console.error('Error ' + data);
alert('Error has occurred');
})
});
});
</script>
This will send a POST request to http://192.168.1.102:1512/qlikapi/RegisterUser straight after when the page loads, with id parameter and its value being 23215
If you want to get the contranumberid from the URL, you can embed the PHP into your JS script like so:
<script type="text/javascript">
var contranumberid = <?php echo intval($_GET['contranumberid']);?>;
$(window).ready(function(){
$.ajax({
type: 'post',
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
data: {'id' : contranumberid },
success:(function(data){
alert('Success ' + data);
}),
error:(function(data){
console.error('Error ' + data);
alert('Error has occurred');
})
});
});
</script>
Note that I've added a new line:
var contranumberid = <?php echo intval($_GET['contranumberid']);?>;
This will assign a JS variable to the value of the GET contranumberid parameter and the POST that value to http://192.168.1.102:1512/qlikapi/RegisterUser.
Hope this helps :)
The script you have given in the question and the actual script in the page linked in question is slightly different. The success callback function was missing closing braces. Here's a better version of your JS code:
<script type="text/javascript">
function myfunc(id) {
id = 23215;
$.ajax({
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
type: 'post',
data: {'id' : 23215},
success: function (data, textStatus, xhr) {
alert(data.ErrorMessage);
}
});
}
</script>
Also, I didn't see any code invoking myfunc() anywhere?
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