I want to begin by saying sorry for asking this question because I know this has been asked a lot on here already. I've search through the site and used Google, and looked at other examples but I can't figure out what's wrong. Running the script with FireBug running shows the POST is sent but nothing gets received. I've posted the code below.
Jquery Code:
$('#studio').submit(function (event) {
$('#formLaunch').click();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
search_var: 'test'
},
dataType: 'html',
success: function (data) {
//$('#result').html(data);
alert(data);
}
});
event.preventDefault();
});
PHP Code:
<?php
$term = $_POST['search_var'];
echo $term;
?>
The end result of the code (once the AJAX request starts working) will process sent variables and echo an image which I want displayed in a DIV box on the page. For starters though just trying to get this basic 'shell' to work properly.
Thanks in advance for any help or direction.
Jeff
Always provide an error function, especially when in development. I suspect you have an error for a response (404, 500, etc). Providing an error function for debugging purposes will help you see this more quickly.
try this
$.post('test.php',{'search_var': 'test'},function(data){
alert(data);
});
Related
This question already has an answer here:
Wordpress: call to plugin php file via ajax
(1 answer)
Closed 6 years ago.
So I'm making a Wordpress site and want to send data (css styles dynamically created by jQuery) to PHP. The reason for this (not fully relevant to this question) is to write the data as a .css file that is loaded at the beginning of every page--making it so there's no visible 'change' of styles when js executes (well, only the first time the page is loaded). I'm sure there's probably a better way to do this.
But back to the main part (sending data from jQuery to a .php). I'm executing a js script (on "front-page.php") that does this:
jQuery(function($){
$(window).on("load", function() {
$.ajax({
type: "POST",
url: "create-style.php",
data: { style : styleString },
dataType: "json",
success: function () {
console.log("success");
}
});
});
});
The console says 'success', so I assume data is getting passed to create-style.php.
create-style.php's write function does this
$file = 'new-style.css';
$style = $_POST['style'];
file_put_contents($file, $style, LOCK_EX);
Now the first thing I tried was having the function included in Wordpress's functions.php. I don't know a lot about Wordpress or web development in general, but it seems intuitive that this wouldn't work since probably the php files get executed before the js (so how could it get the data?)
In an attempt to solve this I rewrite the create-style.php as a cron using wp_schedule_single_event to fire when someone visits the site, with a slight delay:
add_action('write_style_cron', function(){
// the above writing function
});
wp_schedule_single_event(time() + 10, 'write_style_cron'); // give it a slight delay to make sure jQuery happens
However, no $_POST data gets written to the file and doing any tests shows it's empty. I've done a lot of tests and know that:
cron functionality is basically working
the writing function works with test values
$_POST is showing as completely empty and I get an "Undefined index" error in the /wp-cron.php?doing_wp_cron
$.ajax is firing success
there are no other php / js errors
Thanks for reading this very long post. Been searching the internet all day for solutions and decided it might be best to just ask. I'd much appreciate any ideas.
Try using this code:
jQuery(function(){
$('#yourFormName').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'create-style.php', //URL of page where to pass values
data: $('#yourFormName').serialize(), //seriallize is passing all inputs values of form
success: function(){
console.log("success");
},
});
}
});
I'm trying to get echoed variable from php and display on the console. I'm using jquery to send data and I know the backend php file script is working fine. Since I want to see the progress and the backend php script echo out the iteration number while the script is running, I'm trying to see how I can get the echoed variable with jquery and display on the console.
I've tried success, onloading but it doesn't seem to work. Any help would be very appreciated. Thank you!
EDIT
$.ajax({
url: location,
type: 'POST',
data:{
iteration:"10",
readsize:"200",
slimdepth:"3",
sourcedirectory:source,
packagepath:MP
},
dataType:'json',
success: function (response) {
console.log("SUCCESS!");
console.log(response);
},
onInteractive:function (response) {
console.log(response.responseText);
},
complete:function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log("Failure!");
console.log(response.responseText);
}
});
So this is how I send the data and backend php script gets the parameters without problems and it runs. Now I can't see anything until php is done running and then it echo everything. In the backend php script, I have iteration number that I want to check and that is the problem since I can't check while it is running but only it is done running.
From what I could understand from your question probably this is what you are looking for.
You are sending data to PHP file with jQuery post or send:
$.post(file.php, {post}, function(data){
});
If you want to log returned data from php in console you must use console.log() function:
$.post(file, {post}, function(data){
console.log(data)
});
and now data will be logged into browser console.
I must be missing something simple here. Firebug shows data being sent exactly as it should in NET tab (NET tab-> Post -> Parameters). PHP function will not even echo simple text.
The PHP:
add_action('wp_ajax_nopriv_process_json', 'process_json_received');
add_action('wp_ajax_process_json', 'process_json_received');
function process_json_received(){
echo "ANYTHING...";
exit;
}
The JS/Jquery (sending correctly)
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
$.ajax({ url: 'http://localhost:12345/site_name/wp-admin/admin-ajax.php',
data: {data: data},
type: 'post',
dataType: 'json',
success: function (response) {
alert("Got this from the server: " + response);
console.log( response );
$('body').append(response); // <-- Append the ajax response to the page body
},
complete: function(XMLHttpRequest, text_status) {
},
error: function (response) {
alert("Error getting php file");
}
});
Again, it doesn't matter what is in the PHP function, the response is always 0. It could be an "enqueue_scripts" thing but ajax request is sending exactly as it should. NET tab in Firebug shows perfect json data so the problem has to be with the PHP function (or correct access to it). Maybe Wordpress is somehow blocking it??? Has to be something simple - I'm hoping a fresh set of eyes will help. Thanks in advance...
Because ANYTHING... isn't correct json format. Try echo json_encode(array('msg' => 'test')); This causes that JQuery have a parsing error (not error from receive)
Change the line in javascript from
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
to
var data = { action: 'process_json', value_name: 'value' };
Wordpress expect POST Data so it can read $_POST['action], you should never Stringify it, but use core javascript object only.
Read more about it : http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
EDIT:
Also change data: {data: data}, to data: data,
:) I miss that last time.
OK, I got it using the following code:
In main PHP plugin file:
echo "<script src='URL PATH TO/ajax_file.js' type='text/javascript'></script>";
add_action( 'wp_ajax_foobar', 'foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'foobar_handler' );
function foobar_handler() {
// Handle request then generate response
echo "ANYTHING..."; // do stuff here
die(); // avoids extra 0 at the end of the response
}
In ajax_file.js: (referred to above in script tag)
jQuery(document).ready(function($) {
$('#id_to_submit_button').click( function() {
var data = {
action : 'foobar',
Whatever : '1234',
}
;
// ajaxurl only needed for front - facing public pages, comment out for back end pages
var ajaxurl = 'http://SITE_URL/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
}
);
}
);
}
);
As soon as I included the script in this way it worked, it would not when placed in a PHP function as many sources suggest. I tried soooo many other ways that should have worked. I went step by step on the Wordpress codex pages (many times) and several other tutorials. Enqueueing scripts, registering scripts, following all recommended practices. I still don't understand why this way works for me and all the other "correct" ways didn't. Could be something in my local server environment. Big thanks to those who answered and tried to help. God knows I have gotten the quick answer on StackOverflow enough times, I hope this saves someone the long hours I spent testing and troubleshooting...
I wonder whether someone may be able to help me please
Firstly, my apologies as this may be a very simple problem to the more seasoned developer, but this is my first website I'm building so please bear with me.
For my site I have a number of forms which all fit around a template I've created. Most forms require the user to click a submit button which then calls a PHP script to save the data into a MySQL database.
An example of code that I use to do this, is as follows:
<form id="addfinds" name="addfinds" method="post" action="savefinds.php">
When the form has been submitted, a line in my addfinds.php script then echoes either Find saved or There was a problem.
I'm working separately on some form validation to cleanse the data before submission, but what I'd like to be able to do is rather than the message being echoed from the PHP script, I'd like a pop up message to appear on screen in it's place, and if the submission is successful for the fields to clear and the page refresh.
I've done quite a bit of reading on this, and I'm a little unsure on how to progress this. I just wondered whether someone, perhaps with a greater experience than I could offer some guidance please or point me in the direction of a good tutorial.
function FUNCTIONNAME() {
$.ajax({
type: "POST",
url: "YOUR METHOD NAME WHICH IS CALLED",
data: "{PARAMETER VALUES TO BE PASSED}",
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
},
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
}
I have seen some answers to this question in previous posts, but no one has given a real working example, just psuedo code. Has anyone ever done this before?
Basically, what i have is a variable in javascript (jquery), and i want to use this variable to drive a query (for an overlay window) i am going to run in php.
From what i have read you can do this using an ajax call to the same page so it doesnt refresh itself, but i must be missing something because i can't get it working...
Any examples out there?
Thanks.
UPDATE 6/21/2010:
Ok, i tried to work through but still having some problems...here is what i have. The page I am working on in edit_1.php. Based on Firebug console, the page (edit_1.php) is receiving the correct 'editadid'.
When i try to echo it out though, i get an 'Undefined variable' error though...anything y'all can see i missed here?
Here is the javascript:
var jsVariable1 = $(this).parent().attr('id');
var dataString = 'editadid=' + jsVariable1;
$.ajax({
url: 'edit_1.php',
type: 'get',
data: dataString,
beforeSend: function() {
},
success: function (response) {
}
});
Here is my php:
if(isset($_GET['editadid']))
{
$editadid = (int)$_GET['editadid'];
}
echo $editadid;
It's hard to help without seeing the code you're currently using.
In jQuery:
var jsVariable1 = "Fish";
var jsVariable2 = "Boat";
jQuery.ajax({
url: '/yourFile.php',
type: 'get',
data: {
var1: jsVariable1,
var2: jsVariable2
},
success: function (response) {
$('#foo').html(response);
}
});
Then your PHP:
<?php
$jsVariable1 = $_GET['var1'];
$jsVariable2 = $_GET['var2'];
// do whatever you need to do;
?>
<h1><?php echo $jsVariable1; ?></h1>
<p><?php echo $jsVariable2; ?></p>
It's fairly generic... but it'll do stuff.
An important thing to note, and a very common mistake, is that any additions you make to the DOM as a result of an AJAX request (i.e in this example I've added a h1 and a p tag to the DOM), will not have any event handlers bound to them that you bound in your $(document).ready(...);, unless you use jQuery's live and delegate methods.
I would say instead of looking for an example you must understand how ajax works. How can you hit a URL via ajax and pass query parameters along with them (these can be the javascript variables you are looking for) How server side response is captured back in javascript and used into manipulate existing page dom. Or Much better you can post what you have tried and somebody can correct it for you.