Using JQuery to Update Form Fields before passing to PayPal - php

I have spent the day studying up on jquery because I think it will allow me to do this. I have a paypal form and I want the "onClick" button to send this field to my sql table
<input type="hidden" name="amount" id="amount" value="0.05">
Meanwhile my PayPal button is doing this:
<input class="btn btn-primary" onClick="send()" type="submit" value="Subscribe">
How can I pass this value to my process_plan.php? So far I have this but it's hanging and not working.
function send() {
var id = $('#amount').val();
var result;
$.ajax({
type: "POST",
url: "process_plan.php",
data: {
"amount" : amount
},
async: true,
dataType: "html",
success: function(response) {
result = response;
},
error: function(response) {
alert("Oh no! An error occured!");
}
});
return result;
}
I apologize if the code is really wonky - really my first day studying up on Jquery and Ajax.

Don't know if that is the problem, but I think you have a little mistake in your code.
Please try :
...
data: {
amount : "amount"
},
...
In case that amount is a var too, delete the "

Use a tools such as firebug for firefox or fiddler (http://www.fiddler2.com/fiddler2/) to look at the request and response. It will tell you how the communication is going.
That being said it's not hanging. Your send() function is posting a value asynchronously, meaning the function send() will return while the ajax call is being made. You cannot rely on the result to be set by the time the function returns. That is why you have a callback function in the call:
success: function(response) {
result = response;
},
This will run after the call is complete and generally after the originating function has completed. To see it in action change it to:
success: function(response) {
window.alert("Response: " + response);
},
You can then go onto submitting the form, in the success function, by selecting the form and manually call submit:
success: function(response){
$('#form-id').submit();
}
For more information on the quirks of ajax see this msdn: https://developer.mozilla.org/en-US/docs/AJAX
Where is the variable amount defined? I have a feeling you wanted to use id instead:
data: {
"amount" : id
},

I think there is another mistake! You set the variable 'id' to the value of the field, then you send the undefined variable 'amount' in the data of the post. This would fix it:
var amount = $('#amount').val();

Related

Jquery/Ajax not getting input value from widget

Have a ajax request sending data to a WordPress action which works fine however I can receive the nonce value perfectly but the email input isn't being sent. I know I'm targeting the right value. It does not want to get the value of the email input. If I hardcode a value into the input it will see it. I need to get the user entered value and send that to the ajax script. The code is also run on document load and is after the form values have been rendered.
Input field looks like this:
<input type="email" name="cjd_email" id="cjd_email" class="cjd-email-input"/>
The jquery selector looks like:
var cjd_email = $('#cjd_email').val();
The ajax call is:
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: {
action: 'cjd_subscribe',
nonce: cjd_nonce,
email: cjd_email
},
cache: false,
success: function(data) {
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
}
else {
console.log(message);
}
}
});
Thanks :)
I am assuming you are having a class on form i.e. cjdajax. Then use serialize method to send data instead of any other.
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: $('.cjdAjax').serialize(),
cache: false,
success: function(data) {
//your code
}
});
Depending on the browser you use, type=email might not be supported by jQuery / JavaScript and thus the valid() method could return rather strange values. As an alternative, one can use type=text with input validation.
Also, you should Review the success function : You attempt to apply the find()-method on text rather than a DOM element. The code could be corrected if the server returned a JSON-encoded string, so in JavaScript you could convert the string back into an object.
In PHP one could write print(json_encode($yourArray, true)); (notice how the true flag is required for associative keys), while
...
success: function(data){
var yourObject = JSON.parse(data);
if (yourObject.responseData === "success")
console.log(yourObject.message);
},...
could replace the respective current JavaScript passage.

Run jquery ajax request when user finishes typing

I Am working on my project i have added feature for image search and i am having little trouble i have bounded min 2 characters when ajax fire but when i type more then 2 chars ajax run after every letter i don't want that to happen instead i want to run ajax only after when user finishes typing i found few questions related to this i have tried as much as i can but they did not helped me.
Update:-
And one more thing when user clears input box my loader is still there i want to hide loader if input is empty
My Jquery:-
$(function() {
var minlength = 2;
$("#image_query").keyup(function() {
$('#span_result').html('<div class="loader">Loading...</div>');
var that = this,
value = $(this).val();
if (value.length >= minlength) {
$.ajax({
type: "GET",
url: "image.php",
data: {
'image_query': value
},
dataType: "text",
success: function(html) {
if (value == $(that).val()) {
$("#span_result").html(html)
}
}
})
}
})
});
My HTML:-
<form method="get" action="">
<input type="text" id="image_query" placeholder="Search Here For Images">
<button type="submit">Go</button>
Although there are probably more optimal ways - I always find this the easiest and best ways. I think this is what you are looking for. Also please note the hide image should go in the ajax success callback.
var timeout = null;
var minlength = 2;
$("#image_query").keyup(function() {
$('#span_result').html('<div class="loader">Loading...</div>');
// clear last timeout check
clearTimeout(timeout);
var that = this;
var value = $(this).val();
if (value.length >= minlength) {
//
// run ajax call 1 second after user has stopped typing
//
timeout = setTimeout(function() {
$.ajax({
type: "GET",
url: "image.php",
data: {
'image_query': value
},
dataType: "text",
success: function(html) {
// hide image
$(#span_result .loader).hide();
if (value == $(that).val()) {
$("#span_result").html(html)
}
}
});
}, 1000);
});
});
I think, then you should use setTimeout() along with keyup event before sending the ajax request. The delay could be 2 or 3 seconds, as per your need.
Edit:
To clear the loader image, you can do following:
$(#span_result .loader).hide();
At the end inside AJAX response.
You could use the jQuery blur() method to capture when the user is finished with input. Then check for minlength inside the blur function before your ajax call.
You can find an example of blur in W3 schools here

Wait until ajax request is done before each() jquery continue

I'm using Jquery ajax to check registration form.
this is my code:
$("input.register_input").each(function() {
name= this.name;
$(".ono#"+name).html("<img src='images/ajax-loader.gif'>");
if (name == 're_password') {
var dts = this.name+"="+$(this).val()+"&pass="+$("input[name='password']").val();
} else {
var dts = this.name+"="+$(this).val();
}
$.ajax({
type: "POST",
url: "ajc/register_check.php",
data: dts,
success: function(resultfrompage){
$(".ono#"+name).html(resultfrompage);
}
});
});
This is after user submitting the form. so I can't check all values at once.
I dont completly sure if that's the problem, but I this the each() loop is running before the ajax request is done so I'm getting only 1 value (last one) back. and all the rest still showing ajax-loader.gif.
This is the reason for the problem? and if so how can I fix it?
thank you!
Try t use async:false.
By default, all requests are sent asynchronously (i.e. this is set to
true by default). If you need synchronous requests, set this option to
false. Cross-domain requests and dataType: "jsonp" requests do not
support synchronous operation. Note that synchronous requests may
temporarily lock the browser, disabling any actions while the request
is active. As of jQuery 1.8, the use of async: false with jqXHR
($.Deferred) is deprecated; you must use the success/error/complete
callback options instead of the corresponding methods of the jqXHR
object such as jqXHR.done() or the deprecated jqXHR.success().
$("input.register_input").each(function() {
name= this.name;
$(".ono#"+name).html("<img src='images/ajax-loader.gif'>");
if (name == 're_password') {
var dts = this.name+"="+$(this).val()+"&pass="+$("input[name='password']").val();
} else {
var dts = this.name+"="+$(this).val();
}
$.ajax({
type: "POST",
async: false,
url: "ajc/register_check.php",
data: dts,
success: function(resultfrompage){
$(".ono#"+name).html(resultfrompage);
}
});
});
I suggest you to show some loading image while the Ajax request is processed. This way the user will understand that something is going on in the background. When this process will be finished handle the response.

Performing update query then change page in Jquery Mobile

I have a confirmation dialog that leads to an update query when the user clicks a link.
<div class="ui-bar">
<a id="confirm" href="#" data-strid="<?php echo $str_info['str_id'] ?>">Confirm</a>
</div>
What I am looking to do is run an update query, then reload the previous page with the updated information on it.
I thought I accomplished this, but some sort of error keeps popping up in firebug and the ajax doesnt seem to be successful. The error only comes when I reload the page...and when I put a delay on it, there is no error, so I can't even read what it is.
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
}
});
$('.ui-dialog').dialog('close')
setTimeout(
function()
{
location.reload()
}, 750);
return false;
});
</script>
Is there any good way of accomplishing this? Again, in summary, I am looking to perform an update query, then reload the last viewed page (not the dialog) so that the changed info is displayed. ../../ajax/add_land is in PHP.
There are few better ways of achieving this but that is beyond the point, in your case you should do this:
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
$('.ui-dialog').dialog('close');
location.reload();
}
});
return false;
});
</script>
When ajax call is successfully executed it will call code inside a success callback. Ajax call is asynchronous action, that means rest of the code is not going to wait for it to finish. Because of this success callback is used. So there's need for the timeout.
One more thing, there's also an error callback, use it to debug ajax problems:
error: function (request,error) {
alert('Network error has occurred please try again!');
},

AJAX form submission and results

Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.
First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);
In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.
There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.

Categories