PHP function
function getSerialNumber(){
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
$serial_num_array[] = $serialnum['product_serial'];
}
$json_array = json_encode($serial_num_array);
return $json_array;
}
Return Value
["123456","789012"]
User input
<input name="product_serial" type="text" class="form-control login-field"
value="<?php echo(isset($_POST['reg_product_serial']) ? $_POST['reg_product_serial'] : null); ?>"
placeholder="Product serial number *" id="reg-product-serial" required/>
JS Code:
<script>
jQuery(document).ready(function($){
$.ajax({
url: "registration-form.php&f=getSerialNumber",
type: "GET"
success: function(data){
console.log('eureka');
}
});
$('input#reg-product-serial').on('blur', function() {
alert($(this).val()); //alerts user input
});
});
</script>
I am unable to call PHP function and pass json values in JS code to compare user input value for reg_product_serial.
How to fetch user input entered for product_serial and validate it
with php array returned ?
If that user input does not exists in array validate user by alert
message.
I didn't quite understand why do you have an ajax request to the form and why it's on the document ready event.
As far as I understood, the following is the code I came up with.
I haven't tested it but it should be enough for understanding the direction and main idea.
If you'd need further help add a comment.
validSerials.php
function compareSerialNumber($userSerial){
$validSerial = 0;
#Consider sanitizing the $userSerial variable (!!)
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
if($userSerial == $serialnum['product_serial'])
$validSerial = 1;
}
echo $validSerial;
}
echo compareSerialNumber($_GET['userSerial']);
die();
JS
<script>
jQuery(document).ready(function($){
$('input#reg-product-serial').on('blur', function() {
$.ajax({
url: "validSerials.php",
data: {userSerial: $(this).val() },
type: "GET"
success: function(res){
if(res == 1)
alert('Valid Serial');
else
alert('Invalid Serial');
}
});
});
});
</script>
Related
I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});
My form:
<form action="html_post.php" method="post" id="myform">
<textarea id="textarea" placeholder="Add your comment" name="posting"> </textarea>
<input class="button" type="button" name="send" value="Send">
</form>
I have such code
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: {
text: content,
action: "add_post"
},
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
And such php:
echo mysqli_error($connection);
if (strlen($_POST['posting']) >= 5) {
$text = htmlspecialchars($_POST['posting']);
$insert = "INSERT INTO post(content) VALUE ('$text')";
mysqli_query($connection, $insert);
}
But it does not add text to db. I'm just learning ajax and it's my first experience with key:value so can you help me?
And yep, there is no shown errors
The way you've written it, there is no $_POST['posting']. Instead, $_POST['text'] contains a URL-encoded string containing all the inputs in the form, i.e. a string like "posting=blah blah blah".
What you probably want is:
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: content + '&action=add_post',
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
Based on your posted code, on the server there will be two keys set in the $_POST variable. These are the ones that you define at your ajax request in javascript: text and action.
So while you check $_POST['posting'] it does not exists, but there are $_POST['text'] and $_POST['action']. $_POST['text'] will contain all the form fields as an URL-encoded string, like "posting=xyz". In order to access these values, you could use the parse_str() php function that parses this string as it were a query string.
So the condition at the server side could be something like as follows.
if (isset($_POST['text'])) {
// $formdata passed in by reference, it will contain all the form fields
parse_str($_POST['text'], $formdata);
}
if (isset($formdata['posting']) && strlen($formdata['posting']) >= 5) {
// Perform db operation
}
i have a problem in ajax, indeed, i try to send value with ajax to my upload function before submit.
But when i check the $_POST array in my php code, there is only the value of the form, and not from the ajax, and I don't know why.
Here is my code :
HTML:
<button id="btn_saisie" class="btn btn-app saver adddocu" ><i class="fa fa-save whiter"></i></button>
<form action="/uploader/adddocu" id="form_saisie" class="form_saisie" method="POST" enctype="multipart/form-data">
<input type="file" name="document" class="val_peage form-control form_num" id="document" data-rest="document" placeholder="Document">
<input type="text" name="description" class="val_parking form-control form_num" id="description" data-rest="description" placeholder="Description">
JS :
$( ".adddocu" ).click(function() {
if ($('#document').val() != "" && $('#description').val() != ""){
api_sendvalue_adddoc();
}
if ($('#document').val() == "")
alert('test');
else if ($('#description').val() == "")
alert('test2'); });
function api_sendvalue_adddoc(){
user = JSON.parse(sessionStorage.getItem('user'));
pays = localStorage.getItem("pays");
magasin = localStorage.getItem("magasin");
$.ajax({
type: 'POST',
url: '/uploader/adddocu',
data: {pays:pays, magasin:magasin},
success: function(data){
alert(data);
$("#form_saisie").submit();
console.log(data);
},
error: function(xhr){
alert(xhr.responseText);
console.log(xhr.responseText);
}
}); }
PHP:
public function adddocu(){
$path = './asset/upload/pdf/';
$path2 = '/asset/upload/pdf/';
$config['upload_path'] = $path;
$config['encrypt_name'] = false;
$config['file_ext_tolower'] = true;
$config['allowed_types'] = 'pdf';
// die(var_dump($_POST));
$this->load->library('upload', $config);
foreach($_FILES as $id => $name)
{
$this->upload->do_upload('document');
$upload_data = $this->upload->data();
$url = $path2 . $upload_data['file_name'];
$data = array('nom' => $upload_data['raw_name'], 'description' => $_POST['description'], 'url' => $url, 'user_id' => '17');
$this->db->insert('pdf', $data);
}
redirect("/login/docu");
}
So, when I var_dump the $_POST array, I only have the value of "description", and not of "pays" and "magasin".
Can you help me please?
Thanks for your time.
Seems like you are accessing localstorage value , you are posting it somewhere and then submiting the form.
More you are submiting the form which dont have this pays & magasin so i have a trick using which you can achieve it.
Create two hidden inputs inside your HTML form like
<input type="hidden" name="pays" id="pays">
<input type="hidden" name="magasin" id="magasin">
Now before ajax call give them values after getting it from local storage, like this.
user = JSON.parse(sessionStorage.getItem('user'));
pays = localStorage.getItem("pays");
magasin = localStorage.getItem("magasin");
$("#pays").val(pays);
$("#magasin").val(magasin);
$.ajax({ .... });
Continue your code and enjoy.
Hopefully it will work for you.
The issue is because you are not preventing the form from being submit normally, so the AJAX request is cancelled. Instead of using the click event of the button, hook to the submit event of the form and call preventDefault(). Try this:
$('#form_saisie').submit(function(e) {
e.preventDefault();
if ($('#document').val() != "" && $('#description').val() != ""){
api_sendvalue_adddoc();
}
if ($('#document').val() == "")
alert('test');
else if ($('#description').val() == "")
alert('test2');
});
EDIT:
Here is a working example of a ajax post to codeigniter:
View
<script>
$( document ).ready(function () {
// set an on click on the button
$("#button").click(function () {
$.ajax({
type: 'POST',
url: "[page]",
data: {pays: "asd", magasin: "dsa"},
success: function(data){
alert(data);
$("#text").html(data);
console.log(data);
},
error: function(xhr){
alert(xhr.responseText);
console.log(xhr.responseText);
}
});
});
});
</script>
Controller
<?php
// main ajax back end
class Time extends CI_Controller {
// just returns time
public function index()
{
var_dump($_POST);
echo time();
}
}
?>
Output
array(2) {
["pays"]=>
string(3) "asd"
["magasin"]=>
string(3) "dsa"
}
1473087963
Working example here
So you should check the request that you're making from AJAX, on dev console. There you should get the response with the var_dump($_POST).
to debug try to make your controller return only the $_POST data, comment the rest. and same thing on javascript side, test only the ajax post and data received.
i am trying to make an search box which search the name from elastic search database, but when i run the it always give me an error that ----
Notice: Undefined index: value in the line --> $query = $_GET['search_keyword'];
but from my script i believe it should get the "search_keyword".
Search box --
<form method="GET" action="/latest/helloTestData">
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</form>
Script --
<script>
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
$.ajax({
type: "GET",
url: "/latest/helloTestData", // address to the php function
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
</script>
PHP ---
public function helloTestDataAction() {
$paramss = array('hosts' => array('localhost:9200'));
$client = new Elasticsearch\Client($paramss);
$query = $_GET['search_keyword'];
if ($query != "") {
$params = array();
$params['size'] = 1000000000;
$params['index'] = 'myindex';
$params['type'] = 'mytype';
$params['body']['query']['bool']['must'] = array(
array('match' => array('name' => $query)), // search data by input data
);
$esresult = $client->search($params);
if ($esresult < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
echo $esresult; //results found here and display them
}
}
return new Response('ok');
}
Can anyone knows how to fix this problem. Thanks a lot in advanced.
Modifiy $_GET['value'] into $_GET['search_keyword']
So
public function helloTestDataAction() {
[...]
$_GET['search_keyword'];
[...]
}
You're searching for a key that will not be into $_GET array, as, into your ajax request, you're passing a key named search_keyword and so this is the error
Simply replace
$_GET['value'] to $_GET['search_keyword']
Quick and simple! The front-end pass the typed text via GET by url.
In this test I put the 2 files in the same folder. Change as you need.
Front-end:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="my_header" style="background-color:lightblue">
</div>
<input type="text" id="foo" value="bar" onkeyup="loadlink(this)" />
<script>
function loadlink(e){
$('#my_header').load('back.php?var='+e.value,function () {
$(this).unwrap();
});
}
</script>
Back-end (back.php):
<?php
echo "received: " . $_GET["var"] . ' <br>at ' . gmdate('Y-m-d h:i:s \G\M\T', time());
?>
I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";