How to detect new line in result of ajax? - javascript

I get result of PartialViewResult in asp.net mvc project via ajax.When Model is null ! I pass nothing in partialViewResult but I get newline in result of ajax.How can i detect it by js?
var GetSuns = function (btn) {
$('body').append('<div class="WrapProgress"><img class="loadingimg vertical-middle-image" src="/Content/Travelo/images/travelenter_process_Art.gif" /></div>');
var urn = $(btn).data('urn');
var method = $(btn).data('method');
$.ajax({
url: '/art/ShowTime',
data: { s: urn, method: method },
type: "POST",
success: function (result) {
if (result.trim) {
console.log("1"+result+"1")
$('.WrapProgress').remove();
$('#ModalSuns .modal-body').html(result);
$('#ModalSuns').modal('show');
} else {
$('#Modal').modal('show');
}
},
error: function (jqXhr, textStates, errorThrown) {
console.log(errorThrown);
$('.WrapProgress').remove();
}
});
};

The issue with your code is anyway the result.trim need to changed to result.trim() inorder to trim the result string for any trailing spaces or linebreaks.
In order to detect line breaks in your code
text = `
`;
numberOfLineBreaks = (text.match(/\n/g)||[]).length;
console.log(numberOfLineBreaks)

Related

How to get variable from one Ajax function to work in another Ajax function

I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);

Adding JSON object items to DIVs with same class

I've looked up a lot of examples and none really answered my question. I'm trying to iterate through a JSON file and add certain items to divs on my page.
Here's the code I've written so far. This code returns all the item values of all objects into the different divs instead of appending each item to its div. You can ignore the first for loop, it's just for adding id's to each div. I've also created an example fiddle.
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams',
dataType: 'json',
success: function(data) {
console.log(data);
var name = document.getElementsByClassName("player-name");
var gamename = document.getElementsByClassName("gamename");
var viewcount = document.getElementsByClassName("viewcount");
var date = document.getElementsByClassName("date");
var numItems = $('.stream').length;
var i = 1;
$('.stream').each(function(i) {
$(this).attr('id', (i + 1));
i++;
});
$('.stream').each(function(i, obj) {
$.each(data.streams,function(index,item) {
$(name).append(item.channel.name);
$(gamename).append(item.channel.game);
$(viewcount).append(item.viewers);
$(date).append(item.created_at);
});
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
var name = $(".player-name"); // jQuery's $ cares about your fingers
var gamename = $(".gamename");
var viewcount = $(".viewcount");
var date = $(".date");
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams',
dataType: 'json',
success: function(data) {
console.log(data);
$.each(data.streams,function(index,item) {
// now use .eq(index) over your elements collections
name.eq(index).append(item.channel.name);
gamename.eq(index).append(item.channel.game);
viewcount.eq(index).append(item.viewers);
date.eq(index).append(item.created_at);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});

how to handle encoding while sending value via ajax

In wordpress, i am making an ajax call and sending this value
blow = \'blo\
But when i receive the value at the server end it has one \ extra
blow = \\'blo\
As you can see a \ is extra. I used urldecode but it is also giving me the same result
Please help me to find out what i am doing wrong
this is my script here are i serialize the form and in form i place in a text box blow = \'blo\
jQuery.ajax({
type: 'POST',
beforeSend: function () {
var Container = jQuery("#mainContainer");
var height = Container.height();
var width = Container.width();
jQuery('#le_form_container').css("display", "none");
Container.append('<div class="loadingOverlay" style="width: 100%; height: 100%;" ><img class="ajaxLoading" src="' + url + '/leasson_Evalution/images/ajax_loader_blue_512.gif" /></div>');
},
url: ajaxcontactajax.ajaxurl,
data: {
action: 'ajaxcontact_send_mail',
values: jQuery('#le_form').serialize().replace(/\+/g, '%20')
},
success: function (data, textStatus, XMLHttpRequest) {
//console.log(data);
if (data == 0) {
jQuery("#le_SucessDialog").html('');
jQuery('#le_SucessDialog').append("<p>Data is Submited</p>"); //alert(data is );
jQuery("#le_SucessDialog").dialog({
draggable: true
});
//console.log("tenp");
jQuery("#le_form")[0].reset();
//console.log("tenp");
}
//console.log(data);
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
complete: function () {
jQuery('#le_form_container').css("display","block");
jQuery("#mainContainer").find(".loadingOverlay").hide().remove();
jQuery("#le_form")[0].reset();
}
});}
Use stripslashes:
$values = stripslashes($_POST["values"]);
Try this : reset your variable with the escape
escape(blow)

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Can we have two or more function call in jquery-ajax success

I have request to webservice and getback xml result as output , In sucess function can i have a two or more function call
function searchLocationNear() {
// Get the radius using jQuery
var radius = $("#radiusSelect").val();
// Make Ajax call using jQuery
$.ajax({
type: "POST",
data: "keyword1=&streetname=&lat=&lng=&radius=" + radius,
url: "WebService1.asmx/GetList",
success: function (response) {
var xml = GXml.parse(response.xml);
....
.....
var marker=createmarker(...........);
var sidebar cretesidebar(.........);
},
error: function (response) {
alert(response);
}
});
}
function createmarker(..........)
{}
function createsidebar(....)
{
}
Yes you can. Don't forget the assignment symbol var sidebar = cretesidebar(...);

Categories

Resources