I'm having a problem with passing variables in PHP to jQuery via AJAX.
My code PHP is:
function obtieneurl($args, $instance){
extract( $args );
$valorjson = apply_filters('', $instance['value']);
$variableurl = "http://api.openweathermap.org/data/2.5/weather?q=".$valorjson;
return $variableurl;
}
File Weather-ajax-js.js:
jQuery(document).ready(function() {
jQuery.ajax({
type: 'json',
url: '/wp-admin/admin-ajax.php',
data:{
'action':'obtieneurl'
},
dataType: 'html',
success:function(data){
alert(data);
},
error: function(errorThrown){
alert('error');
console.log(errorThrown);
}
});
});
What is the problem?
the function needs to be changed to receive the data from ajax as data is not passed to the function arguments.
function obtieneurl(){
$args= $_POST['action']; // or whatever your method is in your ajax call
extract( $args );
$valorjson = apply_filters('', $instance['value']);
$variableurl = "http://api.openweathermap.org/data/2.5/weather?q=".$valorjson;
return $variableurl;
}
Related
I am developing a WordPress plugin and I am trying to pass a variable from function.php(ajax) to pass_userid.php. Both files are inside my plugin folder. I am attempting to pass the data attribute from function.php(ajax) to pass_userid.php but it did not send the data and received error 500.
Plugin structure:
-plugin folder
--function.js
--pass_userid.php
This is my function.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function custom_ajax(){
?>
<script>
jQuery(document).ready(function( $ ) {
$('[data-source-id="13487"]').on("load", function() {
$('[data-source-id="13487"]').contents().find('button.button.ld-gb-gradebook-component-grade-add').click(function() {
var ajaxurl = "https://<?php echo $_SERVER['HTTP_HOST'];?>/wp-content/plugins/gradebook-custom/pass_userid.php";
var user_id = $('[data-source-id="13487"]').contents().find('.ld-gb-gradebook-component-overall-grade').attr('data-user-id');
alert(user_id);
$.ajax({
type: 'POST',
url: ajaxurl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
'action' : 'call_userid',
'userid' : user_id},
success: function(data)
{
console.log("data pass success!");
},
error: function(errorThrown){
console.log("no data pass!");
}
});
});
});
});
</script>
<?php
}
add_action('wp_head', 'custom_ajax');
?>
This is pass_userid.php:
<?php
function call_userid(){
if(isset($_REQUEST)){
$testing = $_REQUEST["userid"];
console.log("Test 123");
}
}
add_action("wp_ajax_call_userid", "call_userid");
add_action("wp_ajax_nopriv_call_userid", "call_userid");
?>
I want to pass a variable from jquery to PHP on the same page (I am using WordPress).
I tried using using ajax post like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("li.year-item a").click(function(){
$post = $(this);
$.ajax({
type : "POST",
url: "https://example.com/exhibition/",
data: {yearValue: $($post).attr("value")},
success: function (data) {
console.log(data);
}
})
});
});
</script>
and I get the post variable below the script tag:
<?php var_dump($_POST['yearValue']); ?>
but the var_dump result is null..
I have no idea.. anyone can help me? thanks in advance :)
In Wordpress you should use the built in Ajax mechanism.
$.ajax({
type : "POST",
url: "https://your-site.com/wp-admin/admin-ajax.php",
data: {
action: 'retrieve_yearvalue',
yearValue: $($post).attr("value"),
test: 'Test is ok'
},
success: function (data) {
console.log(data);
}
})
On PHP-Side:
add_action( 'wp_ajax_retrieve_yearvalue', 'my_year_retrieve_function' );
add_action( 'wp_ajax_nopriv_retrieve_yearvalue', 'my_year_retrieve_function' );
function my_year_retrieve_function() {
$yearValue = $_REQUEST['yearValue'];
$test = $_REQUEST['test'];
$response = array(
'recieved_year' => $yearValue,
'test_data' => $test
);
wp_send_json( $response );
}
I have an Ajax post from a js file. This all works, but I am not able to set data to a variable and echo this to the screen.
I guess I do not know how to set class variables?
get Ajax code:
public function get_info()
{
// $test = $this->input->post();
var_dump($this->input->post());
$original_property_text = $this->input->post('original_property_text');
// set_ajax($original_property_text);
//$new_property_text = $this->input->post('new_property_text');
//return $test;
}
class variables and constructor:
class Users extends CI_Controller{
// gobal vars
var $new_property_text = '';
var $original_property_text = '';
var $changes = array();
function __construct() {
parent::__construct();
//$changes[] = $this->get_info();
}
*** edit *****
ajax code:
$.ajax({
url: base_url + 'users/get_info',
type: 'POST',
data: {
'original_property_text': $original_property_text,
'new_property_text': $new_property_text
},
success: function(data){
alert(data); // for testing
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
Quick answer, use this in your PHP :
public function get_info()
{
// better to use json when you need to return array
header('Content-Type: application/json');
echo json_encode( $this->input->post() );
exit();
}
In your ajax code (using jQuery framework) :
// call your controller in ajax
$.post('yourUrlHere', $('#yourForm').serialize(),
function(data) {
console.log(data);
// you manipulate json, so you can use : alert(data.property);'
}, 'json');
'$' defines variable so convert your php value to javascript object.
data: {original_property_text: '<?=$original_property_text?>', new_property_text: '<?=$new_property_text?>'},
Or,
var original_property_text = '<?=$original_property_text?>';
var new_property_text = '<?=$new_property_text?>';
var base_url = '<?=base_url();?>';
$.ajax({
url: base_url + 'users/get_info',
type: 'POST',
data: {original_property_text: original_property_text, new_property_text: new_property_text},
success: function(data){
alert(data); // for testing
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
And Get Using Your get function
print_r($_POST);exit
I've followed some tutorials on how Wordpress interacts with Ajax and I've tried to build a frontend form for my users. Starting with my html:
<form id="myform" action="" method="post" enctype="multipart/form-data">
<div id="apf-response" style="background-color:#E6E6FA"></div>
<input type="text" name="title" id="title" value="titlevalue">
<input type="text" name="description" id="description" value="descvalue">
//other inputs
<input type="submit" class="submit" value="Publish"/>
</form>
I've registered and localizd my script
function apf_enqueuescripts()
{
wp_enqueue_script('apf', APFSURL.'/js/apf.js', array('jquery'));
wp_localize_script( 'apf', 'apfajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', apf_enqueuescripts);
I've created wp_ajax_priv and wp_ajax_nopriv functions like:
function apf_addpost() {
get_currentuserinfo();
$uid = $current_user->ID;
$results = '';
$project_title = $_POST['title'];
$project_description = $_POST['description'];
$pid = wp_insert_post( array(
'post_title' => $project_title,
'post_content' => $project_description,
'post_status' => 'publish',
'post_author' => $uid,
'post_type' => 'project',
) );
if ( $pid != 0 )
{
$results = '*Post Added';
}
else {
$results = '*Error occurred while adding the post';
}
// Return the String
die($results);
}
add_action( 'wp_ajax_nopriv_apf_addpost', 'apf_addpost' );
add_action( 'wp_ajax_apf_addpost', 'apf_addpost' );
and I've writtend this very simple ajax function which is not working:
$(document).ready(function(){
msform_init(); //validation function which I'm not showing but it's working
$('#myform').submit(function(event){
event.preventDefault();
apfaddpost(); // which is my below ajax function
})
})
function apfaddpost() {
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
action: 'apf_addpost', //where I should send data and trigger the php
data: $('#myform').serialize(),
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
It's obvious that I'm wrong but I can't see the error. I guess I'm serializing data and calling the action very badly but I don't know how to fix it. I'm not an expert as you can see. Thanks in advance.
My objective was to serialize many input values without writing all keys : values. I don't know if this is a good practice but I've fixed after many tries like this:
function apfaddpost() {
var formData = $('#msform').serialize(); //serialized
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
data: formData + '&action=apf_addpost', //this was the problem
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
If there are better methods please share them, I'm beginner and I'm not really aware of potential issues.
Thanks.
The way in which wordpress does things tends to be confusing sometimes.
Try writing your javascript in the following manner:
(function($){
# assuming you have a lot of code before this line.
msform_init();
$('#myform').submit(function(event){
event.preventDefault();
apfaddpost(); // which is my below ajax function
});
function apfaddpost() {
$.post(apfajax.ajaxurl, {
action: 'apf_addpost', //where I should send data and trigger the php
title: $('#title').val(),
description: $('#description').val()
}, function(response) {
var id = '#apf-response';
$(id).html('');
$(id).append(response);
resetvalues();
});
}
})(jQuery);
I am using jquery's AJAX in my project. Today, I used it somewhere else with all same themethods but it doesn't work.
Is there something wrong with my script?
HTML:
<a class='btn edit_receipe_btn' id='myreceipe-52'>Edit</a>
JQuery:
(Click function works. When I put alert(instance) after var instance line, it works)
$(document).ready(function(){
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
}
});
});
});
PHP:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
It appears the problem is in the PHP. What am I doing wrong?
Is that the entire PHP page? if so, you should echo instead of return
As Jasper De Bruijn notified me, the problem was in my php script. I should use echo instead of return:
Wrong usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
Correct usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
echo $instance;
}
Two things, output the error and check to make sure instance is not undefined.
Output the error like this:
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
},
error: function(response, status, error)
{
alert(response.responseText);
alert(status);
alert(error);
}
});
});
I think you have formed this POST like a get, not sure why. Try doing this in JS:
var dataString =
{
"process" : "userReceipeEdit",
"instance" : instance
};