Ajax Request In Order - ajax

I'm making litte app to get pages by URL and check their title.
I need check URLs line by line which is user pasted in textarea.
Process sequence :
Check URL > append response to page > then check next url......
Here is my code :
HTML :
<textarea id="textarea" name="urlLine"></textarea>
<button type="button" name="action" id="check">Check IT!</button>
Js :
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500)
},
fail: function (msg) {
console.log(msg);
}
});
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
}
$(document).ready(function () {
$('#check').click(function () {
var uris= $('textarea').val().split('\n');
getResp(uris);
});
PHP :
sleep(5); // I don't know why i'm adding. Just wait for performance.
$title = 'title_i_searching';
$adress = $_POST['uriLine'];
if($check->chekURL('https://'.$adress) == $title){
echo ' OK';
}else{
echo 'NOT OK';
}
PHP CLASS :
class checkES
{
public $url;
public function chekURL($url){
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
"http"=>array(
"timeout"=> 5
)
);
$str=
file_get_contents($url,false,stream_context_create($arrContextOptions));
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str));
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title);
return $title[1];
}
}
public function parseByLine($content){
$lines = preg_split('/\r\n|[\r\n]/', $content);
return $lines;
}
}
But when i run this code for example; in 20 URL searching on 5th url page alert 'finish'. But append function still continue.
Sometimes, page crash down.
I could not find the healthy method.
I wish i was explain. Sorry for bad language.

Try moving the code to process next uri in success function like this:
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500);
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
},
fail: function (msg) {
console.log(msg);
}
});
}

Related

Ajax alert inside function not works

First alert : alert('<?php echo t_lang('M_FRM_PLEASE_WAIT_WHILE_FILE_OR_IMAGE_IS_BEING_UPLOADED_._IF_FILE_SIZE_IS_BIG_IT_CAN_TAKE_SOME_TIME_._PLEASE_DO_NOT_CLOSE_TAB');?>'); does not work unless I put second alert out of function call: alert();
$('input[name="btn_submit"]').click(function second(){
var step = <?php echo $_REQUEST['step']?>;
var dealid= <?php echo $_GET['edit']?>;
var ur="imagecheck.php?dealid="+dealid;
if (step == 1) {
$.ajax({
url: ur,
type: "GET",
header: {'Access-Control-Allow-Origin': '*'},
success: function(y) {
if(y=='true'){
alert('<?php echo t_lang('M_FRM_PLEASE_WAIT_WHILE_FILE_OR_IMAGE_IS_BEING_UPLOADED_._IF_FILE_SIZE_IS_BIG_IT_CAN_TAKE_SOME_TIME_._PLEASE_DO_NOT_CLOSE_TAB');?>');
} else {
alert(dealid);
}
}
});
alert(); // if I don't add this first alert is not showed up.
}
});
I tried almost everything but still can not understand why first alert relies on second alert. Any help would be highly appreciated.
I am adding the codes below which is all about ajax in my file.
<script type="text/javascript">
$(document).ready(function(){
$('input[name="btn_submit"]').click(function first(){
var com_id=<?php echo $_SESSION['logged_user']['company_id']?>;
var co_type=$('#co_type').val();
var ur="check_no_of_deals.php?company_id="+com_id;
if(co_type==0){
$.ajax({
url: ur,
type: "GET",
header: {'Access-Control-Allow-Origin': '*'},
success: function(t) {
if(t == 'true'){
} else {
alert('<?php echo t_lang('M_FRM_YOU_HAVE_ALREADY_ADDED_DEAL_TODAY');?>');
window.location.href='http://deals.az/merchant/company-deals.php';
}
}
});
}
});
//bizim kod basladi
$('input[name="btn_submit"]').click(function second(){
var step = <?php echo $_REQUEST['step']?>;
var dealid= <?php echo $_GET['edit']?>;
var ur="imagecheck.php?dealid="+dealid;
if (step == 1) {
$.ajax({
url: ur,
type: "GET",
header: {'Access-Control-Allow-Origin': '*'},
success: function(t)(y) => {
if(t=='true'){
alert('<?php echo t_lang('M_FRM_PLEASE_WAIT_WHILE_FILE_OR_IMAGE_IS_BEING_UPLOADED_._IF_FILE_SIZE_IS_BIG_IT_CAN_TAKE_SOME_TIME_._PLEASE_DO_NOT_CLOSE_TAB');?>');
} else {
alert(dealid);
}
}
});
// alert();
}
});
//bizim kod bitti
});
</script>
try replacing to arrow function
$.ajax({
...
success: (y) => {
if(y=='true'){
...
}
}
...
})
the difference between an arrow function and a regular function is by their this
so when you pass the regular function it becomes part of the ajax call or the Jquery object.
but the arrow function stays where you see it.

select2 4.0.8, templateSelection option not working

I am using select2 version 4.0.8 with ajax search. In my angular 4 application with ajax call. Till searching and populating result it works fine. But after that when I click on any option it doesn't call method specified in templateSelection option.
Below is the code I am using:
jQuery(".suggestion"+i).select2({
placeholder: 'Select Countries',
ajax: {
url: AppConstants.facebookBaseUrl + "/search",
dataType: 'json',
delay: 250,
type: "GET",
beforeSend: (request)=> {
request.setRequestHeader("Authorization", "Bearer "+this.user.facebookPage_Token);
},
data: (params)=> {
return {
q: params.term, // search term
location_types: this.facebookFilters[i].filter,
type: "adgeolocation",
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
multiple:true,
minimumInputLength: 2,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (repo) {
if (repo.loading) {
return repo.text;
}
var $container = jQuery("<option (click)='selectCountry($event)' class='country_name' value='"+repo.key+"'>"+repo.name+"</option>");
return $container;
}
function formatRepoSelection (repo) {
var $container = jQuery("<option class='selectedCountry' value='"+repo.key+"'>"+repo.name+"</option>");
return $container;
// return repo.key || repo.text;
}
And HTML:
<select class="form-control" name="selected[]" [ngClass]="'suggestion'+i"></select>
What I am doing wrong here?
thanks in advance!
Try by changing option to span as:
function formatRepoSelection (repo) {
var $container = jQuery("<span class='selectedCountry'>"+repo.name+"</span>");
return $container;
// return repo.key || repo.text;
}

Getting Error in codeigniter ajax dropdown changing

Getting Error in codeigniter ajax dropdown changing
[![enter image description here][1]][1]
function fun1(sid) {
//alert(sid);
var obj;
if (window.XMLHttpRequest) {
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP")
}
obj.open("post", "https://99shopin.com/register/getcity?val=" + sid, true);
obj.send();
obj.onreadystatechange = function() {
if (obj.readyState == 4) {
document.getElementById('div1').innerHTML = obj.responseText;
} else {
document.getElementById('div1').innerHTML = "";
}
}
}
Try this, and check Is there still an error?
function fun1(sid){
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('register/getcity'); ?>",
data: ({val: sid}),
//dataType: "json",
success: function (data) {
document.getElementById('div1').innerHTML = data.responseText;
}
});
}

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div

I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.
The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.
So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.
The data comes in the form of:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
As an extra question, is this the correct way of long polling?
Here is my code:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
EDIT - After answer I have now got this but it does not work (I get nothing in the console).
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
You can try this:
function poll_n() {
$.ajax({
type: 'POST',
url: 'your url',
success: function(data){
var notification = $('#notification-data');
$.each($(data), function(){
var id = this.id;
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend(this);
}
});
},
complete: function(jqXHR, status) {
if (status === 'success') {
setTimeout(poll_n, 9000);
}
}
});
}
You must call poll_n() again after the request has been completed.

Make a if loop according to what returns the ajax html(data)

I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}
Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});
The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}
You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}

Resources