I know that there is a lot of questions like this out there, but I have been surfing them and other website for like 4 hours trying to figure this out. I am trying to get main.js to post the data via ajax and then the php should echo that data. If it does not work, it will echo "null". It keeps echoing "null" instead of "John". I know that the jquery and main.js links work, I have tested them. Here is main.js:
$(document).ready(function(){
$.post("index.php", { test: "John"} );
});
And here is the php part of index.php:
<?php
$var = "null";
if(isset($_POST['test'])) {
$var = $_POST['test'];
}
echo $var;
?>
I hope you can solve my problem, and thank you in advance.
You are missing the callback function with the response from the server.
$.post( "index.php",{ test: "John"}, function( data ) {
alert(data);
});
Or you can do something like this:
$.post( "index.php",{ test: "John"})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Please check the documentation Documentation
Give this a shot
jQuery
var available agent = 1;
jQuery.ajax({
type: "POST",
url: "your-url",
data: available_agent,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data){
owner = data['round_robin_agent'];
},
error : function () {
alert("error");
}
});
PHP Script
public function round_robin() {
//Do your work
$round_robin_agent = 'rob';
$results_array = array(
'round_robin_agent' => $round_robin_agent
);
return json_encode($results_array);
}
Download HTTP Trace chrome extension, traceback ajax call and share a screenshot.
https://chrome.google.com/webstore/detail/http-trace/idladlllljmbcnfninpljlkaoklggknp
Related
I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending
I'm trying to verify a very simple ajax request in WordPress (in order to diagnose a probem with a bigger form), and wp_verify_nonce keeps failing on my staging server, but on my localhost it works perfectly!
My setup is like this:
In my plugin __construct function I have:
wp_register_script('request-quote', plugins_url('scripts/request-quote.js', $this->root), array('jquery'));
wp_enqueue_script('request-quote');
wp_localize_script('request-quote', 'pqimageupload',
[
'ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce( 'my_text' )
]);
add_action('wp_ajax_prq_checknonce', [$this, 'prq_checknonce'] );
add_action('wp_ajax_nopriv_prq_checknonce', [$this, 'prq_checknonce'] );
Then in my request-quote.js I have this:
$('#verify_nonce').on('click', function(){
console.log('checking nonce');
let data = {
action: 'prq_checknonce',
security: pqimageupload.security,
}
$.ajax({
url: pqimageupload.ajax_url,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
return false;
});
My prq_checknonce function is:
function prq_checknonce()
{
$response = [];
$response['nonce'] = $_REQUEST['security'];
$response['verify'] = wp_verify_nonce($_REQUEST['security'], 'my_text');
$json = json_encode($response);
echo $json;
die();
}
My HTML link:
Verify nonce
So it's about as simple as you can get! And when I click on the link on my local server: http://abc.localhost/form/' the console log shows thatverifyis 1, however when I upload this to my staging serverhttps://abc.myserver.com/form/` console log shows verify as false!
Does anyone have any ideas?
Much appreciated
Lar
Gaaahhh I'm so stupid!!! It was a caching issue, so whilst I was removing my temp files, I didn't delete my cookies... deleting my cookies did the trick!!
I searched my problem but I cannot find any solution.
I guess it's really simple and I missing something really easy...but I'm stucked.
I have an html page with a php generated list of links, like that:
<?php
$val = "'"my file with spaces.txt"'";
echo 'click me';
?>
Where $val is different each time, depending on a SQL query.
And the file name is showed correctly, since I hover the mouse on the link and I can read on the bottom-left of the browser:
javascript:post_filename('my file with spaces.txt');
Clicking this link will call this javascript function:
<script type="text/javascript">
function post_filename(val){
$.ajax
({
url: 'myurl.php',
data: { filename: val },
type: 'POST'
});
}
</script>
But clicking on it, does nothing! No errors, just nothing happens.
With the dev tools (F12 on Chrome) I see that it's all ok... just the mypage.php doesn't show... is a page with graphics, part of the site!
I'm stucked... please help me!
Thanks so much
Your AJAX call was invalid, data should be either a String, Array or Object. Object is probably what you're after here from the start you've made
<script type="text/javascript">
function post_filename(val){
$.ajax
({
url: 'myurl.php',
data: {
filename: val
},
type: 'POST';
});
}
</script>
Try making data an object:
<script type="text/javascript">
function post_filename(val){
$.ajax
({
url: 'myurl.php',
data: { filename: val },
type: 'POST';
});
}
</script>
I tried your code, but I made some some revisions for it to work ( I just notice you had a semicolon after type, I believe that should be a comma, that the reason why you have unexpected token) my codes works using this:
<?php
$val = "'hello.txt'";
echo 'click me';
?>
on javascript
$('.click').click(function() {
$.ajax
({
url: 'myurl.php',
data: { filename: $(this).attr('file') },
type: 'POST'
})
.done(function (data) {
//check the output from your url
console.log(data);
})
.fail(function (jqXHR, textStatus) {
console.log("Request failed: " + textStatus);
});
});
So the purpose of me using this ajax post is to use some JS variables in a wordpress loop, so I can call a custom loop depending on what the variables are in the ajax post.
Below is the ajax call.
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
Currently I'm sending hard-coded data.
In my single-collection.php page:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
I'm using the print_r just to debug the problem, currently it returns:
Array()
The problem is that I cannot access the Json object called "test" within the single-collection.php
How do I access it?
Thanks in advance!
EDIT: Screenshot of firebug
From ajax to php :
this is the conventional way
var payload = {
smth1: "name",
smth2: "age"
};
and then when calling ajax
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
From phpPost to javascript:
right way getting the post parameters:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
and when returning smthn to javascript
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
Use $_POST['test'] to access the test parameter. Your print_r() shows that it is filled in correctly.
Your PHP code is accessing $_POST['filters[Artist]'] but there is no such parameter in the Javascript. If you pass:
data: { 'filters[Artist]': somevalue }
you can access it in PHP as $_POST['filters']['Artist'].
I have an ajax request like :
$.ajax({
type: "GET",
url: "services/Test.class.php",
data: "call=getTest",
success: function (data) {
alert(data);
},
error: function (response) {
alert("Error getting php file");
}
});
So, in my class ( Test.class.php ), I have a getTest() function and a require_once('OtherPHP'),
When I test this code, I have an error in require once :
No such file or directory
in my alert(data)
how can I fix it?
It seems like you've included a wrong path of OtherPHP file in Test.class.php. Use file_exists() function to make sure that given path really exists before including/requiring in Test.class.php
if (file_exists(`OtherPHP.php`)) {
require_once(`OtherPHP.php`)
} else {
echo "The file `OtherPHP.php` does not exist";
}
You cant able to call the class directly from ajax,
create new php file say test.php
in test.php
include("Test.class.php");
$test = new Test();
$test ->getTest(); //print the getTest outpout here
Javascript:
$.ajax({
type: "GET",
url: "test.php",
.....