server side validation for jQuery ajax submission - php

I am using jQuery ajax to submit a form. I have written php code in a different file to insert the form-data into a database table. How can I do the server side validation and show corresponding error message (e.g. this field cannot be empty)? I have no idea about how to solve this problem. jQuery function that does the submission is as follows
$('#form-add-button').click(function () {
$.ajax({
type: "POST",
url: 'addemployee.php',
data: $("#employee-form").serialize(),
success: function (response) {
showEmployeesData();
initInputValues();
},
error: function (response) {
alert('Error:' + response);
}
});
return false;
});

Before inserting the data into the database validate the data using php if you have errors in validation you can encode the error message as json and return back to the ajax function and show the message
AJAX FUNCTION
$.ajax({
type: 'post',
url: 'lettersubscribe/subscribe',
dataType: 'html',
data:$("#subscribenewsletter").serialize(),
success: function (html) {
var result = jQuery.parseJSON(html);
if(result.success == true){
$("#subscribeBox").html('<span id="blacktext">TACK / THANKS FOR</span><span id="bluetext"> SIGNING UP!</span>');
}else{
$("#subscribe_result").html(result.error);
}
}
});
//PHP FUNCTION
function subscribe(){
$msg = array();
$msg['success'] = TRUE;
if($_POST['emailid']){
// Validate email id
}else{
$msg['email'] ="Invalid Email";
$msg['success'] = false;
}
echo json_encode($msg);
}

Related

Codeigniter validation not working with ajax but without ajax working well

when submitting the form using ajax codeigniter validation not working please resolve this issue i am facing this problem from last week
jQuery code that i am using for submitting form
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
data: contactForm.serialize(),
success: function(response){
}
});
});
});
Controller
public function add_account() {
if($this->form_validation->run('add_account')) {
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
} else {
$this->login();
}
}
Here is just the concept. I have not tried codeigniter but am php professional.
You will need to retrieve records as json and pass it to ajax. At codeigniter
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'Account Created Successfully !');
echo json_encode($result);
hence the code might look like below
public function add_account(){
if($this->form_validation->run('add_account')){
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'ok');
echo json_encode($result);
//$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
}else{
$this->login();
}
}
in ajax you can set datatype to json to ensure that you can get response from the server and then let ajax handle the response....
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function(response){
alert(response.message);
console.log(response.message);
//display success message if submission is successful
if(response.message =='ok'){
alert('message submited successfully');
}
}
});
});
});
You have a misunderstanding about what an ajax responder can and cannot do. One thing it cannot do is use PHP to make the browser redirect to a new page. You will have to send a clue back to the success function and then react appropriately.
A few minor changes to the answer from #Nancy and you should be good.
public function add_account()
{
if($this->form_validation->run('add_account'))
{
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post))
{
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
echo json_encode(array("result" => 'ok'));
return;
}
$message = '<span class="error">Account Not Created!</span>';
}
else
{
$message = validation_errors('<span class="error">', '</span>');
}
echo json_encode(array("result" => 'invalid', 'message' => $message));
}
In the Javascript, handle the various responses in the success function of $.ajax
$(function () {
$("#registratiom_form").on('submit', function (e) {
var contactForm = $(this);
e.preventDefault();
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function (response) {
console.log(response); // so you can examine what was "echo"ed from the server
if (response.message=='ok') {
// Simulate an HTTP redirect: to the right page after successful login
window.location.replace( "https://example.com/frontend/somepage");
} else {
//stay on the same page but show the message in some predefined spot
$('#message').html(response.message);
}
}
});
});
});

Ajax request shows complete but data not submitted

I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Kohana - how to create form without refresh?

How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on

Submitting form via ajax in jquery

i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.

Categories