Code igniter validation- Ajax, error:function work while validation->run is true - ajax

Hi I try to make validation form with ajax. When Textbox is empty, There is no problem everything works fine and give right errors. But when I fill in form Ajax else is not working and it goes to error:function . Please could you help!
When I enable dataType:"JSON",
I see output
false
Basvuru:1379 {isim: " İsim Zorunludur!", soyad: " Soyad Zorunludur!", emailadresi: " Email Adresi Zorunludur!", ilce: "", il: "", …}
When I disable dataType:"JSON", ı could see console.log(data) of post datas otherwise goesto error:function
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo $data=json_encode(array("status" => TRUE));
}
}
View Ajax:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success:function (data) {
// var obj = $.parseJSON(data);
// $('#data1').html(data);
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
console.log(data.status);
// alert(data.sonuc);
if(data.status){
console.log("false");
}
else{
console.log("true");
console.log(data);
}
},
error:function(data){
console.log("error");
}
});
}
model:
function basvuru_ekle($data)
{
print_r($data);
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}

Remove print_r() in insert function and try this:
function save() {
var url;
if (save_method == 'add') {
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
} else {
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
}
},
error: function(data) {
console.log("error");
}
});
}

I checked to find the exact problem.As Alex said problem was because of Print_r() in modal. After I erased it ,now it works fine.
After fixed the problem.
view:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
$('#modal_form').modal('hide');
location.reload();// for reload a page
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 404) { alert('AJAX page not found.');
}
else {
alert('AJAX Error: ' + textStatus + ': ' + errorThrown); }
}
});
}
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo json_encode(array(
"status" => TRUE,
));
}
}
model:
function basvuru_ekle($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}

Related

woocommerce ajax call using a template part

I have set up a filter for products using ajax. It works fine when using a string as response but not when using a template part.
See below the part of the query
$qry = new WP_Query($args);
$responses = '';
if ($qry->have_posts()) :
while ($qry->have_posts()) : $qry->the_post();
$responses .= wc_get_template_part( 'content', 'product' );
//$responses .= '<h2 class="entry-title">'.get_the_title().'</h2>';
endwhile;
$response = [
'status'=> 200,
'found' => $qry->found_posts
];
else :
$response = [
'status' => 201,
'message' => 'No posts found'
];
endif;
$response['content'] = $responses;
die(json_encode($response));
and below is the ajax call
function get_posts($params) {
$container = $('#container-async');
//$content = $container.find('.content');
$content = jQuery('.products');
$status = $container.find('.status');
$products = $('.products');
$status.text('Loading posts ...');
$.ajax({
url: ajaxurl.ajax_url,
data: {
action: 'do_filter_posts',
nonce: ajaxurl.nonce,
params: $params
},
type: 'post',
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {
if (data.status === 200) {
$content.html(data.content);
console.log(data.content);
}
else if (data.status === 201) {
$content.html(data.message);
}
else {
$status.html(data.message);
}
},
error: function(MLHttpRequest, textStatus, errorThrown) {
$status.html(textStatus);
console.log(MLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
},
complete: function(data, textStatus) {
msg = textStatus;
if (textStatus === 'success') {
msg = data.responseJSON.found;
console.log(data);
}
$status.text('Posts found: ' + msg);
console.log(data);
console.log(textStatus);
}
});
}
In the inspect mode is see the following feedback
SyntaxError: Unexpected token '<', "<li class="... is not valid JSON
Am I calling the template wrong? or do i need to do anything else first?
The ajax function is working when using the return string $responses .= '<h2 class="entry-title">'.get_the_title().'</h2>';
How do I make it work when using the template part?
Thanks in advance!

Get post meta in the Ajax not working in Wordpress

I am doing an Ajax call and return the value. The post id is coming. But when i tried with this code, It is return blank
function visa_status() {
$postid = $_POST['appid'];
// args
$args = array(
'numberposts' => 1,
'post_type' => 'cpt_15',
'meta_key' => 'application_number',
'meta_value' => $postid
);
$metaarry = array();
// query
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$posti = get_the_ID();
endwhile;
//echo $posti;
echo get_post_meta( $posti, 'given_name');
exit();
}
In the above code, $posti is coming. But get_post_meta() is not working.
This is my JS part
onStepChanging: function (event, currentIndex, newIndex) {
if ( newIndex === 1 ) {
jQuery('.wizard > .steps ul').addClass('step-2');
appId = jQuery('#appid').val();
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: my_ajax_object.ajax_url,
data: {
'action': 'visa_status',
'appid': appId,
},
success: function (msg) {
console.log(msg);
}
});
} else {
jQuery('.wizard > .steps ul').removeClass('step-2');
}
if ( newIndex === 2 ) {
jQuery('.wizard > .steps ul').addClass('step-3');
} else {
jQuery('.wizard > .steps ul').removeClass('step-3');
}
return true;
},
Is there any mistake i have done. Please help me in this.
Try this
$given_name = get_post_meta( $posti, 'given_name', true );
echo $given_name;
OR Try this
echo get_post_meta( $posti, 'given_name', true );
Check here what get_post_meta function returns based on 3rd parameter.

laravel ajax request not print when i add html code in controller

In my controller when I remove the html from the code and take message then it works fine but when I used it will give error
POST http://localhost/buyWatch/public/addwatch 500 (Internal Server Error)
/*******************************************************
Ajax code here:
<script>
insertdata();
function insertdata(){
$(document).ready(function() {
$('#form_output').hide();
$("#watch-form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax( {
url:"{{ route('add_watch.postdata') }}",
method: "POST",
data:formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
if(data.error.length > 0)
{
$('#form_output').show();
var data=data.error ;
var errors = data.responseJSON;
//var error_html = '';
$('.alert ul').html(errors);
/* for(var count = 0; count < data.error.length; count++)
{
error_html += data.error[count];
$('.alert').html(error_html);
}//for loop end*/
// $('#form_ul').html(error_html);
}//if condition
else{
console.log(data.success);
$('.alert').html("sucess fully updated");
$("#watch-form")[0].reset();
}//else end here
}
});
});
});//end document
}//insertData end function
</script>
Controller here:
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'watch_name' => 'required',
'watch_price' => 'required',
'watch_quantity' => 'required',
'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image2' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image3' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'watch_size' => 'required',
'discription' => 'required',
]);
if($request->ajax())
{
/// $error_array = array();
$success_output = array();
if ($validation->fails())
{
foreach($validation->messages()->getMessages() as $field_name => $messages)
{
// $error_array[] = $messages;
$error_array = '<li>'.$messages.'</li>';
}
}else{
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}
}
Can u give us the response of XPOST http://foobar/addWatch ?

Ajax with laravel Post returning

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
Update your ajax header, according to this:
$.ajaxSetup({
headers: {
accepts: "application/json; charset=utf-8",
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The possibilities of this issue is CSRF token and missing route.

stop page reloading when using ajax

I've created a wordpress plugin to vote on a post, using ajax.
When you click the 'vote' link the jquery popup works, your vote is added but then the page reloads
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$user_id = get_current_user_id();
date_default_timezone_set('GMT+2');
$dateVoted = get_user_meta($user_id, 'date');
$today = date('d M Y');
if ($dateVoted === $today){
//Already Voted
echo '<script language="javascript">';
echo 'alert("already voted")';
/*
echo 'alert("User ID: ' . $user_id . '")';
echo 'alert("Date Voted: ' . $dateVoted . '")';
echo 'alert("Today: ' . $today . '")';
*/
echo '</script>';
}else{
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
update_user_meta( $user_id, 'date', $today );
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/video-of-the- day/my_voter_script.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
I also have a jquery file:
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
}
else {
alert("Your vote could not be added")
}
}
});
})
});
why is the ajax not working?
Try this
jQuery(".user_vote").click( function(e) {
e.PreventDefault();
});

Resources