So I am trying to submit just an email address using ajax to get people to register and I have no idea why I am getting a 500 internal server error. I am new to ajax calls.
I have tried to follow the following tutorial: http://www.youtube.com/watch?v=TZv5cgua5f0
However I have done as they have said and still if I do a post with values I do not get to the desired controller method. If I do add data to the post then I get an internal server error.
javascript:
$('#email_submit').click(function()
{
var form_data =
{
users_email: $('#users_email_address').val()
};
$.ajax
({
url: 'http://localhost/myZone/NewsLetter/submit',
type: 'POST',
data: form_data,
success: function(msg)
{
alert(msg);
}
});
return false;
});
HTML
<div id="email_newsletter_signup" class="ajax_email_block_signup" >
<h3>Sign up to the newsletter:</h3>
<?php echo form_error('signup_email','<div id="email_error" class="error">','</div>');?>
<h3>email: <input id="users_email_address" type="email" name="signup_email" value="<?php echo set_value('signup_email'); ?>" placeholder="Your email"/> </h3>
<input id="email_submit" type="submit" name="submit"/>
</div>
contoller
public function index()
{
Assets::add_module_js('newsletter','email.js');
//If included will be added
Template::set_block('email_block','email_block');
Template::render();
}
public function submit($email)
{
$success = $this->newsletter_model->set_unverified_email($email);
// if($success === FALSE)
// {
// Template::set_block('newsletter_error','newsletter_error');
// }
// else
// {
// Template::set_block('newsletter_success','newsletter_success');
// }
// Template::render();
return;
}
I have a breakpoint inside the submit and it just wont be hit when I do a post
Thanks
Found my solution. Nothing to do with bonfire but with the codeigniter. It was the CSRF token.
Here is an excellent post about sorting the issue:
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
add csrf token to data before posting
$.ajax({
type: "POST",
url: url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>'}
})
csrf token needs to be send along every request so it needs to be specified by the above echo statements
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",
-----
});
I'm so confusing of this forbidden issue. First of all I checked related stackoverflow posts and googled enough but still have no idea.
Project Details:
- Currently used libraries:
1. Carabiner (https://github.com/bcit-ci/CodeIgniter/wiki)
2. Template (https://github.com/jenssegers/codeigniter-template-library)
3. hmvc
3. instagram_api
- CSRF Protection turned on (I don't want false the protection)
- Followed main posts
1. https://stackoverflow.com/questions/40225908/ajax-post-not-working-codeigniter
2. https://stackoverflow.com/questions/22527412/403-forbidden-access-to-codeigniter-controller-from-ajax-request
- ISSUE: 403 Forbidden ("The action you have requested is not allowed.")
HTML
instagram.php
form_open() function generates hidden field for access token and it is included in ajax posting data.
<input type="hidden" name="csrf_token_localhost" value="3f5887fd41ac4eaa9b558afa7cb4a6de">
...
<?php echo form_open('admin/getInstagramAccessToken', array('id' => 'instagram_settings', 'class' => 'form-horizontal row-border')); ?>
...
<div class="col-sm-8 col-sm-offset-2">
<?php echo form_submit('submit', 'Get my access token', ['class' => 'btn-primary btn btn-get-token']); ?>
</div>
...
<?php echo form_close(); ?>
Javascript
adminscript.js
$('#instagram_settings').submit(function( event ) {
var posting_data = $( this ).serializeArray();
event.preventDefault();
$.ajax({
type: 'POST',
dataType: 'json',
async: true,
cache: false,
data: posting_data,
url: 'admin/getInstagramAccessToken',
success: function(json) {
try{
console.log(json);
}catch(e) {
console.log('Exception while request..');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
},
complete: function() {
console.log('ajax complete');
}
})
Controller
Admin.php
public function getInstagramAccessToken()
{
if ($this->input->is_ajax_request())
{
$response['status'] = 'success';
echo json_encode($response);
}
else
{
// if the request if not ajax then show 404 error page
show_404();
}
}
When I make the csrf protection status false they all work fine. Or when I changed the post type from "post" to "get". But I want to keep the status true and using "post" method.
Dropbox link for two images:
Hidden csrf token field after form load
Posting Datas
https://www.dropbox.com/sh/e93ubgwzv9zir5j/AAA6vf5IWc1m7rtpGWGCpub4a?dl=0
You can by pass this issue by sending the CSRF token with your AJAX request.
This is occurring because you have put CSRF protection in 'ON' mode.
This can be bypassed only if you sent the request through GET or explicitly put CSRF 'OFF', which of course is not advised.
So the solution is to include the CSRF token in your AJAX requests.
Read this post, to know more about putting CSRF tokens on AJAX requests.
EDIT: Ideally, you shoud send the CSRF token through your data option in ajax requests. Check this link for more info
Please add this snippet in your every form which have type POST.
<?php $csrf = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
); ?>
<input type="hidden" name="<?php echo $csrf['name']; ?>"
value="<?php echo$csrf['hash']; ?>" />
this is my ajax code that work perfectly if i show using an id.
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data: "bulan="+ masa +"&tkh_kerja="+tkh_kerja, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
});
}
});
}
return false;
});
the problem is, can the 'cekmasa' value pass to the php.? i need to use that value to do some code in php. is it possible to get the data from ajax? in the same page.
there is no problem when i return value in
<input align='right' type="text" name="tkh_akhir" maxlength="3" id="cek_tarikh" class="span2" readonly/>
no, that's not possible.
once your PHP page is processed by the server it sends the generated output to the client. and there is no PHP executed unless you reload the page or go to another page in your browser.
additional information: that's what often gets confused by people that start working with ajax. you use ajax because you want some "realtime behavior" without having to reload a whole html page. but ajax still is executed by your browser on the clientside.
simplified that's what you want to achieve with ajax, a communication between your browser and the server:
client(browser) <- ajax -> server(PHP)
but what you are asking for would be something like this:
server(PHP) <- ajax -> server(PHP)
which doesn't work and doesn't really make sense if you think about it.
you can call another ajax function to use php file inside success response like below
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data:
{
bulan:masa,
tkh_kerja:tkh_kerja
}, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
$.ajax
({ //Make another Ajax Request
type: "POST",
url: "", //file name
data:
{
}, //data
success: function()
{
}
});
});
}
});
}
return false;
});
You can do one thing. You can store ajax response in php session or cookie and then simply refresh page on ajax response.
//File: ajax_cek_tarikhakhir.php
// Your ajax handling code.
if(isset($__SESSION('ckmasa')){
$ckmasa = $__SESSION('ckmasa');
// use this $ckmasa for your php
}
$ckmasa = $output; // $ckmasa have data which you send to ajax response.
$__SESSION['ckmasa'] = $ckmasa;
echo $ckmasa;
return;
For your jQuery. Do as following.
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data: "bulan="+ masa +"&tkh_kerja="+tkh_kerja, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
// Reload page
location.reload();
});
}
});
}
return false;
});
I have just reloaded your page on ajax response. I have no idea how your server side code. but i tried to give some brief. hope this helps you. I have not tested code written above. Sorry for my bad English.
Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>
I have the following form for users to reset their password it is within the file forgotten.php in the root directory.
<form id="pass_form" action="" method="post" name="pass_form">
<label>Username:</label>
<input type="text" class="blank" name="name" id="name" value="Trader Username" data-default="Trader Username" data-message="Please enter your username..."> *<br>
<input class="sub-btn" type="submit" value="Submit">
</form>
I would like to post the username to inc/sendreset.php so I have the following Ajax in js/scripts.js
$("#pass_form").validator({
offset: [0, 354],
position: 'center left',
messageClass: 'conerror'
}).submit(function(e) {
if (!e.isDefaultPrevented()) {
var form = $(this);
var serdata = form.serialize();
$.ajax({
type: "POST",
url: "sendreset",
data: serdata,
cache: false,
success: function (html) {
log('inside ajax sendreset', this, arguments);
$('#pass_form').fadeOut(400,function(){
if (html=="0") {
} else {
$('#pass_form').html('<p>The password reset instructions have been sent. Please check your email.</p>');
}
$('#pass_form').fadeIn();
});
},
error: function (err) {
log('error inside ajax sendreset', this, arguments);
}
});
//$('#pass_form').fadeOut(400);
e.preventDefault();
}
});
However it does not seem to post the username into the file. The inc/sendreset.php is as follows
<?php
require_once('./library.php');
require_once('./PHPMailer/class.phpmailer.php');
$Trader = new CompanyTrader();
$resetdata = $Trader->resetTrader($_POST['name']);
print_arr($resetdata);
//more php which isn't relevant
?>
I know the file inc/sendreset.php works as when I the file to use $_GET['name'] and i use inc/sendreset.php?name=username the array is returned for the relevant user. It does not work from forgotten.php using Ajax though. Please help!
i really think this is wrong:
url: "sendreset",
try with an relative or absolute url like http://mysite.com