Correct URL in ajax call JavaScript - javascript

I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?

On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design

Related

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>");
}
}
},

Load specific html page with href and GET request response

First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks

Can't retrieve data in table from json

I am trying to load data into table using JQuery and AJAX but when I click on the button data is not retrieved. I have done coding as shown below:
var globalgrid;
Here I am going to call json url and try to display it in the table.
function loadgrid() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://instatalk.in/sip/GetApprovedUsersList?page=1&limit=10',
success: function(griddata) {
globalgrid = griddata.lines;
// remove all data - but the headers!
$("#gridtable").find("tr:gt(0)").remove();
if (globalgrid.length === 0) {
$('#errormsg').html('Sorry, <strong>no</strong> rows returned!');
return;
}
for (var i = 0; i < globalgrid.length; i++) {
var line = globalgrid[i];
// insert after last row!
$('#gridtable > tbody:last').append('<tr><td>' + line.Id + '</td><td>' + line.AccountId + '</td><td>' + line.Name + '</td><td>' + line.IsFranchiseUser + '</td></tr>');
}
},
error: function(data, errorText) {
$("#errormsg").html(errorText).show();
}
});
}
I am getting the table heading only. When I click on the button I want data to be retrieved from the json data. I don't know where I am going wrong. Please do help.
This is my json file:
{"results":[{"Id":17,"AccountId":"5737329468","Name":"Martin (Nigeria)","IsFranchiseUser":false},{"Id"
:16,"AccountId":"3644824444","Name":"Deep Patel","IsFranchiseUser":false},{"Id":15,"AccountId":"4692068407"
,"Name":"Jacob (kiribati)","IsFranchiseUser":false},{"Id":14,"AccountId":"4650982975","Name":"sebin John
(spain)","IsFranchiseUser":false},{"Id":13,"AccountId":"2855375107","Name":"Jassi want(new jersey)"
,"IsFranchiseUser":false},{"Id":12,"AccountId":"6242007588","Name":"Moussa","IsFranchiseUser":false}
,{"Id":11,"AccountId":"3075258818","Name":"srkrbm (saudi arab)","IsFranchiseUser":true},{"Id":10,"AccountId"
:"3615509810","Name":"Om Saini","IsFranchiseUser":false},{"Id":9,"AccountId":"9251133143","Name":"swati
mohandas","IsFranchiseUser":false},{"Id":8,"AccountId":"8143395019","Name":"babu Kuppu","IsFranchiseUser"
:false}],"totalAccounts":16}
This line: globalgrid = griddata.lines;
According to your Json data format, you should use griddata.results.

Code is not executing when i pass a parameter

I have the problem that my code is not performing the ajax call when i pass a search parameter. I added several console.log to my code! So that you i hope you can easily comprhened my code:
icd: function(icd,id,search){
if(!(typeof search === 'undefined')){
var urls = "icd?search=" + search;
console.log("1");
}else{
if(icd == 2){
var urls = "/icd/icd2/" + id;
}if(icd == 3){
var urls = "/icd/icd3/" + id;
}
console.log("2");
}
console.log("3");
$.ajax({
dataType: "json",
url: SERVER + urls,
headers: {"X-TOKEN": TOKEN},
success: function(data,status,xhr){
console.log("4");
var array = $.map(data['icd'], function (field, i) {
return '<tr data-link="'+ field.id +'"><td>' + field.nummer + '</td><td>' + field.bezeichnung + '</td></tr>';
});
$('#DiagnosenTable').html(array.join(''));
$('#side-panel2 .breadcrumb').html($('<li/>').html($('<a/>',{href: '#',text: 'Alle',click: function(){Diagnose.start()} })));
if(icd == 2){
$('#side-panel2 .breadcrumb').append($('<li/>', {class: 'active',text: data['icd1'].bezeichnung}));
}
if(icd == 3){
$('#side-panel2 .breadcrumb').append($('<li/>').html($('<a/>',{href: '#',text: data['icd1'].nummer,click: function(){Diagnose.icd(2,data['icd1'].id)} })));
$('#side-panel2 .breadcrumb').append($('<li/>', {class: 'active',text: data['icd2'].bezeichnung}));
}
$('#DiagnosenTable tbody').eq(0).children('tr').each(function(){
$(this).click(function(){
if(icd == 2){
Diagnose.icd('3',$(this).attr('data-link'));
}else{
$('#inputCode').val($(this).children('td')[0].innerHTML);
$('#inputBez').val($(this).children('td')[1].innerHTML);
$('#TextEntry').val($(this).children('td')[0].innerHTML);
}
});
});
},
error: function(xhr, status, error) {
ErrorHandler.connection(xhr,status,error);
console.log("5");
}
});
console.log("6");
}
When i first tried to execute my code, i noticed that when i pass a search parameter, the ajax call isnt performed (because 4 or 5 is not printed to the console)Here is a screenshot from my console:
I cant explain me why this happens! What do i wrong?
One of these URLS is not like the other
var urls = "icd?search=" + search;
var urls = "/icd/icd2/" + id;
var urls = "/icd/icd3/" + id;
Do you see why the search URL does not work? It is different than the others. AKA: It is missing the a leading /.
var urls = "/icd?search=" + search;
^

Set div html to display contents of array

i'm doing a simple php chat application that sends the message input to the server via ajax and saves it in a text file. Now after it retrieves all data in the text file and sends it to the client in an array form via ajax. Now what i want to do is populate a div called "chat-box" with the contents of the array as html but nothing happens and ii don't get any errors in firebug apart from ": undefined".
This is the code:
<script type="text/javascript">
// setInterval(function(){alert("Hello");}, 5000);
$(document).ready(function() {
function getchat(messages)
{
var chat = $(".chat-box").html();
for (var i=0; i < messages.length; i++)
{
var msg = messages[i].split(':');
var name = msg[0];
var post = msg[1];
$(".chat-box").html(chat + "<div class='bubble'>" + name + " : " + post + "</div>");
}
}
$("#btnPost").click(function() {
var msg = $("#chat-input").val();
if (msg.length == 0)
{
alert ("Enter a message first!");
return;
}
var name = $("#name-input").val();
var chat = $(".chat-box").html();
//$(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");
var data = {
Name : name,
Message : msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(chat) {
getchat(chat)
}
});
});
});
</script>
Try this instead for updating the chat box:
var index = messages[i].indexOf(':');
var name = messages[i].substring(0, index);
var content = messages[i].substring(index + 1);
var $newMessage = $('<div>')
.addClass('bubble')
.text(name + " : " + content);
$(".chat-box").append($newMessage);
If this doesn't work, check if the messages returned by the server are correct by using console.log(messages).
You said the div is called chat-box. Perhaps it's this:
$(".chat-box")
maybe you intended to write it as $("#chat-box")

Categories

Resources