Code is not executing when i pass a parameter - javascript

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;
^

Related

WordPress REST API Ajax show more posts button

PHP/HTML:
<ul id="load-more-div"></ul>
<a id="load-more" data-ppp="<?php echo get_option('posts_per_page'); ?>">load more</a>
JavaScripts:
(function($) {
// Grab the load more button, since I only want to run the code if the button is on the page
var loadMoreButton = $("#load-more");
if (loadMoreButton) {
// Get the posts_per_page number set in Reading Options
var ppp = loadMoreButton.data("ppp");
// Initialize function
var loadPosts = function(page) {
var theData, loadMoreContainer, errorStatus, errorMessage;
// The AJAX request
$.ajax({
url: "/wp-json/wp/v2/posts",
dataType: "json",
data: {
// Match the query that was already run on the page
per_page: ppp,
page: page,
type: "post",
orderby: "date"
},
success: function(data) {
// Remove the button if the response returns no items
if (data.length < 1) {
loadMoreButton.remove();
}
// Create a place to store exactly what I need
// Alternatively, the response can be filtered to only return the needed data, which is probably more efficient as the following loop wont be needed
theData = [];
// Get only what I need, and store it
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
}
// Grab the container where my data will be inserted
loadMoreContainer = $("#load-more-div");
// For each object in my newly formed array, build a new element to store that data, and insert it into the DOM
$.each(theData, function(i) {
loadMoreContainer.append(
'<li><a href="' +
theData[i].link +
'">' +
theData[i].title +
"</a></li>"
);
});
},
error: function(jqXHR, textStatus, errorThrown) {
errorStatus = jqXHR.status + " " + jqXHR.statusText + "\n";
errorMessage = jqXHR.responseJSON.message;
// Show me what the error was
console.log(errorStatus + errorMessage);
}
});
};
// Since our AJAX query is the same as the original query on the page (page 1), start with page 2
var getPage = 2;
// Actually implement the functionality when the button is clicked
loadMoreButton.on("click", function() {
loadPosts(getPage);
// Increment the page, so on the next click we get the next page of results
getPage++;
});
}
})(jQuery);
This is the trouble part, it doesn't remove the link.
// Remove the button if the response returns no items
if (data.length < 1) {
loadMoreButton.remove();
}
Console errors when click the load more link after reaching the end of posts:
400 Bad Request The page number requested is larger than the number of pages available.
I found two ways to solve it:
###Using data attribute
Get the max number of pages in the template, assign it to a data attribute, and access it in the scripts. Then check current page against total page numbers, and set disabled states to the load more button when it reaches the last page.
PHP/HTML:
<ul id="ajax-content"></ul>
<button type="button" id="ajax-button" data-endpoint="<?php echo get_rest_url(null, 'wp/v2/posts'); ?>" data-ppp="<?php echo get_option('posts_per_page'); ?>" data-pages="<?php echo $wp_query->max_num_pages; ?>">Show more</button>
JavaScripts:
(function($) {
var loadMoreButton = $('#ajax-button');
var loadMoreContainer = $('#ajax-content');
if (loadMoreButton) {
var endpoint = loadMoreButton.data('endpoint');
var ppp = loadMoreButton.data('ppp');
var pages = loadMoreButton.data('pages');
var loadPosts = function(page) {
var theData, errorStatus, errorMessage;
$.ajax({
url: endpoint,
dataType: 'json',
data: {
per_page: ppp,
page: page,
type: 'post',
orderby: 'date'
},
beforeSend: function() {
loadMoreButton.attr('disabled', true);
},
success: function(data) {
theData = [];
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
}
$.each(theData, function(i) {
loadMoreContainer.append('<li>' + theData[i].title + '</li>');
});
loadMoreButton.attr('disabled', false);
if (getPage == pages) {
loadMoreButton.attr('disabled', true);
}
getPage++;
},
error: function(jqXHR) {
errorStatus = jqXHR.status + ' ' + jqXHR.statusText + '\n';
errorMessage = jqXHR.responseJSON.message;
console.log(errorStatus + errorMessage);
}
});
};
var getPage = 2;
loadMoreButton.on('click', function() {
loadPosts(getPage);
});
}
})(jQuery);
###Using jQuery complete event
Get the total pages x-wp-totalpages from the HTTP response headers. Then change the button states when reaches last page.
PHP/HTML:
<ul id="ajax-content"></ul>
<button type="button" id="ajax-button" data-endpoint="<?php echo get_rest_url(null, 'wp/v2/posts'); ?>" data-ppp="<?php echo get_option('posts_per_page'); ?>">Show more</button>
JavaScripts:
(function($) {
var loadMoreButton = $('#ajax-button');
var loadMoreContainer = $('#ajax-content');
if (loadMoreButton) {
var endpoint = loadMoreButton.data('endpoint');
var ppp = loadMoreButton.data('ppp');
var pager = 0;
var loadPosts = function(page) {
var theData, errorStatus, errorMessage;
$.ajax({
url: endpoint,
dataType: 'json',
data: {
per_page: ppp,
page: page,
type: 'post',
orderby: 'date'
},
beforeSend: function() {
loadMoreButton.attr('disabled', true);
},
success: function(data) {
theData = [];
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
}
$.each(theData, function(i) {
loadMoreContainer.append('<li>' + theData[i].title + '</li>');
});
loadMoreButton.attr('disabled', false);
},
error: function(jqXHR) {
errorStatus = jqXHR.status + ' ' + jqXHR.statusText + '\n';
errorMessage = jqXHR.responseJSON.message;
console.log(errorStatus + errorMessage);
},
complete: function(jqXHR) {
if (pager == 0) {
pager = jqXHR.getResponseHeader('x-wp-totalpages');
}
pager--;
if (pager == 1) {
loadMoreButton.attr('disabled', true);
}
}
});
};
var getPage = 2;
loadMoreButton.on('click', function() {
loadPosts(getPage);
getPage++;
});
}
})(jQuery);
The problem appears to be an invalid query to that endpoint so the success: function() is never being run in this circumstance.
Add to All API Errors
You could add the same functionality for all errors like this...
error: function(jqXHR, textStatus, errorThrown) {
loadMoreButton.remove();
....
}
Though that may not be the desired way of handling of all errors.
Test for Existing Error Message
Another option could be to remove the button if you receive an error with that exact message...
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText === 'The page number requested is larger than the number of pages available.') {
loadMoreButton.remove();
}
....
}
but this would be susceptible to breaking with any changes to that error message.
Return Custom Error Code from API
The recommended way to handle it would be to return specific error code (along with HTTP status code 400) to specify the exact situation in a more reliable format...
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusCode === '215') {
loadMoreButton.remove();
}
....
}
Here's an example on how to configure error handling in an API: Best Practices for API Error Handling
Return 200 HTTP Status Code
The last option would be to change the way your API endpoint handles this type of "error"/situation, by returning a 200 level HTTP status code instead, which would invoke the success: instead of the error: callback instead.

Correct URL in ajax call 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

Ajax call jsonp from PHP

Hi guys so i made a code that parses a CSV file into a JSON ARRAY with PHP. So when you go to this URL you get the PHP output:
http://www.jonar.com/portal/mynewpage.php
Now i used this code to append my JSON ARRAY to HTML but now things have changed since i am using PHP i am not sure how to use it and what to do differently.
Also my ajax call is always empty which is weird..
$.ajax({
type: 'GET',
url: 'http://www.jonar.com/portal/mynewpage.php',
dataType: 'jsonp',
success: function(response) {
alert(response);
}
});
I used this to append my JSON ARRAY but now if i can get the response do i use the same code or will it have to be altered?
$.each(results.data.slice(1), // skip first row of CSV headings
function(find, data) {
var title = data.title;
var link = data.link;
var date = data.date;
var type = data.type;
var where = data.where;
var priority = data.priority;
if (priority == '1') {
$('ul.nflist').prepend($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
} else if (where == 'pp', 'both') {
$('ul.nflist').append($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
}
});
the reason i used PHP is to avoid cross domain issue
Thanks for the help guys!

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Defining default jQuery tab based on URL

I have a jQuery search script that uses tabs for the user to define the search type they want. A tab is selected as the default by using $('#type_search').click(); however this causes a problem when refreshing a results page. If a different search type is selected and then the page is refreshed, the default tab is automatically selected so it doesn't return the correct results even though the page URL says it is correct.
My question is, how can I define the default tab from the section in the URL if a query is active and if there is no active query use the default tab? I hope you can understand what I'm saying.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#type_search').click();
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
Ah, I had that problem too. It's pretty simple. On page ready you just take the anchor from the URL and simulate a click.
$(document).ready(function() {
url = document.location.href.split('#');
$('#'+url[1]).click();
});

Categories

Resources