I'm trying to pass a field name dynamically to my function in order for my form to use autocomplete. I then call this function in my page but I keep getting an error and I think it's because it's trying to get the column property literally as opposed to dynamically.
In PHP I could do something like {$fieldName}. Is there a javascript equivalent? Or am I getting this horribly wrong?
// Call to function index.php
inputSuggetion('input.search', 'http://myapi.com/endpoint', 'title')
// Function
function inputSuggestion(element, endPoint, fieldName) {
$(element).on("keydown", function(event) {
$.ajax({
type: 'GET',
dataType: "json",
data: {
q: $(element).val()
},
url: endPoint,
success: function(data) {
var apiCollection = [];
$.each(data, function(key, value) {
apiCollection.push(value.fieldName);
});
$(".autocomplete").autocomplete({
source: apiCollection
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
}
Thanks!
If I'm right then you want to get the value of field 'title' from your Json data and this field name 'title' will be passed to the function dynamically.
In this case your syntax to get the value from json is wrong.
you just need to change following line of code:
from :
apiCollection.push(value.fieldName);
to :
apiCollection.push(value[fieldName]);
let me know in case of any issue.
Related
I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },
I've created two calls, one is ajax call to my controller, and other one is jquery call. I've did both just to check if my HTML would update once I trigger the event... But none of these methods update my HTML (it stays the same way). Here are the methods:
Method #1:
$("#btnSearch").click(function(){
var startDate = $.trim($("#startDate").val());
var endDate = $.trim($("#endDate").val());
$.post("/history/list",{'startDate':startDate,"endDate":endDate},function(data){
var result = $('<div />').append(data).find('#historyList').html();
$('#historyList').append(result);
console.log(result);
// the result is displayed correctly in the console...
});
});
// This is supposed to update my HTML in the browser now, but it's not showing anything new...
Method #2:
$('#btnSearch').click(function () {
console.clear();
$.ajax({
url: "/history/list",
data: {
startDate: $('#startDate').val(),
endDate: $('#endDate').val(),
},
type: "GET",
dataType: "html",
success: function (data) {
var result = $('<div />').append(data).find('#historyList').html();
$('#historyList').append(result);
console.log(result);
// the result is displayed correctly in the console...
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
},
complete: function (xhr, status) {
//$('#showresults').slideDown('slow')
}
});
});
None of these methods update my HTML once the call is finished and data is returned... The data object holds the HTML as the result, and I'd like that HTML in the data object replaces everything what is in div tag under id #historyList.. What am I doing wrong here?
P.S. I'm using chrome browser (if this is a useful information)
I don't get the result. Could you use .html, like so:
$('#historyList').html(data);
Or the whole code like this.
$('#btnSearch').click(function () {
console.clear();
$.ajax({
url: "/history/list",
data: {
startDate: $('#startDate').val(),
endDate: $('#endDate').val(),
},
type: "GET",
dataType: "html",
success: function (data) {
$('#historyList').html(data);
console.log(result);
// the result is displayed correctly in the console...
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
},
complete: function (xhr, status) {
//$('#showresults').slideDown('slow')
}
});
});
Make sure $('#historyList') is not an empty array and exists in the DOM. If it exists,
$('#historyList').html(data);
should solve the problem.
Correct me, if my understanding of the question is wrong.
I want to reuse a javascript function using a scala template so I would only have to pass a different success/failure function, but I don't seem to be able to able to pass a javascript function to a scala template.
Please note I'm veeeeerry new to this and don't even know if what I am doing is possible.
This is kind of what I'm trying to achieve:
#(formId: String, success: JavaScript, fail: JavaScript)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success()
/*console.log("save succesfull, progress!")
alert('Save successfull, now move on!');*/
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
//if fails
#fail()
/*console.log(jqXHR.responseText);
var errors = JSON.parse(jqXHR.responseText);
console.log(errors);
alert('Woops, something went wrong: ' + jqXHR.responseText);*/
}
});
e.preventDefault();
});
</script>
How it would be used:
#snippets.ajaxFormSubmit("#form",
function()
{
alert("Save successfull, now move on!");
},
function()
{
alert("Save failed!");
}
)
You can pass any content to a template via Html type.
#(formId: String, success: Html, fail: Html)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#fail
}
});
e.preventDefault();
});
</script>
In a client view you can user it as follows:
#successFunc = {
alert("Save successfull, now move on!");
}
#failureFunc = {
alert("Save failed!");
}
#snippets.ajaxFormSubmit("#form", successFunc, failureFunc)
I'm trying to send from JavaScript, by using jQuery, via AJAX, a string that might contain one or more URL's.
That text will be recieved by a CodeIgniter controller.
I'm having some errors. Sometimes it's a 404 error or other times is a 406 error depending on the way I send the data.
Right now I send it like this:
var dsPost = encodeURIComponent(base64_encode(postContent));
$.ajax({
url: "/posts/createTextPost/" + dsPost,
type: "POST",
data: "userIdWall" + "=" + userIdWall,
success: function(data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
The base64_encode fn is the phpjs implementation.
In the CI controller I do this:
public function createTextPost($dsPost) {
$dsPost = base64_decode(urldecode($dsPost));
}
The thing is, the data can be saved to the database but I can't understand why the 404 error.
Any ideas?
Thanks.
base64_encode() function sometimes add / in encoded string so the Codeigniter action method behaving like second paramameter
In case Encoded String like: qwqw221#1223/dds*(ewfd)
than issue with ci
string part after "/" char behaving like 2nd param
'*' is not allowed char
So you should use GET query string instead of CI param
Like
url: "/posts/createTextPost/?crypt=" + dsPost
And get query sting in CI controller action
public function createTextPost() {
$dsPost = base64_decode(urldecode($this->input->get("crypt")));
}
I would recommend to add the dsPost to your data in the AJAX call, instead of adding it as a parameter to the url:
$.ajax({
url: "/posts/createTextPost/",
type: "POST",
data: { "dsPost": dsPost, "userIdWall", userIdWall },
success: function(data, textStatus, jqXHR) {
// Yippie!
},
error: function (jqXHR, textStatus, errorThrown) {
// Bhuhuhu....
}
});
...and then update your CI controller to work with the posted object instead of the input parameter:
public function createTextPost() {
$dsPost = base64_decode( urldecode( $this->input->post('dsPost') ) );
userIdWall = $this->input->post('userIdWall');
}
You have to send the content through ajax data like below.
$.ajax({
//double check your url setting in this way in case you have diffrent setting for index.php then remove the index.php
url: "<?=base_url()?>.index.php/posts/createTextPost/",
type: "POST",
data: {
"dsPost": dsPost,
"userIdWall", userIdWall
},
success: function(data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
then in your controller
public function createTextPost() {
$dsPost = base64_decode( urldecode( $this->input->post('dsPost') ) );
$userIdWall=$this->input->post('userIdWall');
I hope it will help.
So, thanks for the ideas but the answer can be found here:
PHP/Apache Error:406 Not Acceptable
I quote the answer given there:
Your website is generating error if any user input item is starting
with either http:// or https:// .
When I try with a link starting with http:// I got a 406 Not
Acceptable :
http://onkore.us/?blah=http://www.google.com
It is fine when I try this :
http://onkore.us/?blah=www.google.com
I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id