Codeigniter Form Validation pass value instead field name - javascript

I'm using Codeigniter and I have a dynamically created form with lots of input fields. I'm using jQuery and AJAX to submit form and I'm passing all the data from form as an object. This is my jQuery code:
$('body').on("submit", "#app-options-form", function(evnt){
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
// Prevent form submission
evnt.preventDefault();
// Get all form inputs
var inputs = $('#app-options-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"edit_form_submited" : true, "data" : data},
function (data) {
$('.response-container').html(data.result);
}, "json");
});
I'm having difficulties with validation of that form. If I put a field name as a parameter for set_rules(), it won't work because it will look for $_POST['field_name'] but this doesn't exist. The value of this field is passed as $_POST['data']['field_name'], because I'm passing all inputs as an object called "data".
So, is there any way to validate this form?
EDIT:
My PHP code:
// Get received data, here are all the input fields as $field_name=>$field_value
$data = $this->input->post('data');
// Try no. 1 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 2 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($value, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 3 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($this->input->post('data')['$key'], 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
These are my tries to set the rules, but none of them works

I have not tested this but it should work!
$("body").on("submit", "#app-options-form", function() {
// Prevent form submission
evnt.preventDefault();
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
var form = $(this).serializeArray();
var data = {data: form};
$.post("<?php echo site_url('admin/ajax_app_options'); ?>", data, function(response) {
$('.response-container').html(response.result);
}, "json");
});
When you send a serialized string using $.post it come through as an array at the other end :)
Hope this helps!
After you edit
remove var data = {data: form}; from the above
Then with php do:
foreach ($this->input->post() as $key => $value) {
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
The reason you code wouldn't work is because Form_validation will be looking for the key in the $_POST array but it would need to look inside $_POST['data'].
The other option (which would be quite pointless, but follows using the data array) would be:
$data = $this->input->post('data');
foreach ($data as $key => $value) {
$this->form_validation->set_rules("data[$key]", 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
I can't say this will definitely work though.

Related

Retrieve product custom field values in product page custom fields

What I have ?
A single product page showing customs fields to be filled before add item to cart. I have added a button which should put all the values in the custom fields in a text file and save it without reloading the page.
What is my code?
in simple.php
<input type="submit" id="ajax-order-btn" class="button" value="Place Order via AJAX" />
in functions.php
<?php
add_action('wp_head', 'ajax_call_place_order');
function ajax_call_place_order() {
if ( is_product() ){
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$(document).on("click", "#ajax-order-btn" ,function(e) {
e.preventDefault();
var data = {
'action': 'ajax_order',
};
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data);
});
});
</script>
<?php
}
}
add_action('wp_ajax_ajax_order', 'ajax_order_callback_wp');
add_action( 'wp_ajax_nopriv_ajax_order', 'ajax_order_callback_wp' );
function ajax_order_callback_wp() {
$custom_fields_value = ***What Should Go Here***
file_put_contents(wp_upload_dir()['basedir'].'/orders/AJAX_TEST.txt', $custom_fields_value);
}
?>
Currently you're not sending anything to your ajax_order_callback_wp function. To do this you must get the values from the form, by selecting the form and extracting the values.
Instead of listen for the button click, listen for the submit event on the form. Preventing this default behavior will stop the form from reloading the page.
Now the $.post function is responsible for sending data to your backend, but it currently only gets an object with 'action': 'ajax_order' sent with it. It needs the data from the form as well.
jQuery has a function called serialize which can be called on a form element to extract the data from the form. Pass that form data to the data object. Now your form data is included.
jQuery(document).ready(function($) {
var $form = $('form.cart');
$form.on("submit" ,function(e) {
e.preventDefault();
var data = {
'action': 'ajax_order',
'data': $form.serialize()
};
$.post(<?php echo admin_url("admin-ajax.php"); ?>, data);
});
});
On the receiving end you can now extract the value by reading out the global $_POST variable. This variable is available in every function and will contain values if something has been sent using the POST method. In your case you used the jQuery $.post, so $_POST is the way to go.
Because the property on the object is called data you'll need to access that property on the $_POST array to see what the values are.
function ajax_order_callback_wp() {
// If data is there, use it, otherwise use an empty array.
$data = $_POST[ 'data' ] ?? [];
file_put_contents(wp_upload_dir()['basedir'] . '/orders/AJAX_TEST.txt', $data );
}
If you need to know what $data contains, then you could send a response back to the client with the contents of $data to inspect it on the frontend. Add this to end of the PHP ajax_order_callback_wp function.
wp_send_json_success( $data );
And this to your $.post function in JavaScript.
$.post(<?php echo admin_url("admin-ajax.php"); ?>, data, function(response) {
console.log(response);
});

CakePHP can't get ajax GET working

I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax. I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']); ?>
<script>
$.ajax({
type: "POST",
url: "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});
</script>
Here is my search function in my InvoicesController.
public function search()
{
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax'))
{
$name = $this->request->query['term'];
$resultArr = $this->Invoices
->find()
->where(
['Invoices.id LIKE' => ($name . '%')],
['Invoices.id' => 'string']
);
$resultsArr = [];
foreach ($resultArr as $result)
{
$resultsArr[] = (strval($result['id']));
}
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', ['resultsArr']);
}
}
This is the error that is produced when I try to type in an ID.
This is what i want to produce which I have been able to do by using an array in search.ctp
and here is my table I am trying to fetch the IDs from.
There are two methods.
$this->request->query('term');
$_REQUEST['term'];

Populating an array through jquery AJAX in php

I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

Jquery autocomplete with Ajax from PHP not working

The following ajax call
var whatever = [];
$.ajax({
url: "myScript.php",
success: function (response) {
whatever = response.split(",");
}
});
is generating:
"ABC,DEF,GHI,JKL,"
Which are the values I want to use in JQuery autocomplete:
$('#conta').autocomplete({
source:whatever
});
However, nothing is displayed in the autocomplete popup.
If I type the values directly in JS, it works perfectly:
var whatever=[
"ABC",
"DEF","GHI","JKL"
];
But why isn't it working when generated by PHP?
try put $('#conta').autocomplete({
source:whatever
});
in the success callback function
In your source your php array needs to have rows with a "label" key like this:
foreach($rows as $key)
{
$results[] = array('label' => ($key['nome']));
}
echo json_encode($results);
Also if your database rows are not encoded in utf8 you need to encode them otherwise it will be "null":
$results[] = array('label' => utf8_encode($key['nome']));
UPDATE:
myScript.php:
...
foreach($rows as $key)
{
$results[] = array('label' => ($key['nome']));
}
echo json_encode($results);
Javascript:
$(function(){
$('#conta').autocomplete({
source:"myScript.php"
});
});

Categories