How to change specific element on ajax ? - javascript

I have ajax call that change the user info. And I want to get the value from the response and change value of specific element
Example: the element that need to chage:
<div id="changeMe"><!-- New Value --> </div>
Ajax call:
$.ajax({
url: "?rr=profile",
}).success(function(response) {
});
How to change the value of the "changeMe" element ONLY ?

Try it with
$.ajax({
url: "?rr=profile",
}).success(function(response) {
var r = $( response ).find( "#changeMe" );
$( "#changeMe" ).html( r.html() );
});

You could do this:
$.ajax({
url: "?rr=profile",
}).success(function(response) {
$('#changeMe').html('Your new content');
});
This will change the element with the ID "changeMe". See also JQuery API
To get a value you can use the same method.
Example:
var res = $('#someOtherElement').html();
The variable res has now the content of the element.

You can do it by following line.
$('#changeMe').html(response);

You can use the .html() or .text() jQuery methods depending on your requirements (whether the response content is HTML or plain text):
$.ajax({
url: "?rr=profile",
}).success(function(response) {
$('#changeMe').html(response);
});
switch .html(response) with .text(response) if that's better for you.

In your success function your can do like below
.success(function(response) {
$("#changeMe").append("Your value");
});

If you want to change the text then :
$('#changeMe').text('new data from response');
If you want to change CSS as well :
$('#changeMe').css('property', 'attribute');

Related

How to extract converted value from response using jquery ajax method?

I am using this link :freecurrencyconverterapi to get the converted value from USD to INR.
As you can see in developer mode of browser that the response is {"USD_INR":64.857002}.
Since I am new to programming, is there a way to get the float value using jquery ajax .
Thanks in advance.
That is returning a JSON object.
You need to assign that response object to a variable in your code, so ultimately it will end up looking like below...
var currency = { USD_INR: 64.857002 };
Then you can access it like this:
currency.USD_INR // This will give you 64.857002
See example below..
Edit: As per Rory's code (adapted)...
var currency;
$.ajax({
url: 'https://free.currencyconverterapi.com/api/v4/convert?q=USD_INR&compact=ultra',
dataType: 'jsonp',
success: function(data) {
currency = data.USD_INR;
console.log(currency);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The url that u provided had an issue, so I took an unorthodox route to get what u wanted;
$.get( "https://cors-anywhere.herokuapp.com/https://free.currencyconverterapi.com/api/v4/convert?q=USD_INR&compact=ultra", function( data ) {
$( ".result" ).text( data );
document.getElementById("result").innerHTML = JSON.stringify(data);
console.log(data);
//alert( "Load was performed." );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="result">
</div>

Checking a condition through Ajax

I have following code in jquery for my webpage http://localhost/currentpage
$('body').on('click', '.checkid', function(e) {
var url = 'http://localhost/newpage';
var id = $(this).attr('data-id');
$.ajax({
type: 'GET',
url: url,
success: function (data) { }
});
});
What I want need to do is I need to check whether there is an ID exists with same name in page http://localhost/newpage .Suppose the ID is myId , I need to check whether there is a ID with same name in http://localhost/newpage.
Can anybody help me how to execute it in jquery through ajax request for the above coding ?
You can use $(data).find('#myId')
Assuming data in the AJAX response is a HTML string, you could check for the presence of your ID checking with a RegExp on the tags:
if (data.match(/<.*id="myId".*\/?>/gi)) {
// a tag with ID "myId" has been found
}
The above code needs to be executed inside your function success(data) {} callback.
You can also achieve the same using jQuery, by doing $(data).find('#myId').length > 0

Use one ajax call for different page and div?

I use this code to make ajax call to change the content of div in main page without reloading the page :
function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}
and I call it like that :
<p><a onclick="ajaxcall()" >Create</a></p>
The issue is very complicated because I have to call 4 pages in the same div :
create.hmtl ; update.html; delete.html ; read.html
Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :
create.html :
<div id="container">
....
</div>
<div id="container-1">
....
</div>
So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?
Edit
To explain more my problem, I have 4 options (create/update/delete/read) with 4 pages, and in every page they are 2 div and 2 contents for 2 forms, I should change div content of every option(CRUD) for every form in webpage!
form -> ajax call content -> create.html -> div:container
form-1 -> ajax call content -> create.html -> div:container-1
form-1 -> ajax call content -> update.html -> div:container-1
You can add those as parameters to the function and make it like below
function ajaxcall(url, data, targetDivId)
{
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
$("#"+targetDivId).html( returnedData );
}
});
}
For your scenario:
I assume that even the AJAX url may change as currently it's pointing to create.php. In case it's same then you can avoid tht parameter.
<p><a onclick="ajaxcall('/create.php', {} , 'container-1')" >Create</a></p>
<p><a onclick="ajaxcall('/update.php', object2 , 'container-2')" >update</a></p>
<p><a onclick="ajaxcall('/delete.php', object3, 'container-3')" >Delete</a></p>
Following mohamedrias' answer, if you also needed to process each alternate path in the CRUD use case differently, you can use global event handlers.
Don't handle when making the request:
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
}
});
Do handle seperatley for each alternate path in CRUD
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var url = settings.url;
if (url.match(/create.php/) && query.match(/container1/)){
$("#container1").find(".form-1").html( xhr.responseText );
}
});
You should also notice that the selector in my example implies that "form-1" is a Class and not an ID.
IDs must be unique but Classes can occur many times.
Following this rule, if you wanted to reuse the same form for each alternate path you can do so by addressing discrete elements in the form using unique class names for each element. The container Div must have a unique ID (as you have already done). But you must give that element context by chaining the selectors to first select the div using ID and then select the element using class.
If I understood it correcyly you want to provide an argument to the ajax calling function to apply the return content from "/create.php" to a different div.
function ajaxcall(id, path)
{
$.ajax({
type: "POST",
url: path,
success: function( returnedData ) {
$("#"+id).html( returnedData );
}
});
}
And in html you can set the id like
<p><a onclick="ajaxcall(this.id, "/create.php")" >Create</a></p>
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var document = xhr.response;
var container = document.getElementById('container');
var container-1 = document.getElementById('container-1');
console.log(container, container-1);
// or
// var containers = document.querySelectorAll("#container, #container-1" );
//console.log(containers);
}
xhr.open('POST','/create.php');
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.responseType = 'document';
xhr.send();

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

add a jQuery selector to the URL parameter

Is it possible to add a jQuery selector to the URL parameter after an AJAX-request?
This is my perfectly working code:
$.ajax({
type : "POST",
url : "load_page.php",
data : 'page=' + url,
success : function(msg) {
if (parseInt(msg) != 0)//if no errors
{
$content.fadeIn(200, function() {
$('#content').html(msg);
});
}
}
});
//load the returned html into pageContent
I know that via .load() (or link) it is possible:
$("# content'").load("demo_test.txt #sub.content");
But is it possible via $('#content').html(msg);?
Additional info:
I am trying to only get the <div id=”sub-content”>
Yes, simply filter the data before appending it.
var $content = $("#content").empty();
$("<div>").html($.parseHTML(msg)).find("#sub").appendTo($content);

Categories

Resources