Posting to same page with jquery.ajax, no vars passing. - javascript

I'm grabbing the onclick event for a specific #id and then sending the relevant form data to the same page( to itself ), checking to see whether $_POST['submit'] is set, if it is I'm sending an email.
It I don't get any errors but I get no data sent via post it seems.
<script>
$(document).ready(function(){
$('#login').keyup(username_check);
$('#clickarea').click(submit_form);
});
function submit_form(){
var login = $('#login').val();
var comment = $('#message').val();
var spt = $('#spam_prevention_test').val();
var submit = #('submit').val();
alert('You got here'); <-- Yes i get the alert so its making it to the function
jQuery.ajax({
type:"POST",
url: "sign_up.php",
data: 'login='+ login+'message='+ comment+'spt='+ spt+'submit'+ submit,
cache: false
});
}
</script>
I tried setting submit to .val, to 1, to "1" thinking it just needed to be set to something.
I did a quick echo in the header to see if I'd get any of the var's and no I don't.
echo "Var" . $_POST['login']; <-- just returns blank
if(isset($_POST['submit'])) { <-- never makes it into here.
What am I missing here, is there something special I need to do to pass back to the same page?

You need a success handler function that will read the response to the HTTP request made by $.ajax and do something with it.

Related

Pass javascript string variable to another page and get the variable in PHP with AJAX

I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.

How to get the values of ajax post in iis7.5

Good day to all..
I have a problem.. I can't get the values that are send in my ajax code..
This is my ajax code
$(function(){
$('#login').on('submit',function(e){
e.preventDefault();
var user = $('#username').val();
var pass = $('#password').val();
$.ajax({
url:'confirm_login.php',
type:'POST',
data:{user:user, pass: pass},
success : function(data){
alert(data);
}
});
});
});
this is my php code
<?php
echo "outside";
if(isset($_POST['user']) && isset($_POST['pass'])){
echo "inside";
}
?>
When I tried it, the result is outside..
I also tried to remove the echo "outside" but the result is empty..
So I can assume the problem is in the $_POST.. If you guys have encountered and resolved this pls help..
Note: This is in the iis7.5.
I've already resolve it.. When I was looking in the networks tab in the chrome dev tools, I saw that it send a request to confirm_login.php and confirm_login..
I also remember I have a rewrite rule in my web.config that removes the .php in the url.. So what I did was just simply remove the .php in the url of the ajax and it works like a charm..
Just this url:'confirm_login',

unable to get the data value of ajax on another page

I'm trying to update the user votes into database. This below ajax codes returns correct rating datas. But, I'm unable to get the alert data on another page. In my car_user_rating.php page I have tried this echo $post_rating = $_POST['performance_rating'];. But it doesn't get the performance_rating data value.
I have checked my console. It returns the rating values (4). I'm confused why it doesn't get the data value?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: "<?=CAR_USER_RATINGS?>",
data: { performance_rating: performance_rating },
success : function(data){
alert(performance_rating)
},
});
});
});
you should alert the data which you pass in success: function()
like
success : function(response){
alert(response);
},
use 'var' in submit handler, may it's because of scope:
var performance_rating = $('input:radio[name=rating]:checked').val();
I am not sure of your context so cant say exactly. Also i dont know if you are using exact same code as above or you have written teh above code in a hurry since there are mistakes there!!!
However Firstly try these
data: { "performance_rating": performance_rating },
url: "<?php=CAR_USER_RATINGS?>" //you have forgotten php
success : function(data, testStatus, xhr){
},
and check each values of data, testStatus, xhr
Also what is the value of
performace_Rating before $.ajax
"<?php=CAR_USER_RATINGS?>" before $.ajax
Just to summarize. I could figure out from your comment that your php is as below:
no. I have this codes on my php page inside the body tag
<?php echo $post_rating = $_POST['performance_rating'];
/*var_dump($get_rating); echo $sql = "UPDATE ".TBL_CAR_USER_RATINGS." SET performance = '$get_rating' WHERE model_id = '2'"; die(); mysql_query($sql, $CN) or die(mysql_error()); */ ?>
This is present inside the body tag!!! Well if you are using body tag i presume you are using other html, header(optional) tags as well
For a ajax response page the reply to client should "ONLY" be the value you want to send back.
Having tags will result in the the ajax response containing these tags as well.
So if you want your ajax page to return performance rating do the below:
//car_return_Rating.php
<?php echo $_POST['performance_rating']; ?>
If you have below code your response is shown below
//car_Return_rating.php
<html>
<body>
<?php echo $_POST['performance_rating']; ?>
</body>
</html>
then response i.e. data in success(data){}
will be equal to
data = "<html><body>4</body></html>"; //assuming 4 to be equal to $_POST['performance_rating'];

Unable to return a value from jQuery.ajax success function

I want to use jQuery Validator to check against the server when a user is signing up for if their desired username is already taken. The PHP script untaken.php does this job, returning ok if the username is available, or taken if it is taken.
My entire source is below, however the line in question is this:
return data != "taken";
Currently the message "Username already taken" permanently appears. However if I change it to:
console.log( data != "taken" );
and type in the text box I see in the console true and false messages exactly when I expect them. That's how I know the design itself isn't to blame, it's just the fact that I can't return anything from the success clause in jQuery.ajax.
$.validator.addMethod("userCannotBeTaken", function(value, element){
var check;
check = $.ajax({
type: "GET",
url: "untaken.php",
data: ({ "user" : value }),
dataType: "text",
success: function(data){
return data != "taken"; //return false if taken or true if not, based on response
}
});
}, "Username already taken");
How can I return something from within jQuery.ajax?
Turns out I was overthinking the whole thing and it can be easily done with jQuery Validator's built-in remote method. Here's my code if it helps someone:
Rule in validator script:
remote: "untaken.php"
PHP:
<?php
//mysql info
[snip]
//connect to database
$sql = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
//Populate variable
$newun = $sql->real_escape_string( $_GET['newuser'] );
//Do the actual checks
$un_already_taken = $sql->query("
SELECT username FROM logins WHERE username = '$newun'
"); //check if UN already in DB
if($un_already_taken->num_rows > 0) //un taken already
print "false"; //tell jQuery to not submit form
else
print "true"; //tell jQuery all is good
As easy as printing "true" or "false". Note it uses GET (ie. URL paramaters) not POST, and the GET variable is the name of the field it is validating (in my case newuser)
To return data to the ajax function, you need to print or echo the result in your untaken.php page.
soemething like:
echo $result;exit;
Then Try to alert the data inside success function
and debug the result with
alert(data);return false;
The function you define for the success action is a callback.
When you make an ajax call, it is done asynchronously, (meaning the script continues executing while the browser connects to the server. You can't use return when dealing with callbacks because they are executed later, rather than immediately as a typical function.
This might make more sense: http://recurial.com/programming/understanding-callback-functions-in-javascript/
The success function should perform whatever actions that you want to happen after you get the data back to the server ie: alert the user that the username is taken.

How to continue form submission after an AJAX call?

I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK. I have a PHP function that does the checking, returning true if data in form_data is OK, some error code otherwise. The following JavaScript issues the AJAX request, and was supposed to continue submitting the form upon successful checking, but it doesn't:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
var proceed = false;
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
proceed = true;
} else {
alert("Error: " + response);
proceed = false;
}
});
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return proceed; //breakpoint here makes the code run
});
});
The code is adapted from a WPSE question, which originally didn't work for me as the form didn't get submitted. I found out that if the jQuery function bound to .submit() returns true, the form should be submitted, so that's what I tried to implement. With the code above, it doesn't seem to work at first (form doesn't get submitted when there are no errors), but upon close inspection with Firebug proceed seems to get the right result if a breakpoint is inserted at the return proceed line. It works as intended with valid data only if I wait it out a bit upon hitting the breakpoint, and then continue execution. If there are errors, the alert is issued without a problem.
What is the best way to handle this?
EDIT
Based on #Linus answer below, the following code works with both valid and invalid data:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
if(jQuery(this).data("valid")) {
return true;
}
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
jQuery("#post").data("valid", true).submit();
} else {
alert("Error: " + response);
jQuery("#post").data("valid", false);
}
//hide loading icon, return Publish button to normal
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
});
return false;
});
});
Short answer: You can't - not in this manner.
Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. This means that you will return proceed before your success callback has been executed, and proceed will always be false. With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well.
So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action.
This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data.
EDIT:
Another way would be to set an attribute on your form, say valid, and in your submit handler check that:
jQuery("#post").submit(function() {
if($(this).data("valid")) {
return true;
}
// Rest of your code
});
And in the success callback for your validation ajax request you would set/clear that attribute, and then submit:
$("#post").data("valid", true).submit();
EDIT:
You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns.
Bind your button to a validation function instead of submit. If it passes validation, call submit().
Wordpress has its own mechanism to process Ajax requests, using wp-admin/wp-ajax.php. This allows you to run arbitrary code on either side of the Ajax boundary without having to write the back and forth status-checking code and all that. Set up your callbacks and go....
The real question is - why are you doing validation server-side? Why can't you load in the validation criteria before - as the post is being written? Then your validation can happen real-time and not on-submit.
jquery.post is performed asynchronously, which means the JS will continue before it gets the reply. You're stuck with Diodeus's answer - bind the button to validtion which then submits the form (which makes it not degrade well), or change your $.post to ajax and turn off async, which will force it to wait for response before proceeding...possibly locking up JS on your page until it times out.
$.ajax({
type: 'POST',
url: ajaxurl,
async:false,
data: data,
timeout:3000,
success: function(){
}
});

Categories