add a jQuery selector to the URL parameter - javascript

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

Related

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

How to change specific element on ajax ?

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

Extract data from current URL and use it in ajax call as a paramenter

I am developing a website in which only 1 html page is there in which I first fethch the url & gets the id from url and send it to api using ajax call. On success, I displays data of the given id from url.My code is as-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main').hide();
var url = window.location.href;
var formno = url.substr(url.lastIndexOf('/') + 1);
if (formno != 'Login.html') {
var apiUrl = 'http://localhost:801/api/api/Patient/Get';
$.ajax({
url: apiUrl,
crossDomain: true,
contentType: "application/json",
type: 'GET',
data: { formNo: formno },
success: function (result) {
$('#main').show();
alert("Success" + result)
},
error: function (result) {
alert("error :: " + JSON.stringify(result))
}
});
}
});
</script>
when I use the url as abc.in#1 it displays the success alert but I want to give the url in format abc.in/1 at that time it gives
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Why it can not find the page? Is there any solution for this?
I want to give plain url as abc.in/1 where 1 is id and which is dynamic.
Is there any solution?
Your browser is probably trying to access document on location abc.in/1, which doesn't exist. You will need some server side logic for this, e.g. php router which will always serve your document, and additonal parameters will be processed by it. abc.in#1 anchor is different type of url parameter, which purpose is to be processed by document or javascript on client side.

How to send a parameter in data attribute of $.ajax() function in following scenario?

I've written one AJAX function code as follows :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
if(response != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#myModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
}
});
e.preventDefault();
});
Now here in data attribute I want to send some additional parameters with values in data attribute. How should I send these parameters to PHP file?
For clear understanding of my issue refer the following AJAX function code that I've written previously :
function GetPaymentRequest(status){
var status = $('#status_filter').val();
$.ajax({
type: "POST",
url: "view_payment_request.php",
data: {'op':'payment_request_by_status','request_status':status},
success: function(data) {
// alert(data);
}
});
}
In above function code you can see that I've passed few parameters with values viz. 'op':'payment_request_by_status','request_status':status in data attribute.
Exactly same parameters I want to pass in first AJAX function code. The already mentioned parameter "formdata ? formdata : form.serialize()" should also be there.
How should I do this? Can someone please help me in this regard?
Thanks in advance.
Add by using $.param
form.serialize() + '&' + $.param({'op':'payment_request_by_status','request_status':status});
or use serializeArray() and push new items
var data = form.serializeArray();
data.push({name:'op',value:'payment_request_by_status'}).push({name:'request_status',value:status});
then pass data
What you can do is, add two hidden fields to your already existing form, name one of them as op and set the value as payment_request_by_status and another one as request_status and the value based on the status.
When the form is serialized, it will automatically send these values also.

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(...)

Categories

Resources