I've written a php function to generate a random math question for anti-spam purposes. It sets a question and the answer to two session variables.
In the HTML file I call the function in the document ready event and send the results to the div for the question, this works fine.
$(document).ready(function(){
$.ajax({
url: "sec.php",
type: "POST",
data: {"GetQA":""},
success: function(data) {
$("#no_spam_Q").replaceWith(data);
}
});
});
What I'm having trouble with is refreshing the text of the question after the user clicks a submit button.
jQuery:
$(document).on("click", "#submit", function () {
var comment = document.getElementById('comment').value
var no_spam = document.getElementById('no_spam').value
$.ajax({
type:"POST",
url: "comments-set.php",
dataType: "html",
data:{no_spam, comment:comment},
success: function(data){
$("#display").html(data);
$.ajax({
url: "sec.php",
type: "POST",
data: {"GetQA":""},
success: function(data) {
$("#no_spam_Q").replaceWith(data);
}
});
}
});
});
Here the nested ajax call is supposed to refresh the question & answer but it always appears to fail.
PHP:
session_start();
Function GetQA($str){
// some code to generate the question & answer
return $secFinal;
}
if (isset($_POST['GetQA'])) {
echo GetQA($_POST['GetQA']);
}else{
echo "not set";
}
The php always returns "not set" and so the anti-spam question text doesn't change. In another PHP file that checks the answer I echo the right answer if a wrong answer is given (just for debugging). The confusing thing is even though "not set" is being returned a new answer is generated, because entering the same answer twice fails my check and the echo message about the correct answer is shown.
I'm guessing this has something to do with the query being async but despite reading the API and other SO questions for many hours I'm none the wiser on how to solve it.
Here's what I've tried:
deferred.done()
Moving the nested call to GetQA from the success function to a
.mouseup() event for the submit button
Moving the function from success and running it after the call to comment-set.php
On another note I'm passing an empty string to GetQA because the the compiler complains if i just use data: {"GetQA"} - how can I call a function without paramenters?
Related
Debated whether to put this on WordPress.SE or here; decided that since it's primarily a jQuery question I'd post it here with the note that it occurred during WordPress development for context.
Long story short, following a guide on how to use AJAX in WordPress to the letter—including pasting in the same code excerpts to see if they run—doesn't work on my dev server. The designated PHP function is never executed, and the call just returns a 0 when I dump the response to a an output div.
I added an error: field to the AJAX call and that triggered, but other than revealing that there was an error, I couldn't figure out what was actually at issue.
Here's a look at the AJAX call, as shown in the guide.
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
}
})
Remembering having had this problem before, I decided to review an old project from a year ago, and found the following workaround, which seems to do the same thing, but actually returns the proper response from the script.
Functional workaround, does what is expected
var ajaxurl = '<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php';
var data = {action: "my_user_vote", post_id : post_id, nonce: nonce};
// Handle any returned values
jQuery.post(ajaxurl, data, function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
});
Ostensibly, it seems that the latter is just a longwinded way of executing the former, but for some reason only the latter works. What could be causing the error on the first block?
EDIT: It seems this may be a WordPress problem after all. I've already sent the code I was working on the other night to production, so to reproduce it I put it into a plugin and tried to run it on the default theme. It's working on the front end, but it's not working when I take it to a back-end page (which is what I was working on at the time). According to the console, it appears to be an issue with enqueueing the scripts on the back end.
To mitigate that issue, I dumped the following on an otherwise blank back-end page:
This post has <div id='vote_counter'>0</div> votes<br>
<div id="output">Test</div>
<script>
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(5)
},
error: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(10)}
})
})
})
</script>
<?php
$link = admin_url('admin-ajax.php?action=my_user_vote');
echo '<a class="user_vote" href="' . $link . '">vote for this article</a>';
Long story short: There is no longer any external script to enqueue, the link is coded directly into it, and the count should update to 5 on success or 10 on failure (since this is a back-end page and therefore there's no page_id to check for). All extraneous data fields have been dropped, since they won't be used in this form.
To simplify generating the response, I trimmed the code back to just the following:
function my_user_vote() {
$result = array(
'status' => 'success',
'count' => 5
);
$result = json_encode($result);
echo $result;
die();
}
What now happens is we get redirected to a blank page with the JSON response dumped on it. Tried dropping in the .post() method from above and that's doing the same thing for some reason.
TL;DR: This probably needs a move to wp.se.
Ive been checking out how to add variables to a ajax request which I can use in my server side script. I checked this stackoverflow post here and checked the jquery api docs here for a ajax request. I am getting error variable in my code is not defined.
I have this line in my code
return $.ajax({
type: 'GET',
url: '/users/show',
data: {'currentusershow': variable},
});
I was wanting it to do something like this with the results so I can keep all my different script in the one file.
if ($.get("currentusershow")) {
// do something here
}
else if...
i am not sure how to add the value to my code?
Also my url does not work going to the show.js.erb where my code is kept.
You need to declare and assign some value to the variable before the request.
Also you need to change the method type from GET to POST.
var variable = 'some data';
/*$.ajax({
type: 'POST',
url: '/users/show',
data: {currentusershow: variable},
success: function (response) {
// Do something with respsone
},
error: function () {
alert("error");
}
});*/
$.get( "/users/show", {currentusershow: variable} )
.done(function( response ) {
//do something with the response here.
});
Mamun was kind of right here as I did not explain myself very well in my question but I thought I would post this and clarify my question with what I was trying to do. The ajax call should be
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentusershow: 'variable'},
});
where the key is currentusershow and the value variable is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentusershow=variable. And in my destination file add my ruby code there to use the variables. In my question that code was more a php type code as I did not know what I was doing at the time.
I am trying to get a jQuery variable to a PHP variable. I have looked it up but can't find a solution. I have the following jQuery:
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success');
}
});
When I console.log te "eventID" it correctly displays the number.
My PHP code is in the index.php. This is also where the .eventRow class is.
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
However nothing happens. The console.log just displays: "Number: " Is there something wrong with the code? Thanks for your help!
EDIT: Could it be the problem that the index.php is already loaded before I click on the button? Because this php code is in the index.php and thus the $phpEventId is not yet set.
In your Ajax, the type: "POST" is for jQuery prior to 1.9.0. If you're using the latest jQuery, then use method: "POST".
If you're using the latest jQuery and you don't specify method: "POST", then it defaults to method: "GET" and your PHP needs to capture it with $_GET['phpEventId'];.
After reading your update, let's try one thing. Change your PHP to return something meaningful to Ajax:
<?php
$phpEventId = $_POST['phpEventId'];
echo $phpEventId;
?>
Then try to capture the PHP response in your Ajax:
$.ajax({
url: "index.php",
method: "POST",
data: {'phpEventId': eventID },
success: function (result) {
alert("result: " + result);
}
});
This is just a part of your code, and the problem is somewhere else. In this context your code works just fine:
<div class="eventrow" id="1">This</div>
<div class="eventrow" id="2">That</div>
<script>
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index-1.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success: '+eventID);
}
});
});
</script>
With the matching index-1.php:
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
Not sure though why do you print javascript code (console.log) into an ajax response here...
Error Is Visible Even Here
According to WebZed round statistic report, this error was visible over 84% of web-developers.
Failed to post data to PHP via JQuery while both frameworks and codes were updated.
Possible Solutions Available Today
Try using other methods for posting because JQUERY and AJAX libraries are not as efficient as shown in the surveys.
New frameworks are available which can do better with PHP.
Alternative method is to create a post request via $_GET method.
Regular HTML5 supports <form></form> try method="post". For security reasons try using enctype="" command.
Try using React Native https://nativebase.io/
Hello: I am working on a project where I am going to have divisions from a league listed as buttons on a page. And when you click on a button a different team list shows for each division. All divisions and teams are stored in a mysql database and are linked together by the "div_id". The plan was have the buttons use javascript or Jquery to send the 'div_id" to a function; which would then use ajax to access an external php file and then look up all the teams for that division using the div_id and print them on the page. I have been piecing this all together and getting the various pieces to work. But when I put it all together; it seems like the ajax part - does not pull in fresh data from the database if the data is changed. In fact, if I change the PHP file to echo some more data or something, it keeps using the original unaltered file. So, if the data is changed that is not updated, and if the file is changed that is not updated. I did find if I actually copied the file with a new name and then had my ajax call use that file instead; it would run it with new code and the new data at that time. But then everything is now locked in at that point and cannot get any changes.
So - I do not know much about ajax and trying to do this. I am not sure if this is totally normal for what I am using and for a dynamic changing team list, it cannot be done this way with ajax calling a PHP file.
OR - maybe there is something wrong with the ajax code and file I have which is making it behave this way? I will paste in the code of my ajax code and also the php file…
here is the ajax call:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
and here is the script.php file that it calls (removed db credentials):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
echo "div id is: " . $div_id . "<br/>";
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$result_g1 = mysql_query("SELECT * FROM teams WHERE div_id=$div_id");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$team_id=$row[team_id];
$team_name=$row[team_name];
echo $team_id . " " . $team_name . "<br/>";
}
}
?>
So - to sum up - is there something wrong with this making it do this? Or is what it is doing totally normal and I have to find a different way?
Thanks so much...
Most likely your browser is caching.
Try adding cache: false as such:
$.ajax({
cache: false,
type: 'GET',
...
The jQuery documentation explains that by doing so, it simply adds a GET parameter to make every request unique in URL.
It works by appending "_={timestamp}" to the GET parameters.
I believe this is caused by your browser's cache mechanism.
Try adding a random number to the request so the browser won't cache the results:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php?r=' + Math.random(),
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
Or turning jQuery's caching option off by:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
},
cache: false
});
Or (globally):
$.ajaxSetup({ cache: false });
I have the following jQuery AJAX to duplicate a background image. I am stumped as to how to effectively return information back to the original page. Here is the AJAX I send on click of "'#dupBtn"...
//DUPLICATE BACKGROUND
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
"user":<?= $_POST['user'] ?>,
"bgID":bgID,
"refID2":<?= $_POST['refID2'] ?>,
"refTable":"<?= $_POST['refTable'] ?>",
"bgTitle":($('#bgTitle').val()),
"path":path,
"bgColor":bgColor,
"bgPoz":bgPoz,
"bgRepeat":bgRepeat,
"attach":attach
}
});
});
Here is the basic MySQL query on the PHP page bgUpdate.php.
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
What I want to do is have the following code fired on the original page upon successful execution of the MySQL entry, dynamically catching the '$bgIDnew' from the MySQL PHP page.
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
You can accomplish this with the success attribute of the .ajax() function:
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
...
},
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
});
That's only part of it though... The other half is that your PHP needs to return something that jQuery can understand as a "successful" call. My preference is to use HTTP status codes. In your case, your PHP script should return a 200 code if it was successful; otherwise, it should return something in the 400 range. (By the way, if you want jQuery to do something separate with errors, you can use the error property of .ajax().)
However, if you need to return data from the server to the client-side script, then your PHP can print out that information like this:
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
// Best practice to keep it in some sort of understandable format
// Here, we'll put it in an associative array:
$response = array('id' => $bgIDnew);
print_r(json_encode($response));
This PHP script sends back to the ajax() method a JSON representation of the $response variable. You've already configured that ajax() method to read the response dataType as JSON, so it already knows how to read the response parameter... Which means your success function can look something like this:
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=' + response.id);
}
jQuery.ajax() has a success property that acts as a callback that you can use. Another is complete which is fired if the request is successful or not.
jQuery.ajax({
/* your stuff here */
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
You can write up the logic in the success callback function of your ajax Request..
This is fired when an ajax request is successfully returned..
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
Add this to your ajax Request...