I have called a jquery function in form onSubmit
if the status is false, then don't allow form submission
but currently, it is going to submitted page
here is my whole code
php form
echo "<form name='formulaire' id='my_form' method='POST' action='presale_pay.php' onSubmit='return veriftel();'>";
echo "<input type='text' name='promocode' placeholder='Enter Promo Code' id='promo'><div id='result'></div>";
echo "<p> <input type='submit' value='CONFIRM'></form>";
promocheck.php
<?php
include("include/control.php");
if (SessionValide ($session, $bd))
{
$data=array();
$promo=$_POST["promo"];
$party=$bd->ligneSuivante($bd->execRequete("SELECT * FROM promocodes WHERE promocode='$promo' AND used_nbr<=valid_nbr"));
if(!empty($party))
{
$data["status"]=true;
$data["percentage"]=$party["percentage"];
}
else {
$data["status"]=false;
}
echo json_encode($data);
}
?>
function veriftel(e)
{
$.ajax({
type: 'post',
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
if(data.status==false)
{
$("#result").html("<font color=red>Invalid promocode</font>");
return false;
}
else
{
return true;
}
}
});
}
please help me to prevent form submit
should work like this
function veriftel(e)
{
e.preventDefault();
$.ajax({
type: 'post',
async: false,
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
console.log(data);
if(data.status==false)
{
$("#result").html("<font color=red>Invalid promocode</font>");
console.log("false");
return false;
}
else
{
console.log("true");
return true;
}
}
});
}
also the php code should pass the event to the function
echo "<form name='formulaire' id='my_form' method='POST' action='presale_pay.php' onSubmit='return veriftel(event);'>";
The problem is that the following ajax call is asynchronous one. Your code will not wait till you get response from the server, hence the function returns before the completion of ajax call and response.
To avoid the following problem, you'll have to make your ajax call synchronous. Add aysnc:false to make it syncronous
$.ajax({
type: 'post',
async: false, //syncronous call
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
}
Please note that making the call synchronous will cause the javascript execution to freeze in the webpage.
Related
Hello I have a problem with wordpress I can not get an ajax call and I can not find the reason. My query returns me all the time 0.
my javascript code :
updateButton.onclick = function (e) {
var donne = {
'action': 'my_action',
'lodges': updateDeleteArray
};
$(function () {
$.ajax({
type: "POST",
data: donne,
url: ajaxurl,
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(data);
},
});
});
};
my php code :
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action() {
echo 'salut';
die();
}
Try deleting contentType and dataType, because you are not returning a JSON into your function.
Or
modify your function like this
function my_action() {
echo json_encode('salut');
die();
}
hope it helps
I am using the following script
<script>
$(document).ready(function(){
$("#view").click(function(){
var requestId = $("#hdnRequestId").val();
$.ajax({
type: "POST",
url: "enquiryProcess.php",
data: requestId,
cache: false,
success: function(data){
console.log(data);
}
});
return false;
});
});
My controller function is
<?php
include('enquiry_function.php');
$functionObj=new Enquiry();
if(isset($_POST['requestId']))
{
$qt_request_id=$_POST['requestId'];
$responce=$functionObj->view_enquiry_request($qt_request_id);
echo json_encode($responce);
}
?>
And my model function is
class Enquiry
{
public function view_enquiry_request($qt_request_id)
{
$query=mysql_query("SELECT * FROM quote_request WHERE qt_request_id='$qt_request_id'");
$result=mysql_fetch_assoc($query);
return $result;
}
}
I did not get any error.But result in console message is empty.How to get the result from php in jquery ajax.please help me.
Please change
var requestId = $("#hdnRequestId").val();
$.ajax({
type: "POST"
, url: "enquiryProcess.php"
, data: {"requestId":requestId}
, cache: false
, success: function (data) {
console.log(data);
}
});
Pass data as PlainObject or String or Array. See jQuery documentation here http://api.jquery.com/jquery.ajax/
When I click a button, it is handled by ajax and then post to a PHP page. current problem is the PHP cannot recognize the POST name from the front end. It keep throwing me the else part whichis "NOT OK". Below are the snippet.
PHP part
if (isset($_POST['btn-agree'])){ echo "OK<br />"; } else { echo "NOT OK<br />"; }
END PHP part
$(function() {
$("#btn-agree").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postAgreement.php",
success: function(msg){
//do something
},
error: function(){
//do something
}
});
});
});
<form id="agree-form" action="/" method="post" role="form">
<input type="submit" name="btn-agree" id="btn-agree" value="Agree">
</form>
You are not specifying the data to be sent to the server. Use the data parameter and serialize the form.
$(function() {
$("#btn-agree").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postAgreement.php",
data: $('#agree-form').serialize(),
success: function(msg){
//do something
},
error: function(){
//do something
}
});
});
});
EDIT: It looks like .serialize() does not include the submit input type. To test the request method to the script, you can use $_SERVER['REQUEST_METHOD'] and test that it equals "POST". You can also set the data parameter to "btn-agree=Agree".
you forgot the parameter "data" on your ajax.
on isset($_POST['btn-agree']) will always be false because the $_POST['btn-agree'] is not define or set.
check this code or see sample on http://api.jquery.com/jquery.ajax/:
$.ajax({
type: "POST",
data: { btn-agree: $('#btn-agree').val() },
url: "postAgreement.php",
success: function(msg){
//do something
},
error: function(){
//do something
}
});
Statement below I had used before to focus on 1st element in a form, and it works very well.
$('form:first *:input[type!=hidden]:first').focus();
But now the problem is when I use it in a form that was empty(without any input element), and I create the elements inside that form by using jQuery .html() after some work, it will not focus on any element.
This is my form:
<form id="edit_marks" method="post">
<div id="display">
</div>
</form>
This is my jQuery AJAX:
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
$('form:first *:input[type!=hidden]:first').focus();
You are triggering the event before you are adding the form, so you need to trigger event after form get added. Add it inside ajax success. Since ajax is asynchronous it may complete at any time, so before completing it will return from the function.
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
Move the focus code inside the AJAX success, because AJAX means it is asynchronous call. So in order to make focus work after AJAX is to add it in the success.
function getData() {
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax({
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {
Semester:Semester,
StudentID:StudentID
},
dataType: 'text',
success: function(data) {
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts) {
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method