Display Multidimensional array via ajax in laravel - ajax

The form displays data from DB for the entry to be edited. One of the columns is a 2D Array and I do not know how to pass the data.
Tried the normal AJAX display codes
The data coming via COntroller is:
res.credential looks like
[
[
"Facebook","x11111111",
"q1111111","w11111111"
],
[
"Linkedin","x222222222",
"q222222","w222222222222"
],
[
"Twitter","x333",
"q3333333","w3333333"
]
]
The AJAX looks like:
$('.password-edit-btn').on('click', function (){
var client_sel = $(this).data('id');
if (client_sel) {
$.ajax({
type: "GET",
url: "/get_password_data?id="+client_sel,
success: function (res) {
if (res) {
console.log(res.credential);
$("#edit-password-client").empty();
$("#edit-password-client").append('<option>'+ res.client +'</option>');
$('#edit-password-remarks').val(res.remarks);
}
// The problematic area is below
if (res.credential) {
$.each(res.credential, function (key, value) {
console.log(value)
$(".add-hf-accounts").append()
});
}
}
});
}
});
Simply display the data in the div with class "add-hf-accounts".

$.each(res.credential, function (key, value) {
for(var i=0;i<value.length;i++)
{
if(i==0)
{
$(".add-hf-accounts").append('<h2>'+value[i]+'</h2>');
}
$(".add-hf-accounts").append('<li>'+value[i]+'<li>');
}
});
Try It...Will be Work Fine

Thanks a lot for the help guys.
The problem was in parsing. I had to use JSON.parse and then it worked beautifully. Below is the final working answer.
if (res.credential) {
$.each(JSON.parse(res.credential), function (key, value) {
$(".add-hf-accounts").append('<div class="hidden_event"><div class="form-group col-sm-2"><label>Account</label><select class="form-control" name="account[]"><option value="'+ value[0] +'"> '+ value[0] +'</option></select></div><div class="form-group col-sm-3"><label>URL</label><input type="text" class="form-control" placeholder="Accoutn URL" name="url[]" value="'+ value[1] +'"></div><div class="form-group col-sm-3"><label>Username</label><input type="text" class="form-control" placeholder="User Name" name="user[]" value="'+ value[2] +'"></div><div class="form-group col-sm-3"><label>Password</label><input type="text" class="form-control" placeholder="Password" name="password[]" value="'+ value[3] +'"></div><div class="form-group col-sm-1 acc-btn"> <br><button class="btn btn-danger remove " type="button"><i class="glyphicon glyphicon-remove"></i></button></div></div>');
});
}

Related

ajax post failed but controller & db data ok

im posting data to controller with partailview the controller receive valid data & store it in my DB but:
im getting ajax failed Msg.
im not getting a TempData displayed as expected ( i have one for results OK and else for error).
Im not sure where to put my finger on .
Index View
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
function SubmitREgNews() {
var data = {
userName: $("#name").val(),
UserMail: $("#email").val(),
TermsOk: $("#bOk").val(),
};
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) {
alert('Successfully received Data ');
console.log(result);
},
error: function() {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
}
Partial view
#if (#TempData["ErrorMes"] != null)
{
#TempData["ErrorMes"]
}
#if (#TempData["regOk"] == null)
{
<div class="row">
<div class="col-md-4">
<form id="studenteForm" novalidate class="needs-validation">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="userName" class="control-label"></label>
<input asp-for="userName" class="form-control" id="name" required />
</div>
<div class="form-group">
<label asp-for="UserMail" class="control-label"></label>
<input asp-for="UserMail" type="email" class="form-control" id="email" /> </div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" id="bOk" asp-for="TermsOk" /> #Html.DisplayNameFor(model => model.TermsOk)
</label>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" onclick="SubmitREgNews();">Add </button>
</div>
</form>
</div>
</div>
</div>
}
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
controller
public IActionResult _RegNews()
{
return PartialView();
}
[HttpPost]
public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews )
{
var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
if ( ModelState.IsValid && IsNewUser==null)
{
joinNews.JoinId = Guid.NewGuid();
joinNews.JoinDate = DateTime.Now;
_context.Add(joinNews);
await _context.SaveChangesAsync();
TempData["regOk"] = "You are register";
return View("home/index");
}
else
{
TempData["ErrorMes"] = "You are allready register";
}
return PartialView("_RegNews", joinNews);
}
The reason you are getting ajax failed Msg may be that you are returning the wrong path "home/index". Paths in one controller that call a page in another controller should use "../home/index".
Also, Ajax doesn't change page elements. If you want to redirect to another page you can use Url.Action.
Like this:
Controller:
[HttpPost]
public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews)
{
var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
if (ModelState.IsValid && IsNewUser == null)
{
joinNews.JoinId = Guid.NewGuid();
joinNews.JoinDate = DateTime.Now;
_context.Add(joinNews);
await _context.SaveChangesAsync();
TempData["regOk"] = "You are register";
return Json(new { redirectUrlOne = Url.Action("Index", "Home")});
}
else
{
TempData["ErrorMes"] = "You are allready register";
return Json(new { redirectUrlTwo = Url.Action("_RegNews", "NewsLetter") });
}
}
And your ajax:
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function (result) {
alert('Successfully received Data ');
if (result.redirectUrlOne !== undefined) {
window.location.replace(result.redirectUrlOne);
} else {
window.location.replace(result.redirectUrlTwo);
}
console.log(result);
},
error: function (error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
If you don't want to use Url.Action, you can also do not use Ajax, using the Form Tag Helper to submit data is the same. You can check the details in this official document.

Laravel only gets checked items from checklist

I have form with multiple input data and checklists but in controller I'm just getting checked items and no result for unchecked items.
This is what I get
"send_mail" => array:2 [▼
0 => "on"
1 => "on"
]
This is what I need
"send_mail" => array:2 [▼
0 => "off"
1 => "on"
2 => "off"
3 => "on"
]
Blade
<form enctype="multipart/form-data" action="{{route(''xxxxxxxx)}}" method="POST">
#csrf
#method('POST')
<input name="name" id="name" class="form-control">
<div class="form-check">
<input class="form-check-input" checked type="checkbox" name="send_mail[]">
<label class="form-check-label">Send Mail</label>
</div>
<div id="newRows">
// new rows (same as above) will add here by javascript
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
Controller
public function test(Request $request) {
dd($request->all());
}
By default <input type="checkbox"> won't return if it hasn't been checked.
A classic method of fixing this is to duplicate the checkbox with a hidden input:
<input type="hidden" name="send_mail" value="0" />
<input type="checkbox" name="send_mail" value="1" />
This would require, however, moving away from the array of checkboxes you currently have.
The alternative is to use Javascript to submit your form.
I faced a similar scenario back then. I managed to solve it by using JavaScript (jQuery to be specific) to submit the form.
I wrote up a reusable function to append the unchecked items.
Reusable function:
const prepareJQCheckboxFormData = (jQForm, jQSerializedFormData, checkboxNameAttr) => {
let name;
let data = [];
checkboxNameAttr?.substr(-2) === "[]"
? name = checkboxNameAttr
: name = `${checkboxNameAttr}[]`;
let hasItem = false;
jQForm.find("input[name='" + name + "']")
.add(jQForm.find("input[name='" + name?.substr(0, name.length - 2) + "']"))
.each(function () {
if (($(this).attr("checked") === true) || $(this).is(":checked")) {
hasItem = true;
}
});
if (!hasItem) {
jQSerializedFormData.push({
name, value: [""]
});
}
$(jQSerializedFormData).each(function (i, field) {
if (field.name !== name?.substr(0, name.length - 2)) {
data.push(field);
} else {
data.push({
name: `${field.name}[]`,
value: field.value
});
}
});
return data;
};
Form submission:
Assuming that the form 'id' is 'mail-form'
const form = $("#mail-form");
const btnSave = $("#mail-form button[type='submit']");
btnSave.click(function (e) {
e.preventDefault();
$.ajax({
type: form.attr("method"),
url: form.attr("action"),
processData: false, // Important for multipart-formdata submissions!
contentType: false, // Important for multipart-formdata submissions!
cache: false,
data: prepareJQCheckboxFormData(form, form.serializeArray(), "send_mail[]"),
success: function (response) {
// ...
},
error: function (jqXHR) {
// ...
},
beforeSend: function () {
// ...
}
});
});
<div class="form-check">
<input type="checkbox" name="send_mail[]">
<label>Name1</label>
</div>
<div class="form-check">
<input checked type="checkbox" name="send_mail[]">
<label>Name2</label>
</div>
(another 2 div tag here)

How do I post the value of a radio button to a database using AJAX?

I want to be able to post the value of a radio button to a database, without having to submit the form, hence why I have attempted this using 'on change'.
$("input:radio[name=q1_MC]").on("change", function () {
var dunno1 = $(this).serialize();
$.ajax({
url: "get_response.php",
type: "POST",
data: dunno1,
success: function (data) {
console.log("working)";
},
error: function (request, status, error) {
console.log(request.responseText);
}
});
});
My console.log does show when I click one of my radio buttons.
Inside get_response.php I have:
<?php
require("db_connection.php");
if((isset($_POST['your_name']) {
$yourName = $conn->real_escape_string($_POST['your_name']);
$q1_MC = $conn->real_escape_string($_POST['q1_MC']);
$q2 = $conn->real_escape_string($_POST['q2']);
$q3 = $conn->real_escape_string($_POST['q3']);
$q4 = $conn->real_escape_string($_POST['q4']);
$q5 = $conn->real_escape_string($_POST['q5']);
$q6 = $conn->real_escape_string($_POST['q6']);
$q7_MC = $conn->real_escape_string($_POST['q7_MC']);
$q8 = $conn->real_escape_string($_POST['q8']);
$sql="INSERT INTO commenttable (name, q1_MC, q2, q3, q4, q5, q6, q7_MC, q8) VALUES ('".$yourName."','".$q1_MC."', '".$q2."', '".$q3."', '".$q4."', '".$q5."', '".$q6."', '".$q7_MC."', '".$q8."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
} else {
echo "Thank you! Your feedback is appreciated";
}
}
?>
HTML:
<input type="radio" name="q1_MC" value="Excited"> Excited
<input type="radio" name="q1_MC" value="Optimistic"> Optimistic
<input type="radio" name="q1_MC" value="Indifferent"> Indifferent
<input type="radio" name="q1_MC" value="Nervous"> Nervous
<input type="radio" name="q1_MC" value="Sceptical"> Sceptical
if((isset($_POST['your_name']) will only be true when you submit the whole form. In your case you appear to be posting just the key/value of the radio button.
EG:
$("input:radio[name=q1_MC]").on("change", function() {
var dunno1 = $(this).serialize();
console.log(dunno1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label><input type="radio" name="q1_MC" value="test1" />test1</label>
<label><input type="radio" name="q1_MC" value="test2" />test2</label>
</form>

Laravel AJAX getting all records in one JSON request

i am trying to edit record in my database using ajax, my code is working fine, but i have to mention each column by name, how i can get same result without typing all columns name.
Edit Controller: i am using columns name [efirst,esecond etc] i want to pass everything from database without mentioning name
public function edit($id)
{
$teacher = Teacher::find($id);
return response()->json([
'status' => 'success',
'id' => $teacher->id,
'efirst' => $teacher->efirst,
'esecond' => $teacher->esecond,
]);
}
Edit.js:
jQuery(document).ready(function($) {
$(".table-container").on("click touchstart", ".edit-btn", function () {
$.ajax({
type: "GET",
url: "lists/" + $(this).attr("value") + "/edit",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
beforeSend: function() {
$('#esecond-not-found').remove();
},
success: function (data) {
$("#update-id").val(data['id']);
$("#update-efirst").val(data['efirst']);
$("#update-esecond").val(data['esecond']);
$('#update-form').show();
},
});
});
});
View:
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" name="id" id="update-id">
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<label for="esecond">esecond body</label>
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<div class="">
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
A teacher object can be passed instead of writing every table field
return response()->json([ 'status' => 'success', 'teacher' => $teacher ]);
So in order for this code to work the id of the form needs to match the name of the column
let teacher = Object.entries(data.teacher);
teacher.forEach(item => { $("#"+item[0]).val(item[1]); });
Let's say we have four inputs
<input id="data1" type="text" class="form-control">
<input id="data2" type="text" class="form-control">
<input id="data3" type="text" class="form-control">
<input id="data4" type="text" class="form-control">
and you do this
success: function (data) {
let teacher = Object.entries(data.teacher);
teacher.forEach(item => {
console.log(item)
$("#"+item[0]).val(item[1]);
});
}
the console log gives the following
(2) ["data1", "test1"]
(2) ["data2", "test2"]
(2) ["data3", "test3"]
(2) ["data4", "test4"]
you get an array of arrays that you can loop where the index position 0 is your input id and the index position 1 is your value.

variable is not found inside ajax

<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.

Resources