I have searched and red a lot of this issue.
However, I do not know, why this few simple lines produce a
"POST http://example.com/wp-admin/admin-ajax.php 400 (Bad Request)"
What I basically want (later on) is: If you press a button, a counter will be updated and write a value into my mySQL. But before I can think about a mySQL query, I stumble over this 400 Error.
What I have (really basic, no validations, etc.):
html
<button id="vote" type="button">Click Me</button>
jQuery
<script type="text/javascript">
//var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; // get ajaxurl
jQuery('#vote').click(function() {
jQuery.ajax({
url: 'http://example.com/wp-admin/admin-ajax.php', //just hard coded to see if I have a problem with my ajaxurl
type : 'post',
data: {
'action' : 'ibvote'
},
success: function( data) {
alert( data);}
});
});
</script>
php
add_action("wp_ajax_ibvote", "ibvote");
add_action("wp_ajax_nopriv_ibvote", "ibvote");
function ibvote(){
echo "DONE";
wp_die();
}
Any help would be great.
Thank you.
Thank you #all.
I use the "Code Snippets" plugin and I activated "only run on site frontend". Today with more coffee I switched to run snippet everywhere and: voila! Working like a charm.
#Bhautik: Again thank you for your time and answer :)
Related
sorry if I am missing something simple here. I am using CakePHP 3 and the Friendsofcake Search plug-in and trying to load my results with AJAX. I am not sure what to set for the URL - my understanding is the FormHelper url and the AJAX url must match for SecurityComponent. However even with that disabled I cannot get the form to submit. Any help is appreciated. The plugin is working fine otherwise and I can submit other forms using AJAX just fine - I suspect I am missing something here (or it's not possible - I am a beginning programmer)
<?php
$formUrl='//'.$_SERVER['HTTP_HOST'].Router::url(['controller'=>'Treasures','action'=>'frontIndex']);
echo $this->Form->create('Treasure',['id'=>'myForm','url'=>$formUrl]);
echo $this->Form->input('q');
... (Form submit, end, etc.)
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"POST",
url:"<?=$formUrl?>"
});
</script>
<div class="ajax-result"></div>
Can someone tell me what I should be setting for the $formUrl? Currently the Controller action I am using this on successfully filters data with the search plugin and I have specialized the view to return AJAX results when requested - but there is obviously something else going on I am missing.
This works if I leave the URL blank and use GET instead of POST - should've thought of that sooner.
echo $this->Form->create('Treasure',['id'=>'myForm']);
...
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"GET"
});
</script>
Works as expected. Hope this helps someone!
I'm currently trying to learn the basics of Ajax through example. By following a basic tutorial, I've managed to create the following script:
<!DOCYTPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
}); // end ajax call
});
</script>
</head>
<body>
<a href='#' id='mybtn'>click me</a>
</body>
</html>
Combined with a simple php file named ajax-script.php which contains the following code:
<?php
if($_POST) {
echo "<p>ok</p>";
}
?>
Can anyone identify what I might have done wrong? How can I make this work?
You don't have a success function - that's where the echo'd PHP data will be received.
Also, you need to close the script tag that loads the jQuery library, and use a different script tag to delineate the javascript code.
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Also, your if ( $_POST ) could cause problems -- either remove that, or post some data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
data: 'test=Hello',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Then, you could get your PHP to echo what you sent, thus:
<?php
if($_POST) {
$recd = $_POST['test'];
echo 'PHP side received: ' . $recd;
}
?>
To prevent the first answer from becoming too monolithic, I will respond to your comment in this new answer.
A few things to try:
(1) Location of your ajax.php file -- is it in the same folder as the page with the javascript code?
(2) Name of the ajax.php file -- note that in your code it is ajax-script.php
(3) I added an alert after the button click -- did that come up?
(4) I removed the IF condition -- the ajax.php file will echo something back to the javascript success function no matter what.
(5) To ensure that jQuery is working, I added jQuery code to colorize the background. If background not slightly orangish, jQuery is not loading.
Did this fix it?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('body').css('background','wheat');
$('#mybtn').on('click', function(e){
alert('Button clicked'); //<==========================
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax.php',
type: 'post',
data: 'test=Hello',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Then, you could get your PHP to echo what you sent, thus:
<?php
$recd = $_POST['test'];
echo 'PHP side received: ' . $recd;
?>
Hello I am developing a plugin for Word Press,
Admin area is all ok but i want to use AJAX in front end to send some data to my server.
I am using AJAX in jquery like
jQuery.AJAX({
My code.....
})
But its not working, As the same code approach working well at admin side.
the file where I post my data is in my plugin directory
I am attaching the code please check what am i doing wrong thanks
This is the front end file
jQuery(document).ready(function(){
var url= jQuery('#url').val();
jQuery.ajax({
type:"POST",
URL:url,
data:{
data:'azam'
},
success:function(data)
{
}
})
});
Here is my php file
function hello($a)
{
$a = $_POST['data'];
echo $a;
}
add_action('wp_ajax_hello', 'hello');
add_action('wp_ajax_nopriv_hello', 'hello');
Please dont give me online links caz i search whole internet already but i cant understand how it works. please help
If u use wp_enqueue_script, i suggest u to add this function in your main php file.
function plugin_ajax_articles()
{
wp_enqueue_script( "your_js_file", get_stylesheet_directory_uri() . '/your_js_file.js', array('jquery'), "1.0.0", true );
wp_localize_script( 'your_js_file', 'url', admin_url( 'admin-ajax.php' ) );
}
add_action("init", "plugin_ajax_articles");
Then in ur js file, URl will work.
Don't forget to add a "die();" at the end of your php function.
If u have time, read this article => Tuto Ajax WordPress
I hope that help u :)
Your code looks mostly correct but here are my findings:
In the end of your hello function add die();
Are you using correct admin ajax url?
add this to your functions.php to output admin ajax url.
function ajaxurl() {
?>
<script type="text/javascript">
var AjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','ajaxurl');
you need to add action parameter into your data
.ajax({
type:"POST",
URL:AjaxUrl, // is this url correct? it should be admin ajax url
data:{
action:'hello',
data:'azam'
},
My ajax code didn't work, i am trying to pass the colorit value from my script to my controller(php), but the ajax didnt work. the alert box with out put 'success!' didn't pop out and also the alert(colorit). but if i comment the ajax code, the alert(colorit) pops. is there any wrong in my ajax code? please help. tnx. sorry im new to this.
script
$( ".colorselector_1" ).change(function() {
var colorit = document.getElementById("colorselector_1").value;
alert(colorit);
$.ajax({
url: '/addItemColor',
type: 'GET',
data: {'colorit':colorit},
success:function(data){
alert('success!');
}
});
});
html
<select id="colorselector_1" class="colorselector_1">
<option value="#A0522D" data-color="#A0522D">sienna</option>
<option value="#CD5C5C" data-color="#CD5C5C" selected="selected">indianred</option>
</select>
route
Route::get('addItemColor','CakeController#addItemColor');
controller
public function addItemColor(){
.......}
May I just suggest something?
First of all, this is why you have vars like "error" in place. So the first thing you should do is change your code accordingly:
$( ".colorselector_1" ).change(function() {
var colorit = document.getElementById("colorselector_1").value;
alert(colorit);
$.ajax({
url: '/addItemColor',
type: 'GET',
data: 'colorit':colorit,
success:function(data){
alert('success!')},
error:function(data){
console.log(data);
alert('error');
}
});
});
Another thing to remember is that you have the Network panel in developer tools where you can see all of the calls that were made and whether they had successful responses or not, such as in Chrome when you go to More tools -> Developer tools. These two will help you find the answer of "whether there is something" for yourself, like if there's a wrong URL or something.
Make sure you point to the right url in your $.ajax function.
well after reading all the related topics still no success,
I have 4 files index.php with a simple form, after submit I use process.php to send back (ajax) errors to index.php using external script.js file and also send mail to the owner of this site,all i need is that the user will also be redirected to a thank-you.html page (if there are no errors of course) but no luck ,I have tried all the combinations suggested:
header("Location: http://www.mywebsite.com/thank-you.html");
header("Location:thank-you.html");
if (success).....
echo
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>
I have tried to put it in the bottom of the process,php ,also in the top of the page also tried to put in the script.js-inside $ajax function but nothing:(((
Can anyone tell me what to do?
solved:
thank you all so much:))))) it should be inside the ajax function in the script , right after success: function(data){ I have placed it in the bottom of the script and it didnt work before but now its perfect!
If you're doing this inside of a jQuery $.ajax() call, use the "success" method instead.
$.ajax({
type: "post",
//etc...
success: function(){
window.location.href="thank-you.html"
}
});
The correct usage in JS is "window.location.href".
Also, a PHP file with "header" being set during an AJAX call won't redirect the client browser.
If I understand correctly you will need to handle the redirect once you get the response from process.php IE: in the success callback.
$.ajax({
success: function () {
window.location.href = 'thank-you.html';
}
});
echo '
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>';
assuming that is from php you were missing quotes.
I handled it a little differently as I handled something similar recently. I have the PHP page echo back "true" (this could also just be an INT) and then run if/else statements in the ajax.
$.ajax({
url : "process.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
if (data == "true")
{
window.location = "http://www.website.com/thank-you.html";}
}