Where in laravel 5.2 - javascript

I am trying to retrieve zipcodes from the database where I am getting an error- Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given. I am not sure if my where in query is correct. Thanks in advance.
$countiesList array looks like = ["Beaverhead", "Big Horn",......]
function in the model is:
public static function counties_zip($countiesList)
{
$zipCodes= Zip::select('ZIPCode')
->distinct()
->whereIn('CountyName', $countiesList)
->orderBy('ZIPCode', 'asc')
->get();
return $zipCodes;
}
In the controller:
public function zipCodes(Request $request) {
$zipCodes = Zip::counties_zip($request->counties);
return json_encode($zipCodes);
}
and my jS:
$(".submit").on("click", function(){
myList = [];
$('.select2 option:selected').each(function() {
myList.push($(this).val())
});
$countiesList=myList;
console.log($countiesList);
$.ajax({
type: "get",
url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
data: { counties: $countiesList},
dataType: "json",
success: function (data) {
var htmlText = '';
for ( var i=0;i<data.length;i++ ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<input type="checkbox">' + data[i].ZipCode;
htmlText += '<div>';
}
$(".main-div").append(htmlText);
}
});
});

I think it's because you're using a GET request to pass multiple counties values to your controller, but not using the right counties[] parameter in your request. Currently, if you were to do a dd($countiesList); in your function, you wouldn't get an array, as you're not passing it an array; your passing a single value.
To specify a parameter as an array in a GET request, you'd need to do:
/leads/regions/counties/zipcodes?counties[]=one&counties[]=two...
For every single counties value you're trying to filter down to.
You may want to look into structuring this as a POST request, as
data : {
counties: $countieList
}
should be properly handled as an array of values in a $.post(url, data, function(response){ ... }); or $.ajax(...) request.

In the javascript I used JSON.stringify to convert the javascript array to JSON array. Then in the model I decoded the JSON string using json_decode.
JS:
$(".submit").on("click", function(){
myList = [];
$('.select2 option:selected').each(function() {
myList.push($(this).val())
});
$countiesList=myList;
console.log($countiesList);
$.ajax({
type: "get",
url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
data: { counties: $countiesList},
dataType: "json",
success: function (data) {
var htmlText = '';
for ( var i=0;i<data.length;i++ ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<input type="checkbox">' + data[i].ZipCode;
htmlText += '<div>';
}
$(".main-div").append(htmlText);
}
});
});
Model:
public static function counties_zip($countiesList)
{
$county= json_decode($countiesList, true);
$zipCodes= Zip::select('ZIPCode')
->distinct()
->whereIn('CountyName', $county)
->orderBy('ZIPCode', 'asc')
->get();
return $zipCodes;
}

Related

How to put JSON data into a HTML div?

Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.
function showEspece(espece, categorie, object) {
$.ajax({
type: 'POST',
url: 'getespece.php',
data: {
espece: espece,
categorie: categorie
},
dataType: 'json',
success: function(data) {
console.log(data);
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
<div id="output"></div>
And here is what the variable data contains:
How can I show the variable's content in an HTML div - in a table particularly?
You can use pre tag to display JSON.
var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
$('pre').html(JSON.stringify(data, undefined, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
Your data variable it's a JS object you need to convert it to string or the format you want to show it before calling $('#output').html(data).
You can do something like:
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
console.log(data);
data = JSON.stringify(data)
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
as your json data children are array you can use $.each function:
Example:
var noma = data.NOMA;
var html_append = '';
$.each(noma, function(key,value) {
html_append += value +'<br>';
});
$('#output').html(html_append);
The same code you can use for also data.DATENAISSANCE and data.SEXE
Since your data returned is already in a JSON format, i suggest you to use $.getJSON and change your $_POST by $_GET variables in your getespece.php.
Also, your JSON Objects seems to be kind of not formatted correctly.. If you want to display your "especes" in an HTML table, the right JSON format could be something like this:
{
"Columns": [
"DateDeNaissance",
"Nom",
"Sexe"
],
"Especes": [{
"DateDeNaissance": "05-MAY-15",
"Nom": "Chachi",
"Sexe": "F"
}, {
"DateDeNaissance": "07-JAN-15",
"Nom": "Rafiki",
"Sexe": "M"
}, {
"DateDeNaissance": "17-SEP-17",
"Nom": "Chakra",
"Sexe": "F"
}]
}
Once you have this output from your PHP, change your JS to this:
$.getJSON("getespece.php", {
espece: espece,
categorie: categorie
})
.done(function(json) {
// Build the html Table
var html = "<table>\n";
html += "<thead>\n";
html += "<tr>\n";
// Columns
$.each(json.Columns, function(k, value) {
html += "<th>" + column + "</th>\n";
});
html += "</tr>\n";
html += "<tbody>\n";
// Rows
$.each(json.Especes, function(column, values) {
html += "<tr>\n";
// Cells
$.each(values, function(k, val) {
html += "<td>" + val + "</td>\n";
});
html += "</tr>\n";
});
html += "</tbody>\n";
html += "</table>\n";
$("#output").html(html);
});
var data = {
DATENAISSANCE: [...],
...
}
var root = document.getElementById("output");
var table = element("table");
root.appendChild(table);
var dataName;
for (dataName in data) {
if (data.hasOwnProperty(dataName)) {
var row = element("tr", element("th", dataName));
data[dataName].forEach(function (dataValue) {
row.appendChild(element("td", dataValue));
});
table.appendChild(row);
}
}
// Create a convenient function `element` which creates an element and sets its content
function element(nodeName, content, attributes, eventListeners) {
var node = document.createElement(nodeName);
appendChildren(node, content);
return node;
}
function appendChildren(node, content) {
var append = function (t) {
if (/string|number/.test(typeof t)) {
node.innerHTML += t;
} else if (t instanceof HTMLElement) {
node.appendChild(t);
}
};
if (content instanceof Array) {
content.forEach(function (item) {
append(item);
});
} else {
append(content);
}
}

How to set the data in AJAX success function?

I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?
Here's my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
var html = '<ul>'
for (var i = 0; i < data.Options.length; i++) {
html += '<li>' + data.Options[i] + '</li>';
}
html += '</ul>'
$("#twoColumnOptions").append(html);
$("#twoColumnOptions").data(html);
$("#Options").val(data.Options);
$("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
if (data.ExteriorColor.isInstalled == true)
$("#Exterior_Color").attr("disabled", true);
}
},
error: function(result) {
console.log("Error while fetching data");
}
});
Try to trigger the change you made using .trigger('change') like:
$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();
I implemented something similar in my solution and my code is like this, you need to set the value like this:
success: function (response) {
var array = response;
if (array != '') {
for (i in array) {
$("#district").append("<option value='"+
array[i].Id + "'>" + array[i].DistrictName + "</option>");
}
}
},

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

How can I call ajax array passed from php json encode? zend framework 2

I can't call an arrays passed from the php json encode. I would concatenate 2 select state-contry-city. How can I do this??
This is the code:
I have 2 selects. I send the first value to an action:
php action into my controller:
public function regioniProvinceComuniAction(){
$response = $this->getResponse();
$request = $this->getRequest();
if ($request-> isPost()){
$post_data = $request->getPost();
$regione = (int)$post_data['regione'];
$province = (int)$post_data['province'];
}
if(isset($regione)){
$prov = $this->getProvincia($regione);
}
if(isset($province)){
$com = $this->getComuni($province);
}
$response->setContent(\Zend\Json\Json::encode(array('prov' => $prov, 'com' => $com)));
return $response;
}
This is my js file:
$("select#Regione").change(function () {
var regione = $("select#Regione option:selected").attr('value');
$.ajax({
type: 'POST',
url: '/zf-tutorial/public/regioni-province-comuni',
datatype: 'json',
data: { regione: regione },
success: function (data) {
alert (data);
}
});
});
An example of the alert function is like this:
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
I tried to populate my second select via data.post like this, but the values are "undefined":
success: function (data) {
$('select#Provincia option').each(function(){$(this).remove()});
for(var i=0; i<data.length; i++){
$("select#Provincia").append('<option value="' + data[i].prov.id + '">' + data[i].prov.nome + '</option>');
}
i tried to do
for (var i = 0; i < data.prov.length; i++) {
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
if i set manually the var data, works fine, but with the response data doesn't work. i tried to do:
var prov = data.prov;
$("div#id").html(prov);
but it doesn't work. works only like this:
$("div#id").html(data);
and the output is the same
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
You need to loop through the items in data.prov. Change your for loop to this:
for (var i=0; i<data.prov.length; i++){
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
jsFiddle Demo
EDIT
Solution found in comments: Can you try to change datatype in your $.ajax() call to dataType. I'm not sure if the case is important. Sounds like data is a string and not an object

JQuery Adding elements to a list from parsed JSON

I am trying to parse some JSON and take the elements "startTime" and "endTime" and add them to a list. I am able to receive the JSON successfully, however I am having trouble properly parsing and then looping through to add each instance to the list. Inside of the UL, i would like to create lists for each, like i demo below:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
The HTML where I am trying to insert the LI inside of the UL:
<div data-role="main" class="ui-content" id="headerDate">
<ul data-role="listview" data-inset="true" id="appts">
</ul>
</div>
So basically for each appointment i get back in the JSON, I want to add a new LI with the startTime and endTime.
I am using JQM 1.3.2, and JQUERY 1.8.0.
Thank you
Change this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
Into this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
$.each( json, function( key, value ) {
var agrega = "<li data-role='list-divider'>";
if(key=='startTime')
{
agrega = agrega + value
}
if(key=='endTime')
{
agrega = agrega + ' - ' + value;
}
agrega = agrega + '<span class="ui-li-count"></span></li>';
$('#appts').append(agrega);
});
From your code sample, it seems your problem is that you're trying to look for the startTime property in the wrong place (on this). In your sample, the startTime property should be present on your parsed JSON, so accessing the key there should do the trick:
$('<li data-role="list-divider">' + json.startTime
+ ' - ' + json.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
If the returned JSON is a series of times, then you'll also want to loop through the JSON object as well:
$.each(json, function(key, value) {
if (key === 'startTime') {
// append to the list
}
});
Additional note:
If JSON is what is being returned from the AJAX call, then you shouldn't need to use $.parseJSON on it. JSON objects are JavaScript objects, so you can simply use the returned value and access they keys on it (meaning you can use data.startTime directly instead of parsing it first).
Please find the response below
var ulObject = $("#appts");
var ajaxObject = $.ajax({
type:"POST",
dataType:"json",
url:"" //Provide the URL in the field to be processed.
});
ajaxObject.done(function(msg){
var jsonResponse = $.parseJSON(msg);
var listObjectStart = '<li data-role="list-divider">'
var listObjectEnd = '</li>';
$.each(jsonResponse,function(key,value){
if(key === "startTime")
{
listObjectStart += value;
}
else if(key === "endTime")
{
listObjectStart += '-'+value+'<span class="ui-li-count"></span>';
}
});
listObjectStart += listObjectEnd;
ulObject.append(listObjectStart);
});
Try the following if server send the data back to client in json format.
$.ajax({
url: 'localhost:8080/sample?',
dataType : 'json',
success: function(data){
$("#appts").append('<li data-role="list-divider">' + data.startTime
+ ' - ' + data.endTime + '<span class="ui-li-count"></span></li>');
},
error: function(){
alert('There was an error in communication.');
}
});

Categories

Resources