I am using JQuery validate on two fields. I do all my validation and display messages if validation fails. I then have my submit handler which is using Ajax
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType : 'json'
})
.done(function (response) {
if (response.success == 'success') {
alert('success');
} else {
alert('fail');
}
});
return false;
}
My problem is that both fields are not required, only one or the other (or both). I have handled this no problem. However, the submitted data will be sent to my PHP file using Ajax. In this PHP, I check to see what fields have data e.g.
if (isset($_POST["mobileNumber"] && !empty($_POST["mobileNumber"])){
var_dump("WORKING");
}
I then need to check the input against a web service API. If I do this seperately, it is not a problem. However, if both inputs are entered into the form, I then need to make 2 API calls to 2 different APIs (each input uses a different API), and then return the response for both back to .done. Once again, if only one input is provided, I dont see a problem. The thing I am wondering about is if both inputs are provided, and how I can return both response?
Any advice appreciated.
Why don't you send both the responses of the API calls back in one response?
$response = array();
if (isset($_POST["mobileNumber"] && !empty($_POST["mobileNumber"])){
$response['mobileNumberResponse'] = array('success'=>true,'data'=>array());
}
if (isset($_POST["secondParameter"] && !empty($_POST["secondParameter"])){
$response['secondParameter'] = array('success'=>true,'data'=>array());
}
echo json_encode($response);
Or something similar. If this isn't an option send two ajax's requests if both parameters are present.
Related
My Question is little complicated, But experts may understand what i am trying to ask.
I have the following code in Jquery which submits a form and display the validation result from the destination page.
submitHandler : function(form) {
if($('#login').submit(function(){return false;}))
{
$.ajax
({
type: 'POST',
url: $('#login').attr('action'),
data: $('#login').serialize(),
success: function(data)
{
$('#results').html(data);
}
});
}
return false;
},
The destination page is in php.
The content displayed in #results is php processed validation results
My Issue is -
Iam getting some alpha numeric strings with the validation result as follows
{"output":"","status":-1,"error_messages":{"error":["please enter your name."],"success":[]}}
This is because i have a php file called message.php this validation results should be come through message.php. it is exaclty processing and stripping the unwanted charectors and displays the error message properly.
Is there any way to do this in the above JavaScript(Jquery)that the the validation results should come through message.php instead of direct displaying to avoid putting unwanted characters in validation results (only validation result should be displayed)..
Or any other suggestions you have ?
Looking forward for a favorable action from an expert..
Regards
TOM
ADDITIONAL INFORMATION
When turning off the browsers JavaScript the result is producing correctly, because the form is not submitting through jquery-Ajax (through form action="") and validation messages come through messages.php.
The messages are displaying as
<?php
echo $messages;
?>
I'm ignoring data['output'] and data['status'] because i don't really know how you plan to use them and what values they could have. I'll assume that the success or error message returned is sufficient for the user.
It looks like data contains JSON so why not pull out the relevant success or error message?
DEMO
...
success: function(data)
{
var msg = data['error_messages']['success'][0] != '' ? data['error_messages']['success'][0] : data['error_messages']['error'][0] ;
$('#results').html( msg );
}
...
The answer form #gillyspy is right.
the only part missing is to parts the ajax return data string as jason.
Either add dataType: 'json',to your ajax request.
Or change your success function to
success: function(str)
{
var data =$.parseJSON(str);
var msg = data['error_messages']['success'].length != 0 ? data['error_messages']['success'][0] : data['error_messages']['error'][0] ;
$('#results').html( msg );
}
I wander how send post form data in json format via ajax with JQuery dynamically?
For example I'm coding something like this in JQ:
$.post("test.php", { func: "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
and that's good, but in live apps often need to send huge form data and user can dynamically change the fields, so I don't know how many func1, func2, func3 or even func[] will be sent.
The q is how to do this dynamically, in old world of an AJAX I could done it by serealizing the form and send to the server.
Thanx in advance.
Yes I can send all the data to the server and in any case it will worked well,
example:
$(function() { // on document load
$('#email_form').submit(function() { // set onsubmit event to the form
var data = $('#email_form').serialize(); // serialize all the data in the form
$.ajax({
url: 'testJson.php', // php script to retern json encoded string
data: data, // serialized data to send on server
dataType:'json', // set recieving type - JSON in case of a question
type:'POST', // set sending HTTP Request type
async:false,
success: function(data) { // callback method for further manipulations
for (key in data.email) {
alert(data.email[key]);
}
},
error: function(data) { // if error occured
}
});
return false;
});
});
It is possible to build up dynamic data for an AJAX request but clearly you'll need to know the logic for retrieving that dynamic data. You don't describe this in your question, so in the below example I'm assuming it's based on the number of .user_input fields in the form (which could be 2, or 10, or whatever). The data is then comprised of field name + field value.
The point is to show dynamic collection of data, that's all.
var ajax_data = {};
$('.user_input').each(function() {
ajax_data[$(this).attr('name')] = $(this).val();
});
$.post('some/url.php', ajax_ata); //etc
I am sending an email in jQuery and PHP, i need to tell the page to submit if the ajax was successful and don't submit if not.
I have tried to place the return values in the success and error attributes, but that did not work, so i want to see if i could set the form to not send by returning false but if it was successful letting it submit the page for some server side work.
In the example below i have tried to set a variable and used a conditional to read it. I get an error message because the value does not seem to get passed globally, so when the conditional reads sendMe, it says it is undefined.
Is there a way to do this correctly?
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
var sendMe = 'true';
},
error: function(){
alert('Error: Message could not be sent');
}
});
if (sendMe == 'true'){
//Submit the page...
}
else {
return false;
}
just create a sendMe() function, and call that function from success:
That should do the trick.
The reason your code does not work is because the javascript is not waiting for the ajax call to come back, right after the ajax call it evaluates sendMe which at that point is still false.
You could consider doing this call synchronously of course to prevent that, but I am not sure that is the right way to go. ( async : false is deprecated as of jQuery 1.8 )
When is your conditional
if(sendMe == 'true') ...
ever getting called?
make a little function like this:
function sendMe(){
// whatever your form's id is, put it in place of myForm
$("#myForm").submit();
return true;
}
and in your ajax success block call the function
Try using this setup:
var form = this;
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
form.submit(); // submit form, bypassing jQuery events
},
error: function(){
alert('Error: Message could not be sent');
}
});
return false; // prevent submit
By returning false after the ajax request, we prevent the submit, then we directly submit the form bypassing all of jQuery's submit handlers using form.submit();
Set the form to go through a validator method on submit event:
<form onSubmit='return checkForm();'>
</form>
In this method - checkForm() - perform your ajax post normally. If the ajax post returns as 'success' proceed with the submit else use return false; to cancel submit and notify the user accordingly.
Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery.
What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken".
If any knows how to do this in just PHP and Javscript, I would be very obliged to know.
Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this:
$.ajax({
url: 'usernameChecker.php',
dataType: 'GET',
data: 'username=' + $("#yourUserNameFieldID").val(),
success: function(result)
{
alert(result);
}
});
Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls.
On your serverside you can use something like this:
<?php
if(isset($_GET["username"]))
{
// check username
if(username_is_free)
// of course this needs to be a bit different, but you'll get the idea
{
echo "Username is free!";
}
else echo "Username is taken!";
}
?>
$(document).ready(function(){
// available-button is the ID of the check availability button
//checkAvailability.php is the file which gets the username param and checks if its available
// user is the id of the input text field where the user enter the username
// available-message is the id of a div which displays the availability message. Use this instead of alert
$('#available-button').click(function() {
$.ajax({
type : 'POST',
url : 'checkAvailability.php',
data: {
username : $('#user').val()
},
success : function(data){
$('#available-message').text(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some Error occured. Try again")
}
});
return false;
});
});
Use jQuery ajax, that is the best & easy way to do it.
Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response.
Is there any way for me to do this using only PHP and Javascript.
Because i'm a starting programmer, which does not have the skills to
work with Ajax or Jquery.
I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript.
As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript.
Look into using jQuery AJAX:
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Here you would change the success part to something like:
success: function(data){
if (data == 1){
$(".message").html("Available");
}
else {
$(".message").html("Already Taken");
}
}
I would recommend using jQuery for this task.
jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them.
jQuery docs are good and for there are plenty of online tutorials matching what you want to do.
You will benefit from putting in the time to learn about the jQuery library.
Here is what I'm trying to do,
Capture my form submission post it to my ajax processing for form validation (without a page reload obviously)
then if the ajax server side doesn't return an array of errors (data in the code below) go ahead with the actual form submission. The 'return false' at the bottom of the snippet should prevent the jquery default behavior (which is to submit the form)
I've tried just return true if we don't get any errors but that doesn't work.
Any suggestions?
Here is what I got so far:
$('.submit').click(function(e) {
$.ajax({
type: "POST",
url: "/processform_ajax",
data: $(':input').serializeArray(),
dataType: "json",
success: function(data) {
if (data != '') {
$("#response span").html("");
$('.highlightbox').removeClass('highlightbox');
} else {
$('#myform').submit();
}
},
error: function(error, txt) {
alert("Error: " + error.status);
}
});
return false;
});
I handle this two different ways:
First, do front end validation with the wonderful Jquery Inline validation tool This step knocks out 95% of the problems before having to get tricky with PHP and Jquery.
Second, I submit my values from the form to the script. Let the PHP (in my case) do the "thinking" on validation. If it's incorrect, I return that information in a json_encoded string for the success function. I build a case (if data.valid == true for example) then display error flags. Else, do success steps and notify the user in the UI.
I think the key in your case is to ensure that the data coming back is json_encoded. FYI, I've noticed some very random issues with json_encode sometimes causing issues with the data return function due to square brackets, which are entirely valid but sometimes cause non-erroring faults.
Good Luck.