how to handle encoding while sending value via ajax - javascript

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)

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

jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>

How to detect new line in result of ajax?

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)

Adding a delay to JQuery keyup() after Ajax call

I'm having a quite tough problem and I'm not sure how to approach it. I have a few textboxes in a row and I need to fill in these textboxes. Every time a textbox is filled, I grab the value and make an Ajax call that uses the value. The response determines whether or not that very textbox is colored red or green(using the Jquery css() function).
Now here's the problem. Let's say I have 5 textboxes in a row. Let's say I type 1-tab, 2-tab, 2-tab, 1-tab, 1-tab. All of this very fast. 1-tab, for example, means I type 1 followed by the Tab button to move to the next textbox. I realized that if I go too fast, some of the textboxes don't get updated and their colors do not change. I assumed this is due to the ajax taking some time to process.
I thought about the problem and came up with an idea that might solve the problem. That is add a delay after each Ajax call and then tab to the next. I search around S.O and found this solution. However, it's not really working for me(basically it breaks and the JS doesn't work at all).
Here's a snippet of my AJAX. I stripped it down and removed the unnecessary pieces of code.
$( ".myTextbox" ).keyup(function() {
//Defining my variables here
$.ajax({
//Perform First Ajax request
$.ajax({
//Perform Second Ajax Request
});
});
});
Here's the solution I tried using what I found from S.O, but it doesn't work.
var timer = null;
$( ".myTextbox" ).keyup(function() {
clearTimeout(timer);
timer = setTimeout(
function(){
.ajax({
//Perform First Ajax request
$.ajax({
//Perform Second Ajax Request
});
});
}, 200);
//Defining my variables here
});
Now, there are 2 options:
My logic is wrong about delaying the tab key. Could there be some better logic to overcome my initial problem?
I'm using the solution posted above wrongly.
Hope to get some constructive answers.
Thanks.
EDIT: Here's the full code, upon request.
$( ".getqty" ).keyup(function() {
var split = this.id.split(":");
var color = split[0];
var size = split[1];
var prodID = split[2];
var $this = $(this);
var value = $this.val();
var stock = 0;
var price = split[3];
var originalProd = split[4];
var dataStock = $this.attr("data-stock");
if(value.length > 0){
value = parseInt(value);
}else{
value = "";
}
$.ajax({ //create an ajax request
type: 'POST',
url: 'includes/add.php',
dataType: 'html', //expect html to be returned
data:'color='+color+'&size='+size+'&prodID='+prodID+'&qty='+value+'&originalProd='+originalProd+'&dataStock='+dataStock,
success: function(response){
if(response == "breakOut"){
$this.css('background-color', '#F87171').css('border', '1px solid #B42C2C');
$("#"+originalProd+"-"+color).text("Not enough in stock.").css('color', '#B42C2C');
$("#"+originalProd+"-totalPrice").text("");
}else{
stock = response;
if((value > 0 && value <= stock) || (value > 0 && dataStock == 'yes')){
$this.css('background-color', '#66CF66').css('border', '1px solid #277230');
}else{
$this.css('background-color', '#fff').css('border', '1px solid #ccc');
}
var count = 0;
$("."+color+"-" + originalProd).each(function(){
if($(this).val() == 0){
count = count + 0;
}else{
count = count + parseFloat($(this).val(), 10);
}
});
//Single Item Total
if(count > 0){
var totalPrice = (price * count).toFixed(2);
$("#"+originalProd+"-"+color).text(count + " - " + totalPrice.toString().replace(/\./g, ',') + " Eur").css('color', '#CCC');
}else{
$("#"+originalProd+"-"+color).text("");
}
$.ajax({ //create an ajax request
type: 'POST',
url: 'includes/cart.php',
dataType: 'html', //expect html to be returned
success: function(response){
if(response > 0){
$("#cart_price").text("Cart: "+response.toString().replace(/\./g, ',')+ " Eur");
}else{
$("#cart_price").text("Cart:0,00 Eur");
}
},
error:function (xhr, ajaxOptions, thrownError){
// alert(thrownError);
}
});
if(pathname == 'mycart.php'){
location.reload();
}
}
},
error:function (xhr, ajaxOptions, thrownError){
//alert(thrownError);
}
});
You should use the change event instead of keyup. From the docs:
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus.
When you press tab your elements will change focus quickly and maybe the keyup event will not be fired for that input text with the right value content.
So try:
$( ".getqty" ).change(...)
Update:
Since the change event just fires when the input text loses focus, you could write instead:
$( ".getqty" ).on('input', function() {
var $this = $(this);
var value = $this.val();
if (value.length > 0) {
value = parseInt(value);
}
else {
value = "";
}
$.ajax({
type: 'POST',
url: 'data.txt',
dataType: 'text',
success: function(response){
$this.css('background-color', '#66CF66').css('border', '1px solid #277230');
$.ajax({
type: 'POST',
url: 'data.txt',
dataType: 'text',
success: function(response){
$("#cart_price").text("Cart: "+response.toString().replace(/\./g, ',')+ " Eur");
},
error:function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
},
error: function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
});
Or with pure javascript event listeners:
var elemList = document.getElementsByClassName('getqty');
for (var i = 0; i < elemList.length; i++) {
elemList[i].addEventListener('input', function(e) {
var $this = $(e.target);
var value = $this.val();
if (value.length > 0) {
value = parseInt(value);
}
else {
value = "";
}
$.ajax({
type: 'POST',
url: 'data.txt',
dataType: 'text',
success: function(response){
$this.css('background-color', '#66CF66').css('border', '1px solid #277230');
$.ajax({
type: 'POST',
url: 'data.txt',
dataType: 'txt',
success: function(response){
$("#cart_price").text("Cart: "+response.toString().replace(/\./g, ',')+ " Eur");
},
error:function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
},
error: function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
});
}
You can try this to delay on keyup
$('input').keyup(function() {
delay(function(){
alert('Time elapsed!');
}, 1000 );
});

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

Categories

Resources