I am using an jquery script with an ajax update method that is bound to the focus event of a form element. It works, but I first want to check if the form element is not empty. As soon as I do that, the function stops working. Below is the code:
<script type="text/javascript">
if ($('#txt_updateone').val().trim().length > 0) {
function single_change(txt_updateone) {
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
error: function (xhr) {
alert("error");
}
});
return false;
}
}
</script>
txt_updateone is a textarea and the onfocus event calls the single_change function. When I remove the if..... on the second line, it works, but I want it to work only if the textarea is NOT empty.
There are two methods.
1) Validate the data at the place where you are calling this function.
2) Validate the data before sending ajax request using beforeSend.
<script type="text/javascript">
function single_change(txt_updateone) {
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
beforeSend: function(xhr) {
alert("Enter some value");
return $('#txt_updateone').val().trim().length > 0 ? true: false;
}
error: function (xhr) {
alert("error");
}
});
return false;
}
</script>
Change your code to
function single_change(txt_updateone) {
if ($('#txt_updateone').val().trim().length > 0) {
$.ajax({
type: "POST",
data: {
"txt_updateone": 1
},
url: "single_scorechange.php",
success: function(data) {
$('#listinscore').load(document.URL + ' #
listinscore ');
},
error: function(xhr) {
alert("error");
}
});
return false;
}
}
You need to perform the if check inside the method.
As you mentioned if condition before the function, the function is actually declared there. So you are calling the undefined function.
function single_change(txt_updateone) {
if ($('#txt_updateone').val().trim().length < 1) {
//form element is empty
return false;
}
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
error: function (xhr) {
alert("error");
}
});
return false;
}
Just swap function and if statement
//Declare function in all cases
function single_change(txt_updateone) {
//When you call function, check if statement.
if ($('#txt_updateone').val().trim().length > 0) {
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
error: function (xhr) {
alert("error");
}
});
return false;
}
}
What you are doing is defining your function only if the text area is non-empty (and it is likely that when this code runs, it may be empty). I think what you mean to do is to always have the function defined, but only execute the body if the text area has content.
If that's what you want, this may work:
<script type = "text/javascript">
function single_change ( txt_updateone ) {
var content = $('#txt_updateone').val().trim();
if (!content.length) { return; }
// now execute function with non-empty content.
}
</script>
Related
I have tried this below link but not working in my server.
Jquery Ajax - post huge string value
Try this one
$.ajax({
type: "POST",
url: "your_url",
data: {string:3MB_string},
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Hi guys I would like to display an error message when the result is not found and A user should be able to enter the number with or without spaces.
$(document).ready(function () {
$("button").click(function () {
var account = $("#number").val();
if (account.length !== 10) {
$("p").text("number is not valid").css("color","red");
}
if (account != "") {
$.ajax({
url: "profile.php",
method: "POST",
data: {
number:account,
},
dataType: "JSON",
success: function(data) {
$("#name").text(data.name);
$("#phone").text(data.phone);
$("#email").text(data.email);
}
});
}
else {
$("p").text("Please Enter Phone Number");
}
})
})
You can use the error: to do something when there is an error or exception from the URL.
You can edit your code as follows:
$(document).ready(function () {
$("button").click(function () {
var account = $("#number").val();
if (account.length !== 10) {
$("p").text("number is not valid").css("color","red");
}
if (account != "") {
$.ajax({
url: "profile.php",
method: "POST",
data: {
number:account,
},
dataType: "JSON",
success: function(data) {
$("#name").text(data.name);
$("#phone").text(data.phone);
$("#email").text(data.email);
}
error: function(err) {
// do something or alert user
alert("Result is not found")
}
});
}
})
})
I have a form which is validated through AJAX and the problem is that after the ajax gives response 1 it should submit the same form to the same page.
As I have used $('#bigform').submit() this does not allow me to submit the form to the PHP that resides on same page.
$(document).ready(function() {
$('#bigform').submit(function(event) {
var captcha_checks = $('#password_again').val();
$(this).validate();
if (!$(this).valid())
return false;
$.ajax({
type: 'post',
url: 'http://trigma.com/mobile-app-development/verify_captcha.php',
data: { captcha_checks: captcha_checks },
dataType: 'html',
success: function(data) {
if (data == 1) {
$('#bigform').submit();
}
if (data == 2) {
$('#captcha_error').text("Invalid Captcha! Please fill captcha carefully");
}
}
});
event.preventDefault();
});
});
You can add a Boolean variable like this:
$(document).ready(function() {
var first = true;
$('#bigform').submit(function(event) {
if(first){
var captcha_checks = $('#password_again').val();
$(this).validate();
if (!$(this).valid())
return false;
$.ajax({
type: 'post',
url: 'http://trigma.com/mobile-app-development/verify_captcha.php',
data: { captcha_checks: captcha_checks },
dataType: 'html',
success: function(data) {
if (data == 1) {
first = false;
$('#bigform').submit();
}
if (data == 2) {
$('#captcha_error').text("Invalid Captcha! Please fill captcha carefully");
}
}
});
}
else
{
$('#bigform').submit();
}
event.preventDefault();
});
});
This is an odd thing to do, but if you must use a separate function, like:
$(document).ready(function(){
function onSubmit(theElement){
var captcha_checks = $('#password_again').val();
theElement.validate();
if (!theElement.valid()) return false;
$.ajax({
type: 'post',
url: 'http://trigma.com/mobile-app-development/verify_captcha.php',
data: {captcha_checks:captcha_checks},
dataType: 'html',
success: function(data) {
if(data == 1){
onSubmit(theElement);
}
if(data == 2){
$('#captcha_error').text("Invalid Captcha! Please fill captcha carefully");
}
}
});
event.preventDefault();
}
$('#bigform').submit(function(event){
onSubmit($(this));
});
});
</script>
Why not set click event handler for the SUBMIT button instead?
$('#submit-btn').click(function(event){
event.preventDefault();
var form = $(this).closest('form');
$(form).validate();
if (!$(form).valid())
return false;
//...your AJAX call...
if(data == 1){
form.submit();
}
//...
});
I want to call an ajax and display its response :
<script type="text/javascript">
function test() {
var pk = $('#salle_code').val();
var donne = {pk:pk};
var ret = $.ajax({
data: donne,
type: "POST",
url: "<?php echo HTTP_AJAX ?>salle/testAjax.php",
async: false
}).responseText;
return $.trim(ret);
}
$(document).ready(function(){
$('#salle_code').on("blur", function() {
if ($('#salle_code').val() != "") {
alert(""+test());
}
});
});
</script>
Code of the ajax :
<?php
$critere = array();
$critere['salle_code'] = $_POST['pk'];
$ret = Salle::lireParCritere($critere);
echo "111111111111111";
?>
At runtime the alert show a blank result ! So how to work with Phalcon and ajax and models ?
use following code and check browser console for response
$.ajax({
data: donne,
type: "POST",
url: "<?php echo HTTP_AJAX ?>salle/testAjax.php",
async: false
success: function (data) {
console.log(data)
},
error: function (textStatus, errorThrown) {
console.log(textStatus + " : " + errorThrown)
}
});
First you need define a route for AJAX request, e.g. /salle/test:
$router->add('/salle/test', [
'controller' => 'salle',
'action' => 'test',
))->beforeMatch(function ($uri, $route) {
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') {
return false;
}
return true;
});
then create your action:
public function testAction()
{
// some work ..
$this->response->setJsonContent(json_encode(['foo' => 'bar']));
return $this->response;
}
then test:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function test() {
var response = $.ajax({
type: "POST",
data: {},
url: '/salle/test',
success:function(results) {
console.log(results);
}
});
return response;
}
$(document).ready(function(){
console.log(test());
});
</script>
#Klay there was a very simple solution : I created an ajax action inside the controller of the actual view.
I am trying to have my form validate before the ajax runs but can't seem to get the coding right for this to happen.
if i seperate them i can post using ajax with no validation or validation but it posts the default way
here is my current code i am trying
$(document).ready(function(){
// ajax code start
$('#form').on('submit', function (e){
e.preventDefault();
if (spry.widget.form.validate('#form') == true)
{
$.ajax({
type: "POST",
url: "localProxy.php",
data: $('#form').serialize(),
success: function (response) {
document.location = '/thank-you';
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
};
});
});
figured it out
$(document).ready(function(){
// ajax code start
$('#form').on('submit', function (e){
e.preventDefault();
Spry.Widget.Form.onSubmit = function(e, form)
{
if (Spry.Widget.Form.validate(form) == false) {
return false;
}
{
$.ajax({
type: "POST",
url: "localProxy2.php",
data: $('#consult').serialize(),
success: function (response) {
document.location = '/thank-you';
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
};
};
});
});