Currently I am stock on this scenario on my current function.
Basically, this ajax call will generate list of emoticons, however I want that when a user clicks on a smiley image, the smiley code will be added to message textbox.
Like for example, when user clicks on smiling image, the :-) code will be added to the message box.
My question is, Is it possible to pass the code :-) to a function?
On my current codes, addText(' + key + ') is not working. The value of key is :-). Error says Uncaught SyntaxError: Unexpected token : And when the value is ;) the error is Uncaught SyntaxError: Unexpected token ;
I also have :lol: etc. codes similar to that. Any help will be much appreciated.
$.ajax({
type: "POST",
async: true,
cache: false,
dataType: "json",
url: "./assets/php/scripts.php",
data: {command: 'get-smileys'},
success: function (data) {
$("#smileys").empty();
$("#smileys").append("<br>");
var div_obj = document.createElement("ul");
$(div_obj).addClass('list-inline');
$.each(data, function(key, value) {
$(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" onclick="addText(' + key + ');"><br>' + key + '</div></li>')
$("#smileys").append($(div_obj));
});
$("#smileys-flag").text('1');
$("#loader-chat").hide();
}
});
And here's the function in adding text part:
function addText(text){
var fullMessage = $("#message").val();
$("#message").val(fullMessage + text);
}
The problem is you need to pass them as string literals as given below.
'" onclick="addText(\'' + key + '\');"><br>'
But a better solution will be to use a jQuery event handler instead of a inline one like
$(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img class="smileys" src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" data-smiley="' + key + '"><br>' + key + '</div></li>')
then
jQuery(function ($) {
$("#smileys").on('click', '.smileys', function () {
addText($(this).data('smiley'))
});
})
You need to pass your args as string literals. Then when you are decoding it you can just get the substring you want.
For example:
function takeSmiley(smiley) {
return smiley.substr(1, smiley.length - 2) // Return lol for :lol:
}
takeSmiley(":lol:");
Related
Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!
Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..
Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.
Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.
If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.
When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify
test.xml
<Bock1>
<No>123</No>
<RoomNo>10</RoomNo>
<UpdateTime>1230</UpdateTime>
</Block1>
run.js
$.ajax({
type: "GET",
url: test.xml,
dataType: "xml",
success: function (xml) {
$(xml).find('Block1').each(function () {
var updateTime = $(this).find("UpdateTime").text();
var no= $(this).find("No").text();
var roomNo = $(this).find("RoomNo").text();
var status = no + '<br/>' + roomNo + '<br/>' + updateTime;
});
}
});
$('<div>')
.attr({
'data-role': 'collapsible', 'data-collapsed': 'false', 'data-mini': 'true'
})
.html('<h4>' + item_name + '</h4><p>' + status + '</p>')
.appendTo(collapsibleset);
}
});
I'm using this to generate collapsibleset with xml data,
but status can't correctly fill into
<p> + status + </p>
status will get correctly inside ajax, but can't get to collapsibleset.
I've tried to use global variable, but get same situation.
How could I fill it in correctly?
I'm new to jquery & javaScript,
Thanks for any answers!!!
jQuery.ajax() is expecting string for the URL value.
Therefore your URL just needs wrapping in quotes.
Then your DOM reference of the
$('< div >')
is wrong.
To reference an element in JQuery, you have several options, but the easiest is to give an element an id and then reference that (think CSS)
$('div') would get all divs
$('div#my_id') would get this particular element:
I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}
I am very new to jQuery and AJAX so I apologise if I am being stupid.
I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:
[{"id":1,
"user_id":14,
"title":"The Title",
"thumbnail":"image.jpg",
"summary":"summary of post",
"content":"content info here",
"category":"Graphic Design",
"sub_category":"Adobe Photoshop",
"views":0,
"published":0,
"created_at":"2015-04-16 00:09:57",
"updated_at":"2015-04-16 00:09:57"}, {and so on...}]
The jQuery is:
function retrieveTutorials()
{
$.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
var tutorial = ('')
$.each(data, function(){
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
});
$("#generated-content").empty().append(tutorial);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
The error I am currently receiving is "Uncaught TypeError: undefined is not a function" which refers to the following section
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
Any ideas as to where I am going wrong?
I have used very similar code before which worked fine
try this
var tutorial = $('<div></div>');
You should select any DOM Element and assign it to tutorial variable, something like this:
var tutorial = $('someCSSselector');
There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.
You can do this:
var tutorial = $('<div>');
...
$("#generated-content").empty().append(tutorial.html());
You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.
var tutorial = $('<div class="generatedbox">')
$.each(data, function(){
tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>'))
});
Guys I have a function which uses ajax call to retrieve data dynamically based upon a value in div. Now lastNoticeID value in the function is not getting updated as its not in any loop..thus it keeps repeating the same data..
CODE :
function callMoreData() {
var lastNoticeID = $('#hiddenLastNoticeID').val();
$.ajax({
type: "GET",
url: "/api/values/getnotice?num=" + lastNoticeID,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
BindNotice(value);
});
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
}
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input id="hiddenLastNoticeID" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
As you can see in the code above, I am retrieving value from the above div and then passing it to webApi url... Now this is running fine and on the first scroll I get the values but then the function keeps repeating the same values over and over again i.e. var lastNoticeID is not getting updated. How do I get it to update per scroll event?
btw divNotices has the same html code as BindNotice function.
Use classes instead:
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
And then:
var lastNoticeID = $('.hiddenNotice').last().val();
Or, you could just store the LastNoticeID in a variable:
var lastNoticeID = 0;
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
lastNoticeID = values.LastNoticeID;
}
It would seem that you are adding more elements of the same ID. ID's are supposed to be single instance and Jquery will therefore only grab the first instance in the DOM. (Which is why $('#hiddenLastNoticeID').val(); is the same every time)