I am currently learning jquery AJAX, i am trying to change my standar php post to AJAX but not working, it's still prosses with php, not AJAX. Not even in the console show anything. Can anyone check my code ?
I am using Codeigniter. And you can asume the php part is working fine ..
HTML :
<form action="<?=base_url()?>operator_pt/unggah/unggah_semua" id="unggahsemua" method="POST" name="unggahsemua" role="form">
<?php foreach($data as $rod)
$tahun = $rod->id_smt;
$jurusan = $rod->id_sms;
?>
<div id="form-tahun" class="form-group">
<input type="hidden" class="form-control" id="tahun" name="tahun" value="<?php echo $tahun;?>">
</div>
<div id="form-jurusan" class="form-group">
<input type="hidden" class="form-control" id="jurusan" name="jurusan" value="<?php echo $jurusan;?>">
</div>
Sedang Mengunggah :
<div id="statmhs"> </div>
<div id="statidmhs"> </div>
<div id="statdsnpt"> </div>
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
JS :
$(document).ready(function() {
$('#unggahsemua').submit(function(event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun' : $('input[name=tahun]').val(),
'jurusan' : $('input[name=jurusan]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
.fail(function(data) {
console.log(data);
});
event.preventDefault();
});
});
You have errors in your Javascript code..
You missed the closing brackets before the .fail method. Also you had an extra comma after the last entry of your formData object
Try changing to this:
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
You have to stop default execution of form submit as you have to do it with ajax.
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
event.preventDefault() //<------- Add this line
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
});
});
if you use form action="" method="POST" name="" role="form", make sure in config.php change $config['csrf_protection'] = TRUE; to FALSE.
But, if you want to set it TRUE you must use form_open()
Related
Hello guys i am desperate i am not getting completly this syntax / concept of Ajax.
I have 2 forms on my page. Based on the value of the hidden field a certain logic in my controller will be executed. Its simple actually -- i thought. I am trying to pass an array from my ajax to my controller and then passing it back to my view. I know it doesnt make much sense. But i am trying to understand how that works. The first logic gets executed but the other one gets me this error:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input
Why is that ? Can you guys please give me an advice.
Update
I tried not to put the whole code and just reduce it to the main question. But since it caused confusion of the rootcause i will show the whole code of the parts which might be relevant. I edited the question to the below.
BLADE
<center>
<div class="col-md-12">
<h3>xlsx, xls, ods, csv to Text</h3>
<form id="xlsForm" enctype="multipart/form-data">
#csrf
<input type="file" name="excelfile" />
<input name ="loadSubmit" id="loadSubmit" type="submit"/>
<input type ="hidden" name="load" value="0">
</form>
</div>
</center>
<div class ="row">
<div class ="col-md-3">
<div class="container mt-5">
<h2 id="words" class="mb-4">Skills found</h2>
</div>
<form id="xlsFormUpdate" enctype="multipart/form-data">
<input type ="hidden" name="load" value="1">
<div id="inner">
</div>
<input name ="updateSubmit" id="updateSubmit" type="submit"/>
</form>
</div>
<div class ="col-md-9">
#include('layouts.partials.datatable')
</div>
</div>
Controller:
if ($request->input('load') == '0') {
//some code -- this works fine
return response()->json($data); //This data can be send - no problem
} elseif (($request->input('load') == '1')) {
$data = $request->post('checkbox_array');
return response->json($data); // i tried json_encode too .. not working.
}
Jquery code
$(document).ready(function(){
$('#xlsForm').submit(function uploadFile(event){
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function (response) {
$("#inner").empty();
$.each(response,function(index,value){
$("#inner").append
('<div class="row">' +
'<div class="col-xs-2">'+
'<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]" checked > <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
'</div>'+
'<div class="col-xs-1">'+
'<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
'</div>'+
'</div>');
});
}
});
});
$('#xlsFormUpdate').submit(function uploadFile(event) {
event.preventDefault();
var checkbox_array = [];
$('input[type=checkbox]').each(function (index,value) {
if (this.checked)
{
checkbox_array.push(1);
}
else {
checkbox_array.push(0);
}
});
let checkbox_s = JSON.stringify(checkbox_array)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: "POST",
data: {checkbox_array:checkbox_s},
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('The Response is ' + response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('jqXHR is : ' + jqXHR
+ 'textStatus is : ' + textStatus
+ ' errorThrown is : ' + errorThrown);
},
})
});
});
When using ajax submit event to send data to controller, the data in the field data: {checkbox_array:checkbox_s}, will be send to the controller. Since the input field load was never sent, the elseif (($request->input('load') == '1')) clause was never true and the controller was never going into that section and was never returning the right response. The data had to be changed like this var my_datas JSON.stringify({mydata:checkbox_array, load: "1"}); and then in ajax the data could be send like data:my_datas. In controller the field load can then be processed.
Here is my view:
<div class="form-group col-md-3">
<label class="sup col-md-12 control-label">Employees</label>
<?php
if(isset($hiddenEmpArray)){
if(is_array($hiddenEmpArray)){
foreach($hiddenEmpArray as $hiddenEmpArraySingle){
echo '<input type="hidden" name="selectall[]" id="selectall" value="'. $hiddenEmpArraySingle. '">';
}
}
}
?>
</div>
Javascript:
$('#form').submit(function(e){
e.preventDefault();
var selectall =$("#selectall").val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>",
data: {selectall:selectall},
success: function (data) {
//alert(data);
},
error: function () {
alert("Server Error! Please try again later.");
}
});
});
Here I want to Submit this form through javascript.Here selectall is an array.When I Submit the form,Only One value is received .How Can I pass this array through javascript.Please help me
The serialize() method creates a URL encoded text string by
serializing form values.
$('#form').submit(function(e){
e.preventDefault();
var formId = $(this).attr('id');//getting form id
$.ajax({
type: "POST",
url: "<?php echo base_url()?>",
data: $('#' + formId).serialize(),//jquery id selector for the form
success: function (data) {
//alert(data);
},
error: function () {
alert("Server Error! Please try again later.");
}
});
});
you can just use this
var selectall = $("input[name='selectall[]']").map(function(){return $(this).val();}).get();
and then in success just do console.log(data);
you may use jquery each function to collect data
var selectall=[];
$.each($("input[name='selectall[]']"), function(){
selectall.push($(this).val());
});
I am submitting a form with JavaScript.
Here is my form:
<form id="rolesSelectForm" class="stdform" action="" onsubmit="return submitForm()">
<p>
<label>Select User</label>
<span class="field">
<select name="selectUser" id="selectUser">
#foreach (var item in Model.Users)
{
<option value="#item.Id">#item.UserName</option>
}
</select>
</span>
</p>
<p class="stdformbutton">
<button class="submit radius2" type="submit">Save</button>
</p>
And here is my script:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
//Shows the success message
function showSuccessMessage(data) {
alert(data);
}
Now when I click the button, the page does refresh and I never get my alert.
In chrome its at least makes the ajax post request but in Firefox, it just reloads the page before the post is even made.
From what I read if I made my form return the JavaScript function, it would not reload. However this is not my case.
From what I read if I made my form return the java script function it would not reload.
No. You have to return false.
This is typically done by returning the return value of the function, and then returning false from that function. A lot of the time this will be done conditionally (since often you will be testing the user input to make sure it is OK before allowing the form to submit.)
You don't have a return statement in your function.
Please add return false in function
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
return false;
}
this is javacript and ajax dont know what is error i tried this without ajax its working but with ajax not working.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#User_Name").val();
var email = $("#User_Email").val();
var mobno = $("#User_Email").val();
var landlineno = $("#user_MobileNo").val();
var proprTd = $("#propertyids").val();
var dataString = 'User_Name='+ name + 'User_Email=' + email + 'User_Email=' + mobno + 'user_MobileNo=' + landlineno + 'propertyids=' + proprTd;
if(name=='' || email=='' || mobno=='' || landlineno=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "SaveContactDetails.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
this is html code
dont know what is error i tried this without ajax its working but with ajax not working.
<form method="post" name="form" >
<input type="hidden" name="propertyid" id="propertyids" value="<?php echo $Propid ?>" >
<input id="individual" name="rdoiam" value="individual" type="radio" class="input-38-ieo">
Individual
<input id="Agent" name="rdoiam" value="individual" type="radio" class="input-38-ieo">
Agent
<input id="builder" name="rdoiam" value="individual" type="radio" class="input-38-ieo">
Builder <span id="ReqTypeErrorDiv12968081_left" class="span-41-ieo"></span> </li>
<li class="li-42-ieo">
<label class="label-43-ieo">Name<span class="span-37-ieo">*</span></label>
:
<input type="text" id="User_Name" name="User_Name" maxlength="30" class="input-45-ieo11">
<input type="text" class="input-276-ieo11" id="Mobileno" name="user_MobileNo" maxlength="12">
<input type="text" class="input-276-ieo11" id="userLandlineno" name="userLandlineno" maxlength="12">
</form>
and this is php file
<?php
include 'config.php';
$iam ="";
$User_Name="";
$User_Email="";
$user_MobileNo="";
$user_LandlineNo="";
$txtMessage="";
if (isset($_POST['rdoiam']))
{
$iam =$_POST['rdoiam'];
}
if (isset($_POST['User_Name']))
{
$User_Name=$_POST['User_Name'];
}
if (isset($_POST['User_Email']))
{
$User_Email=$_POST['User_Email'];
}
if (isset($_POST['user_MobileNo']))
{
$user_MobileNo=$_POST['user_MobileNo'];
}
if (isset($_POST['userLandlineno']))
{
$user_LandlineNo=$_POST['userLandlineno'];
}
if(isset($_POST['txtMessage']))
{
$txtMessage=$_POST['txtMessage'];
}
$Propid=$_POST['propertyid'];
$iam =trim($iam);
$User_Name=trim($User_Name);
$User_Email=trim($User_Email);
$user_MobileNo=trim($user_MobileNo);
$user_LandlineNo=trim($user_LandlineNo);
$txtMessage=trim($txtMessage);
$str="Call sp_SaveContactDetails('".$iam."','".$User_Name."','".$User_Email."','".$user_MobileNo."','".$user_LandlineNo."','".$txtMessage."','".$Propid."')";
// $sql=mysql_query($str);
if(!mysql_query($str))
{
die('Error:'.mysql_error());
}
else
{
}
?>
You are missing & in your data string:
var dataString = 'User_Name='+ name + 'User_Email=' + email + 'User_Email=' + mobno + 'user_MobileNo=' + landlineno + 'propertyids=' + proprTd;
It has to be:
var dataString = 'User_Name='+ name + '&User_Email=' + email + '&User_Email=' + mobno + '&user_MobileNo=' + landlineno + '&propertyids=' + proprTd;
Thats why its not sending proper data, as you want. Of course, you can serialize all your data...
Also you should be using encodeURIComponent because if the user adds a & or =, your string is going to break.
var dataString = 'User_Name='+ name + 'User_Email=' + email + 'User_Email=' + mobno + 'user_MobileNo=' + landlineno + 'propertyids=' + proprTd;
That is not how you build a querystring
The string looks like User_Name=nameUser_Email=email...., you are missing the & between each. Also you should be using encodeURIComponent because if the user adds a & or =, your string is going to break.
Look at jQuery serialize() it does all of it for you.
Or just use serialize function, you are using jQuery anyway.
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( this ).serialize();
$.ajax({
type: "POST",
url: "SaveContactDetails.php",
data: formData,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
});
Before sending ajax you can always add your validation.
You can use this
<script>
$(function () {
$('form#person').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'show.php',
data: $('form').serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
});
</script>
I am Trying to upload file without reloading or redirecting page to other page.
I have tried...
upload.php
<form enctype='multipart/form-data' action='/' method='POST' class="AjaxSubmit" id='newwork' name='newwork'>
Choose New Work<br />
<input name='uploadednewwork' type='file' /><br />
<button id="btnFrmPost1" class="button" onclick="up()" >New Work</button>
</form>
script.js
function up() {
$('#btnFrmPost1').click(function() {
event.preventDefault();
var $form = $(this);
var url = "/subpages/upload_new_work.php";
var data = $form.serialize()
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: data,
success: function (resp) {
var jdata = eval(resp);
var $jAlrtSuccess = $('<div>' + jdata.responseText + '</div>');
$($jAlrtSuccess).dialog({modal:true});
},
error: function (xhr, status, error) {
var $jAlrtError = $('<div>' + xhr.responseText + '</div>');
$($jAlrtError).dialog({modal:true});
}
});
return false;
});
}
I have tried all this code...
but i wont get result...
can any one please tell me how to solve this problem...