Displaying validation results properly in Jquery - php

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 );
}

Related

JQuery validate plugin, ajax submit

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.

Sending information with AJAX and CodIgniter

Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).
The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK.
I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]
Any help greatly appreciated.
view_index.php
function search(){
var term = document.getElementById("mainsearch").value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: term,
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
controller_site.php
function search(){
$gotcha = $this->input->post('term');
return $gotcha;
}
The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key
Try with this:
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: {'term': term }
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:
data: term,
POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try
data: {foo: term},
and then
$gotcha = $this->input->post('foo');
You need to change return to echo as AJAX response works on whatever echo from called function.
So, you can code like :
function search(){
$gotcha = $this->input->post('term');
echo $gotcha;
}
or
function search(){
echo = $this->input->post('term');
}
The responseText property returns the response as a string, and you can use it accordingly
It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.
Now, for the error:
The success callback takes 3 parameters
You need to pass key-value pair in the data argument of the .ajax call
Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side
1 the callback:
Your success callback function should look like this:
function (data, status, response) {
}
Where:
data is whatever you are echoing from your controller's method. You'll probably want JSON.
status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.
Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.
If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.
2 the sent data
As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:
function search($term)
And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")
If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:
$.ajax("url", {
type : 'POST',
data : $('#form').serialize(),
dataType : 'json',
success : function(data, status, response) {} error : function(response, status error) {}});
3 handle errors
If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:
function search() {
$term = $this->input->post("term")
if($term == FALSE) {
//return a 404 so that you can catch .error on jquery
} else {
echo $term;
}
}
Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.

jquery update html with returned mysql data after POST

I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?
Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.
function vote(el, id) {
$.ajax({
type: 'POST',
url: '/path/morepath/',
dataType: 'json',
data: {
'action': 'castVote',
'vote': id
},
success: function (data) {}
});
$.modal.close();
}
On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.
Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.
If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:
$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);
Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.
Inside of your success function, try console.log'ing your response to see what it looks like
console.log(data);
if there is something you can reference in the return data that is reliable, do a check for it:
success: function(data) {
if(data.result == 'true') {
$('someElement.someClass').someFunction();
}
}
You can change the value or html content of the voting number using a few different options such as:
...
success: function(data)
{
var $newTotal = ...//get total from data
$('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
}
...
Hope that helped,
Dan

jquery ajax form validation on submission then continue on to form submission

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.

How to return value using ajax

I have Ajax file in which code has written to accept values form user and then these values are taken in a Ajax function as follows:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(){
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
});
});
The function for passing values and getting values from other file:
function sendValue(str,name){
$.post(
"newsletter/subscribe.php", //Ajax file
{ sendValue: str,
sendVal: name
},
function(data2){
$('#display').html(data2.returnValue);
},
//How you want the data formated when it is returned from the server.
"json"
);
}
and these values are passed to another file called "subscribe.php" in which insertion code to database is written and again I return the value to my first ajax function as follows:
echo json_encode(array("returnValue"=>$msg));
The msg is ging to contain my message to be displayed.
But now, this works fine on localhost, I get the return values nad message properly but when I upload it on server this gives me an error as:
data2 is null
[Break on this error] $('#display').html(data2.returnValue);
This only gives error for return value but insertion, sending mail functionality works fine.
Please provide me with a good solution wherein I can be able to get back the return values without any error.
Thanks in advance.
If it works on your development site, I suspect the error to be in your PHP script.
Your host might run an ancient php version which does not have json_encode().
Simply call the script manually to check its output. If it requires POST you could write a form or check the result to your ajax call with FireBug
Without additional explanation why this is happening, try this:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(e){ // added the e paramenter
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
e.stop(); // dont submit the form normaly
});
});
If you have firebug, write data2 to its console and see what it is:
function(data2) {
console.log(data2);
$('#display').html(data2.returnValue);
}
In addition, you can use firebug net panel to see your php file raw response (if it has error - you will see it there).
Use that:
var response = $.ajax({
type : "POST",
url : "newsletter/subscribe.php",
dataType : "json",
async : false,
data : "sendValue="+str+"&sendVal="+name
}).responseText;

Categories