Ajax send no data [ Codeigniter ] - php

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.

Related

I am unable to post data using ajax on url friendly blog detailing page where I am already using url value in Query

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

Jquery file upload not working in Laravel

I have tried majority of other questions here and other solutions and nothing has worked so far.
What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.
Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,
second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.
Route:
Route::post('/upload', 'UploadController#uploadSubmit');
View:
<div>
<input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
<br />
<div id="files_list"></div>
<p id="loading"></p>
<input type="hidden" name="file_ids" id="file_ids" value="" />
</div>
Ajax call:
$(document).ready(function(){
$("input").change(function(){
alert('triggered');
debugger;
$('#fileupload').fileupload({
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
}
dataType: 'json',
add: function (e, data) {
$('#loading').text('Uploading...');
data.submit();
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
if ($('#file_ids').val() != '') {
$('#file_ids').val($('#file_ids').val() + ',');
}
$('#file_ids').val($('#file_ids').val() + file.fileID);
});
$('#loading').text('');
}
});
});
});
});
Controller:
public function uploadSubmit(Request $request){
$files = [];
dd(request());
foreach($learnerFiles as $key => $learnerFile){
if(count($learnerFile) > 0){
$path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
$search = 'public/' ;
$trimmed = str_replace($search, '', $path) ;
//dd($learnerFiles);
$file = FileUpload::create([
'user_id' => $learner->id,
'file_name' => $key,
'path' => $trimmed
]);
}
else{
}
$file_object = new \stdClass();
$file_object->name = $key;
$file_object->size = round(Storage::size($path) / 1024, 2);
$file_object->fileID = $learner->id;
$files[] = $file_object;
}
return response()->json(array('files' => $photos), 200);
}
I'm using the following method to upload images using Ajax call and Laravel back-end.
var uploader = $('#image-uploader[type="file"]');
var data = new FormData();
$.each(uploader.files, function() {
data.append('image[]', this);
});
data.append('_token', $('[name="csrf-token"]').attr('content'));
var url = '/upload'; //Or any target path with post method
$.ajax({
url: url,
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
alert('succeed');
}
});
Consider you can access to image files in server-side using $_POST['image] array.
Hope this helps you.

jQuery - Check user input with php array

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>

store form data in mysql database using ajax in codeigniter

Edit:
It was a problem with localhost and I think with the htaccess file. Although I couldn't make it in localhost, the script is running fine on the web host.
I want to store my form data in to the database using ajax in codeigniter. The problem is that everything is fine, except I'm getting a 500 server internal error.
My contoller:
public function order()
{
$order = $this->main_model->order($_POST);
if($order)
{
return true;
}
else
{
return false;
}
}
my model:
function order($options = array())
{
$options = array(
'client_Name' => $this->input->post('oName'),
'client_Phone' => $this->input->post('oPhone')
);
$this->db->insert('md_orders', $options);
return $this->db->insert_id();
}
and of course I'm using stepsForm script and this is the js code I have:
var theForm = document.getElementById( 'theForm' );
new stepsForm( theForm, {
onSubmit : function( form ) {
var form_data = {
oName: $('#oName').val(),
oPhone: $('#oPhone').val(),
};
$.ajax({
url: "<?php echo base_url() . 'main/order/'; ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
}
} );
and this is the HTML code:
<form id="theForm" class="simform" autocomplete="off">
<ol class="questions" id="questions">
<li>
<span><label for="oName">Your name:</label></span>
<input class="finput" id="oName" name="oName" type="text"/>
</li>
<li>
<span><label for="oPhone">Your Phone Number:</label></span>
<input class="finput ltr" data-validate="number" id="oPhone" name="oPhone" type="text"/>
</li>
</ol>
</form>
and the error I'm getting is :
POST http://localhost/123/main/order/ 500 (Internal Server Error)
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and nothing is stored in the database. What am I doing wrong?!
Try to check your input in controller before send it to model, although it is not mandatory. In your model you need just feed of your array. So you can just set name of parameter.
Your model something like this:
public function order($options) {
$data = array();
$data['client_Name'] = $options['oName'];
$data['client_Phone'] = $options['oPhone'];
$this->db->insert('md_orders', $data);
if($this->db->affected_rows() > 0) {
return $this->db->insert_id();
else {
return false;
}
}
Your controller something like this:
public function order() {
$order = $this->main_model->order($this->input->post());
if( $order !== false ) {
echo "Inserted!";
} else {
echo "Not inserted!";//These are your ajax success function msg parameter
}
}
Also, I can't see the logic of form parameter inside onSubmit property's function( form ). Maybe you could remove it?
In your view,place the following code in your script,please...
one_field = $('#one_field').val();
second_field = $('#second_field').val();
$.ajax({
type:"post",
data:{one_field:one_field, second_field:second_field},
url :'<?=base_url("directory/controller_name/your_method_name")?>',
success: function(data)
{
alert("success");
}
});
Now the place the following in your controller.
function your_method_name()
{
$your_data = array(
"table_field_1" => $this->input->post('one_field'),
"table_field_2" => $this->input->post('second_field')
);
$last_id = $this->your_model->insert_data_function($your_data);
if(isset($last_id)
{
//your code
}
else
{
//your code
}
}
In your Model,place the following.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
return $this->db->insert_id(); //will return last id
}
Instead of using base_url() in your JS, you should try and use site_url()
Your CodeIgniter website runs through the index.php file.
The base_url() function will return the URL to your base directory.
The site_url() will return the URL to your index.php file.
Your form is trying to access "http://localhost/123/main/order" when it should be trying "http://localhost/123/index.php/main/order"
Hope this helps.
Edit
You should also have a look at the form helper.
https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html

How to use post() jquery method with codeigniter form_validation

I want to validate a form without refreshing the page using the .post() jQuery method.
I use codeigniter for validation. Could you please tell me how to make it right? I find it pretty confusing ...
Here is the jQuery code:
$(document).ready(function(){
$(".form_errors").hide();
$("#send").on("click",function(){ //the submit button has the id="send"
$(".form_errors").hide(); //these are <p> for each input to show the error
var user=$("input.box");
var data={};
var names=$("input.box").attr("name");
for(i=0;i<user.length;i++){
name=names[i];
value=user[i].val();
data.name=value;
}
$.post('ksite/account',
data,
function(result){
$("div.answer").html(result);
for(i=0;i<user.length;i++){
error_message=<?php echo form_error("?>names[i]<?php ");?>;
$("p#error_"+names[i]+".form_errors").html(error_message).show();
}
}
return false;});
});
form_error is a CodeIgniter function. (I suppose someone who used ci is familiar with).
The form:
<p id="error_user" class="form_errors"></p>
<input type="text" class="box" name="user">
<p id="error_password" class="form_errors"></p>
<input type="password" class="box" name="password">
<input type="submit" id="send">
Is the form tag neccessary ? And if yes,do i have to mention action and method ?
Do I have to specify the type of the response?
And in ksite/account I do:
/* ...... */
if (!this->form_validation->run(''account")) {
echo "The account couldn't be made";
} else {
echo "The account was successfully created ";
}
P.S.Although you may not be familiar with codeigniter, I would appreciate if someone could tell me if the code is correct and what improvements could be made.
Here is what I did.
You have to Ajax for getting data without refreshing the page.
HTML Page
$form = $(form);
var url = $form.attr('action');
dataString = $form.serialize();
$.ajax({
type: "POST",
url: url,
data: dataString,
dataType: "json",
success: function(data) {
$(data).each(function(j,details){
var status = details.status;
var message = details.message;
$('#message_ajax_register').show();
$('#message_ajax_register').html('<div class="alert alert-success">'+message+'</div>');
});
}
});//end of $.ajax**
I am first setting up the rules in my controller method and then validating it.
Controller
public function update_fest()
{
if($this->input->post())
{
$this->form_validation->set_rules('txtgpluswebsite', 'Google Plus Page URL', 'trim|xss_clean|prep_url');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
if($this->form_validation->run() == false){
$message = validation_errors();
$data = array('message' => $message,'status'=>0);
}
else{
$message = $this->add_fest_database();
$data = $message;
}
}
else{
$message = "Fest details are required";
$data = array('message' => $message,'status'=>0);
}
$this->output->set_content_type('application/json');
$json = $this->output->set_output(json_encode($data));
return $json;
}
If validation run is not false, then go to add_fest_database(other function). In that function,
function add_fest_database()
{
$youtubeWebsite = $this->input->post('txtyoutubewebsite');
$gplusWebsite = $this->input->post('txtgpluswebsite');
$this->load->model('model_fest');
$data = array("fest_youtube"=>$youtubeWebsite,"fest_gplus"=>$gplusWebsite);
return data;
}

Categories