Javascript typeahead after 3 characters - javascript

I want to send a query string to back end after 3 characters, and have the results used for typeahead.
Currently the I get the data back, no error on console, but there is no suggestions in the type ahead. The back end is spring-boot.
It might be something to do with scope of data array but I am not sure.
CODE:
// doc ready....
$('#queryStation').keyup(function() {
var stationName = $(this).val();
if(stationName.length==3){
ajax_search(stationName);
}
});
function ajax_search(stationName){
var stationJson = '{ "name":"' +stationName+ '"}'
$.ajax ({
url: "/station",
type: "POST",
data: stationJson,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
$('#queryStation').typeahead({
source: data
});
}
});
}
and html snip:
<div class="col-md-5">
<label class="control-label control-label-left">Station</label>
<input type="text" class="form-control typeahead" name="query" id="queryStation" placeholder="Type Station" data-provide="typeahead" autcomplete="off">
</div>
The array of objects being sent back in data look like [ {id:237, name:"LAX"},{id:155,name:"SFO"}....
It was working when I used $.get instead of ajax POST:
$.get("/station", function(data) {
console.log(data);
$("[name='query']").typeahead({
source: data,
minLength: 3
});
}, 'json');
The data returned when using $.get looked like [{"id":1,"name":"LAX","}... - I see that the key names now are enclosed in " .
UPDATE
It appears the problem is to do with the way the data is returned from the server:
data = [{"id":113,"name":"LAX"}] // Works - $.get
data = [{id:113,name:"LAX"}] // Does not work - $.ajax with POST
data = "[{"id":113,"name":"LAX"}]" // Does not work - JSON.stringify result
So to get it to work it seems the spring-boot object sent back needs the keys wrapped in quotes. How do do this?

Related

Controller function call from JS- JSON parse error - only in firefox

I have a button, which on click should insert the users into table.
Basically im stuck in calling the controller function from my javascript.
HTML button.
<div class="continue_btton">
<input type="submit" name="submit" id="SaveSettings" value="<?php echo $this->translate('Update'); ?>" class="update bdr_rds2" onclick="if($('input[name=target_criteria]:checked').val() == 'optedin_users')
{
return someFun()
} else
{
return validateForm()
}
">
</div>
UPDATED:
Javascript
function someFun(){
var urlInsert = '#Url.Action("myFunAction")';
$.get(urlInsert, function () {
});
}
Also tried below, but the controller func not calling
function myFunAction(){
var formData = $("#Preference").serialize();
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
dataType: 'html',
success: function (data) {
$('span.targetCount').text($.trim(data));
},
error: function (jqXHR, textStatus, errorThrown) {
var error = $.parseJSON(jqXHR.responseText);
var content = error.content;
console.log(content.message);
if (content.display_exceptions)
console.log(content.exception.xdebug_message);
},
});
}
Controller.php - Doesnt seem to be called
public function myFunAction(){
echo '+++myFUN---';exit;
}
Error:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
Tried dataType as html, json and text. Still same error.
My guess is either your post data or your response object is not considered valid json and that is why Firefox throws an error (maybe Chrome is more forgiving). What you could check is whether the request is send correctly and whether the response from the server actually arrives and whether it is valid json. You should consider returning valid json from your myFunAction method in your controller (instead of just printing a string like you do right now):
public function myFunAction(){
$data = '+++myFUN---';
return new JsonModel([
'data' => $data
]);
}
Check more on how to properly return Json in Zend for example on this blog post here: https://akrabat.com/returning-json-from-a-zf2-controller-action/
Valid json response should have a content-type header set to application/json and have a valid json string in the response body. Zend JsonModel will help you with this.
When you post data you should also set the content-type of the request to application-json, like that the server understands that you are sending a json object with data.
I never use JQuery but I think it is done like this if I am not mistaken:
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
contentType: "application/json",
});

Calling value in PHP from a jQuery serialized array doesn't work

I have an ajax call that sends data from serialized checkboxes (among other) to a php file:
$("#button1").click(function(e) {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['checkboxvalue'] = $('.checkboxes').serialize();
console.log($('.checkboxes').serialize());
$.ajax({
type: "POST",
url: "allgemein.php
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttable").show().html(response);
}
});
});
The html checkboxes look like this (they contain bits of SQL):
<input type="checkbox" class="checkboxes" name="checkb[]" value="SYSTEM LIKE '%system%'">
When I try to call their name via POST in php like
echo $_POST['checkb'];
it's always empty. I tried variations like $_POST['checkb[1]']; or $_POST['checkb[]']; it's always empty.
However when i call the whole array echo $_POST['checkboxvalues']; I get the same as console.log.
I need the values singularily however. How can I do that?

How to turn HTML POST data into JSON?

'recipient.firstName': 'Fred',
'recipient.lastName': 'Johnson'
Is there any elegant way to turn this into:
var recipient = {
firstName: 'Fred',
lastName: 'Johnson
}
Using JS on the frontend? I want to POST JSON but it doesn't seem like that is done very easily with HTML, therefore I want to intercept the POST with jQuery and format it into the JSON I want.
EDIT: I am leaving the original question above for clarity's sake, but if you read closely you will see that the issue I have is not posting the data with AJAX to a REST API. That's very simple and already implemented. What is happening is that I am dynamically building forms using a template engine that I have created, and the forms id and names are built to represent nested data such as recipient.firstName. However, when I receive this data passed as JSON to the API endpoint, I need to transform it programatically from the first format to the second format, which is what the question is actually asking if you read it closely. Sorry for any confusion, the answer I have listed below solves the question.
var recipient = [{firstName: "Fred",lastName: "Johnson"}]
//:: CONVERT TO JSON
recipient = JSON.stringify(recipient);
//:: POST THE DATA
$.post(LINK_url,{post_recipient : recipient },json/*:: json not important, it can be auto guessed. delete ',json' */,function(output){
//var data =jQuery.parseJSON(output);});
______________________________edit_______________________________________
if i get you right this time your output is plan text and you need to convert to json, if so try this.
var recip = JSON.stringify[{ output }];
var data = jQuery.parseJSON(recip);
var viewdata='';
$.each(data, function(key, recipient){viewdata +=
recipient.firstName +" "+recipient.lastName+"<br/>"
})
prompt(viewdata);
With jQuery with a form by Using serializeArray() and forEach and other object:
$(function() {
var recipient = $("#frm").serializeArray();
var output = {}; // Declare an object.
recipient.forEach(function(v, i) {
output[v.name] = v.value; // Assign the current value to the current key.
});
$.ajax({
url: "http://httpbin.org/post",
type: "POST",
data: JSON.stringify(output), // Send the object.
contentType: "application/json",
success: function(response) {
//console.log(response);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="frm" method="post">
firstName:
<br/>
<input id="firstName" name="firstName" type="text" value="Fred" />
<br />lastName:
<br/>
<input id="lastName" name="lastName" type="text" value="Johnson" />
<br />age:
<br/>
<input id="age" name="age" type="text" value="30" />
</form>
In the request, you send:
UPDATE
Now that I know your server side is NodeJs you simply need to learn how to call NodeJS server side methods:
How to send data from JQuery AJAX request to Node.js server
So your approach is just wrong, you have this unnecessarily complex string of data that you want to intercept. Do not intercept anything, send a well formatted HTTP POST from the start, with jQuery or Javascript to your server Controller or API. The signature of your API method should be:
DoSomethingWithRecipient(string firstName, string lastName);
Your recipient should have a userId as well but that is up to you. If you are not using a Server side framework that can parse the incoming the request and map it to your DoSomethingWithRecipient function like PHP or ASP.NET than you your reinventing the wheel for no reason most likely.
Than with jQuery you simply perform an Ajax HTTP Post like so:
var recipient = {
firstName: 'Fred',
lastName: 'Johnson'
}
var json = JSON.stringify(recipient);
$.ajax({
url: '/MyUrl/DoSomethingWithRecipient',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function (result) {
}
});
This is what I am using:
_.forOwn(options, function(value, key) {
if(key.indexOf('.') != -1){
var split = key.split('.')
if( !global[split[0]] ) {
global[split[0]] = {}
}
global[split[0]][split[1]] = value
}
});
Using global as I'm using NodeJS on the backend.
Seems to work so far, I'll report back on if I finally end up using it.

Problems getting json array in php using json_decode

Im trying to pass and return an array to and from a php script, I've tested the json_ecode portion and its working but I can't get the json_decode on the php side.
Javascript
scid_list = [];
$('.filter_on').each(function(){scid_list.push($(this).data("scid"));});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "/scripts/products_filter.php",
success: function(data){
alert(data.join('\n'));
}
});
PHP
<?php
$scid_list=(json_decode($_POST['scid_list'], true));
echo json_encode($scid_list);
exit();
?>
Ive also tried leaving out the true on decode
$scid_list=(json_decode($_POST['scid_list']);
and not decoding it at all
$scid_list=$_POST['scid_list'];
I'm not sure what I'm missing. I've tried playing around with serializing the data too but read I didn't have to if you specify the dataType as json, I tried using stripslashes
Any help is appreciated!
Cheers
I think the problem is that the data you're sending isn't json even though you're specifying it on the Ajax call. As it's only a 2-dimensional array you're getting, why don't you just use Array.join in your JS before doing the post:
var scids = scid_list.join(',');
That would turn it in to a comma separated string. e.g.
"id1,id2..."
You can simplify the Ajax call a bit too:
$.post('/scripts/products_filter.php', {scids: scids}, function(data) {
// process data response here
});
Then in your PHP file you can use explode() to turn it back in to an array:
$ids = explode(",",$_POST["scids"]);
foreach ($ids as $id) {
// Do something with the array of ids.
};
Hope that all makes sense.
Your dataType parameter specifies that you expect JSON data in response, but it does not mean you are sending data as JSON. In your case you are sending an array, therefor in PHP instead of:
$scid_list=(json_decode($_POST['scid_list'], true)); /* WRONG */
you should simply use:
$scid_list=$_POST['scid_list'];
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String The type of data that you're expecting back from the
server.
Alltogether, for given HTML:
<form action="work.php" method="post">
<p><input class="filter_on" data-scid="22" type="checkbox" /> Filter 22</p>
<p><input class="filter_on" data-scid="28" type="checkbox" /> Filter 28</p>
<p><input class="filter_on" data-scid="31" type="checkbox" /> Filter 31</p>
<p><input type="submit" value="Send" /></p>
</form>
and SCRIPT:
$(document).on('ready', function() {
$('form').on('submit', function(e) {
e.preventDefault();
scid_list = [];
$('.filter_on:checked').each(function(i){
scid_list.push( $(this).data("scid") );
});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "work.php",
success: function(data){
alert(data.join('\n'));
}
});
});
});
PHP part is:
$scid_list=$_POST['scid_list'];
echo json_encode($scid_list);
exit();

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

Categories

Resources