JQuery replacewith not working after Ajax call - javascript

Im doing a AJAX call and once I get the response, I want to replace a submit button with a label...But this is not working. I get the alert msg ie; the response from the Ajax call but the replacewith command fails.
Can you please tell me what is the mistake Im doing..
Replacewith command
$( this ).closest( 'tr' ).find( 'input:label' ).replaceWith("<label for=\'success\'>SUCCESS</label>");
Code:
$("#table_appl,#table_enfr,#table_det01,#table_det02,#table_det03,#table_det04,#table_det05,#table_datais").on( "click", "input:submit", function( event ) {
//alert('Hi')
//event.preventDefault();
var fieldvalue = $(this).closest('tr').find('input:text').val();
var fieldname = $(this).closest('tr').find('input:text').attr('name');
alert('fieldname = ' + fieldname)
alert('fieldvalue = ' + fieldvalue)
$.ajax({
type:"GET",
url:"/validate/",
data:{'fieldvalue':fieldvalue,'fieldname':fieldname},
success:function(data){
if (data == 'Y'){
var item = $(this).closest('tr').find('input:label')
alert("Gonna be replaced" + item);
$( this ).closest( 'tr' ).find( 'input:label' );
$( this ).closest( 'tr' ).find( 'input:label' ).replaceWith("<label for=\'success\'>SUCCESS</label>");
}
alert("Response = "+ data);
}
});
return false;
})

Here's a fiddle.
And here's the code:
<form role="form" method="POST" action="/validate/" id="input_form">
<input id="myInput">
<button type="submit" id="submitButton">Click me!</button>
</form>
with the script:
$("#submitButton").click(function () {
event.preventDefault();
$.get("/validate/", function (d){
if (d == "Y"){
$("#submitButton").replaceWith("<label>SUCCESS</label>");
}
})
})
Is this about what you want? I guess you'll have to adapt the .replaceWith() part to find the correct element...

Related

Submit Form with ajax result

I successfully load iframe into div #output with AJAX. This script play video for me.
jQuery( document ).ready( function( $ ) {
$( '.play_next' ).on('click', function( event ) {
event.preventDefault();
$('#output').empty();
var meta_key = $( this ).data( 'meta-key' );
var post_id = $( this ).data( 'post-id' );
$.ajax( {
url: ajaxobject.ajaxurl,
type: 'POST',
dataType: 'html',
data: {
action : 'wpse_296903_call_meta',
post_id : post_id,
meta_key : meta_key,
},
success: function( result) {
$( '#output' ).append( result );
}
});
});
});
Now no more need of #output in div, Need to submit this value with
form.
<form action="http://other-domain.com/" method="POST" target="_black">
<input type="submit" name="iframe" value="" />
</form>
This form submit iframe to other domain, which open in new tab with property target="_black.
How put #output value in Form and submit with Ajax?
Edit
You can not access the contents of an iframe from outside of one if its an iframe with a different origin.
If its the same origin
let form = document.createElement('form');
let input = document.createElement('input');
input.type = 'hidden';
input.value = encodeURIComponent(document.querySelector('iframe').contentDocument.innerHTML);
input.name = 'iframe_data';
form.action = 'myDestination.html'
form.appendChild(input);
document.body.appendChild(form);
form.submit();

jquery: how to detect element that is being loaded every few seconds

I have a div element where a file is being loaded every 10500 miliseconds;
index.php
...
<div class="loadHere"></div>
...
code that loads every few seconds.
setInterval(
function ()
{
$('.loadHere').unload().load('filetoload.php').fadeIn('slow');
}, 10500);
filetoload.php
test
<input type="hidden" value="1234" class="hiddenelement"/>
and this is what i'm trying to do but isn't working:
$(document).on('click','.testbtn',function(event)
{
event.preventDefault();
var xyz = $('.hiddenelement').val();
alert(xyz);
});
Your strategy seems to work.
setInterval(
function () {
$('.loadHere').unload().load('toload.php').fadeIn('slow');
}, 10500);
$(document).on('click','.testbtn',function(event)
{
event.preventDefault();
var xyz = $('.hiddenelement').val();
alert(xyz);
});
Here is the working plunker : http://plnkr.co/edit/tiLv3WMDCjoW3Ggb9bTH?p=preview.
Use Callback function:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
From Jquery Docs

How to iterate down an Array in chunks

I'm trying to build an application that takes a text from a website (for the app I'm using gutenburg.org's open ebook catalog) and displays the story in bites of 10 indexes at a time in a div to make the story easier to read for those with ADD. I have a working increment function but I'm stuck as to how to increment back to the previous chunk.
HTML:
<input type="text" id="url" style="width: 400px">
<input type="button" id="btn" value="Get JSON">
<button id="button">Next</button>
<button id="prev">Previous</button>
<div id="test"></div>
Javscript:
$(function() {
$( '#service' ).on( 'change', function(){
$( '#url' ).val( $( this ).val() );
});
//angular.module('exampleApp')
$( '#url' ).val( $( '#service' ).val() );
$( '#btn' ).click(function(){
var url = $( '#url' ).val()
$.ajax({
crossOrigin: true,
proxy: "http://localhost:8888/whorl/proxy.php",
url: url,
//dataType: "json", //no need. if you use crossOrigin, the dataType will be override with "json"
//charset: 'ISO-8859-1', //use it to define the charset of the target url
context: {},
success: function(data) {
//alert(data);
var body = data;
console.log(body.length);
//body/data is a string
var text = body.split(' ')
console.log(text.length);
var increment = function(array) {
if (array.chunk < array.length) {
var chunk = array.slice(array.chunk,Math.min(array.chunk+array.chunkSize, array.length).join(" ");
array.chunk += array.chunkSize;
$( '#test' ).html(chunk);
console.log(chunk);
}
};
$(document).ready(function(){
$("button").click(function() {
increment(text);
});
});
}
})
.done(function( data, textStatus, jqXHR ) {
//alert(data);
});
});
});
pass an attribute, value would be either INCREMENT or DECREMENT
if (value=='increment')
array.chunk += array.chunkSize;
else
array.chunk -= array.chunkSize;

Get json data through ajax

The question I am asking is a basic question because I am new in json and ajax.
so I have a json data of name , task , date and status I am getting data through ajax but it is not showing in on my page.
my ajax code is this:
$(document).ready(function(e) {
// Using the core $.ajax() method
$.ajax({
url: "getdata.php",
type: "GET",
dataType : "json",
success: function( json ) {
$( "<h1/>" ).text( json.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.task ).appendTo( "body" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
this is my json data:
[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
I don't know why It is not appending html data but it is showing complete alert.
I have added fiddle even if it is not working.
Fiddle
Ok, i see you actually getting results so i guess you do have a success. You do have a flaw though. You are trying to access properties directly, but your json is an array of objects and not an object.
You need to do a foreach itteration.
json.forEach(function (entry) {
$( "<h1/>" ).text( entry.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( entry.task ).appendTo( "body" );
});
Edit Your Json like
{
"jsontext":[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
}
and the ajax code should be as
$.ajax({
url: '/getdata.txt',
complete: function (data) {
if (data.responseText != "") {
var NewTxt = data.responseText;
NewTxt = NewTxt.replace(/\n/g, "");
NewTxt = NewTxt.replace(/\s/g, "");
obj = JSON.parse(NewTxt);
var NewStr = "";
for (var i = 0; i < obj.jsontext.length; i++) {
NewStr += obj.jsontext[i].name + "<br/>" + obj.jsontext[i].task + "<br/>" + obj.jsontext[i].date + "<br/>" + obj.jsontext[i].status + "<br/><br/>";
}
document.getElementById("demo").innerHTML = NewStr;
}
}
});
and the HTML as:
<div id="demo"></div>

Jquerymobile-1.4.0 keyUp event is called twice every time character is entered in the autocomplete textfield

I used the example from jQuery mobile site Autocomplete source code
It's working fine, but when I tried to give alert in the script inside the listviewbeforefilter event, it's showing the alert 3 times, so when 3 characters are entered, it will prompt around 7-9 times.
Why is it showing so many alerts? I thinks it should prompt only once when the character is inserted.
Here is the code retrun in script for autocomplete:
$( document ).on( "pageinit", "#myPage", function() {
alert("abc");
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
alert("789");
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
alert("123");
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
Here is the code return in the body tag:
<div data-role="content">
<h3>Cities worldwide</h3>
<p>After you enter <strong>at least three characters</strong> the autocomplete `function will show all possible matches.</p>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" `data-filter-placeholder="Find a city..." data-filter-theme="a">
</ul>
</div>

Categories