Checking a condition through Ajax - javascript

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

Related

laravel: view not shown after ajax post

I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.

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

Turning jquery into an includable, callable function

I'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!
I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.
This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.
<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>
<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>
Since moving the jquery include to the bottom of the page this naturally doesn't work.
What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.
Any help would be greatly appreciated. I'm running out of hair!
I think, repeated codes will hurt your page than placement of JQuery file.
You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.
$('[id^=comment-vote]').click(function() {
var elementId = $(this).attr('id');
var elementIdParts = elementId.split("-");
var voteType = elementIdParts[2];
var id = elementIdParts[3];
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v="+id+"&d="+voteType,
success: function(data){
$("#voterow-"+id).text("Thank you for your vote")
}
});
return false;
});
$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.
I didn't try the code but the idea behind that would be beneficial for you.
To really give a great working answer, I would need to see your an example page / the exact structure of your html, but here's what I have for you.
In a script file that you include after jQuery, you can include something similar to the below code assuming your html is as follows:
<div id="voterow-1" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
<div id="voterow-2" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
Having the class of upvote and downvote makes it easy to target these elements in jQuery:
// After jQuery is loaded, the function passed to ready() will be called
$(document).ready(function () {
// bind a click event to every direct child with the upvote class of an element with the voterow class
$('.voterow > .upvote').click(function (event) {
// get the voterow parent element
var $parent = $(event.target).parent();
// use regex to strip the id number from the id attribute of the parent
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
// call your ajax function
vote(id, 'up', $parent.find('.voteresult');
});
$('.voterow > .downvote').click(function (event) {
var $parent = $(event.target).parent();
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
vote(id, 'down', $parent.find('.voteresult');
});
function vote(id, direction, $resultElement) {
$.ajax({
type: "GET",
url: "/ajax.php",
// here we have the id and the direction needed to make the ajax call
data: "a=rv&v=" + id + "&d=" + direction,
success: function(data){
$resultElement.text("Thank you for your vote")
}
});
}
});
Here is a demo: https://plnkr.co/edit/ECL376hZ3NOz8pBVpBMW?p=preview

Change input name attributes after getting html data from action through AJAX in ASP.NET MVC

I have a simple ajax request which get from server a generated HTML, like:
$.ajax({
url: '/GetData'
type: "POST",
dataType: "html",
data: ...,
success: function(data) {
// here I want to change `name` attributes of inputs
// before print on page
// but it doesn't work, so, how to manage this ?
$(data).find("input[name='test']").prop("name", "anotherValue");
$("myDiv").prepend($(data));
}
});
and my action is simple:
[HttpPost]
public ActionResult GetData(){
return PartialView("myview", new MyModel());
}
I want to change input name attributes before print them in html page. If I do in success function (see above) then no change is made.
Why ? To to achieve this ?
try something like
$("input").each(function() {
if($(this).prop("name") == "test") $(this).prop("name", "anotherValue");
});
Data cannot be edited unless you append them to the DOM
So, use String.Replace function
var removed=data.replace("name='test'","anotherValue")
.replace('name="test"',"anotherValue");
$("myDiv").prepend(removed);
or do this
$(data).prependTo("myDiv").find("input[name='test']").prop("name", "anotherValue");

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