Browser hangs after AJAX complete (waiting response?) - javascript

Not really expecting to get answer but struggling with this 2 days now and have no idea whats going on.
So here what I have done:
Uploading file via AJAX and immediately starting processing it in backend.
$.ajax({
type : "post",
cache: false,
contentType: false,
processData: false,
url : formAction,
data : formData
});
In backend I writing session where storing current progress like 500 of 10000...
Then I calling another AJAX to check status from session, I calling this funcion every 1 second till responsve returns 'done'.
Looks legit to me, but problem is that after backend proccessing done, and first XHR changing status from 'pending' to 200 browsers freeze, looks like something is blocking it, like another request or somehing. chekc screens bellow.
So it's done, check is stopped, status is changed to 200, nothing happening but browsers freeze, tried Chrome, Firefox...Browser suggesting me to kill process, but if I wait some time it will refresh.
UPDATE
So i lie a little bit, I tried again do same but without ajax and saw similar issue, after backend processing complete, browser waiting response (spinning backwards)...So that is what cousin hanging.
Here is my backend it's Laravel
foreach ($chunks as $rows)
{
$current_chunk++;
if ( $current_chunk < $all_chunks ) {
Session::put(['import_progress'=>'Importing ' . $current_chunk * 150 . ' of ' . $all_results]);
Session::save();
} elseif ( $current_chunk >= $all_chunks ) {
Session::put(['import_progress'=>'done']);
}
foreach ($rows as $row)
{
// transakcija start
DB::transaction(function() use ($row) {
$code = $row[0];
$gender = $row[1];
$brand_name = filter_var($row[2],FILTER_SANITIZE_STRING);
$category = $row[3];
$subcategory = $row[4];
$condition = $row[5];
$details = $row[6];
$composition = $row[7];
$materials = $row[8];
$colors = $row[9];
$patterns = $row[10];
$country = $row[11];
$size = $row[12];
$m_a = $row[13];
$m_b = $row[14];
$m_c = $row[15];
$m_d = $row[16];
$m_e = $row[17];
$m_f = $row[18];
$m_g = $row[19];
$product = new Product();
$product->code = $code;
$product->gender = $gender;
$product->size = $country . ' | ' . $size;
$product->condition = $condition;
$product->measurement_a = $m_a;
$product->measurement_b = $m_b;
$product->measurement_c = $m_c;
$product->measurement_d = $m_d;
$product->measurement_e = $m_e;
$product->measurement_f = $m_f;
$product->measurement_g = $m_g;
$product->save();
if ( empty($code) ) {
$bad_prods[] = $product->id;
}
if ( !empty( $brand_name ) ) {
$brand = Brand::firstOrCreate(['brand_name'=>$brand_name]);
$product_b = new ProductBrand();
$product_b->brand_id = $brand->id;
$product_b->product_id = $product->id;
$product_b->save();
}
if ( !empty( $materials ) ) {
$materials_exp = explode(',',$materials);
foreach ($materials_exp as $material) {
$material = Material::firstOrCreate(['material_name'=>trim($material)]);
$product_m = new ProductMaterial();
$product_m->material_id = $material->id;
$product_m->product_id = $product->id;
$product_m->save();
}
}
if ( !empty( $patterns ) ) {
$patterns_exp = explode('/',$patterns);
foreach ($patterns_exp as $pattern) {
$pattern = Pattern::firstOrCreate(['pattern_name'=>trim($pattern)]);
$product_p = new ProductPattern();
$product_p->pattern_id = $pattern->id;
$product_p->product_id = $product->id;
$product_p->save();
}
}
if ( !empty( $colors ) ) {
$colors_exp = explode('/',$colors);
foreach ($colors_exp as $color) {
$color = Color::firstOrCreate(['color_name'=>trim($color)]);
$product_c = new ProductColor();
$product_c->color_id = $color->id;
$product_c->product_id = $product->id;
$product_c->save();
}
}
$product_t = new ProductTranslation();
$product_t->product_id = $product->id;
$product_t->product_title = $brand_name;
$product_t->product_description = '<p>'.$details.'</p><p>'.$composition.'</p>';
$product_t->save();
}); // end transakcija
}
}
Session::put(['import_progress'=>'done']);
Session::put(['bad_prods'=>$bad_prods]);
return redirect()->route('admin.import');
And here I'm checking status
public function status()
{
return response()->json([
'status' => Session::get('import_progress'),
'bad_prods' => Session::get('bad_prods')
]);
}

When processing is done I put simple exit(); at the end of processing Controller...Not sure why this works and any other return statement doesn't.

Related

Wordpress favorite system without plugin learning method

Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom

echo select options according to AJAX call

ive been trying this for the whole day and cant get my head around it. Im retrieving a count from an ajax call called quote.pdfnum which tells me the number of pdfs generated per user. I want to echo quote.pdfnum (number) of options. Im trying to echo in the select at the last table column.
setInterval(function(){
$.ajax({
url: 'poll_requests.php',
type: 'POST',
data: {data:currRequests},
dataType: 'json',
// dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
})
.done(function(response, textStatus, jqXHR) {
// console.log("new Requests "+response.new_quotes);
// console.log("all requests "+response.all_quotes);
var oldRequests = currRequests;
currRequests = response.all_quotes;
var newRequests= response.new_quotes;
if(oldRequests!=currRequests){
if(activeTab!='requests_tab' && newRequests.length>0 && pollRequests>1){
var spanText=Number($('#rbadge').text())+newRequests.length;
$('#rbadge').text(spanText);
}
if(newRequests.length==0 && oldRequests.length==1){
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
$("#rtable tr:first").after("<tr><td colspan='8'>No pending requests at the moment...</td></tr>");
}
if(newRequests.length>0 && oldRequests.length==1){
//and old requests are 0 (-1) remove the first row "no requests at the moment"
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
}
for (var i = 0; i < newRequests.length; i++) {
quote = newRequests[i];
if (activeTab!='requests_tab' && pollRequests>1) {
noty({text: quote.company+' requested a new quote'});
};
// $("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a><a class='approve' href='approve.php?id="+quote.id+"'>Approve</a></td> </tr>");
$("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a></td><td><select name='pdfs' id='pdfs'></select></td> </tr>");
};
}
// console.log('requests length '+newRequests.length);
pollRequests++;
})
.fail(function(error) {
console.log("error"+ error.responseText);
})
.always(function() {
// alert("complete");
});
// },1000000);
},2000);
And this is my poll_requests.php page.
<?php
header('Content-Type: application/json');
$data = $_POST['data'] ;
$new_quotes = array();
$files = array();
$all_quotes = array();
require_once('db_connect.php');
$sql = $db->prepare("SELECT * FROM users, quotes WHERE users.id = quotes.user_id and quotes.status = 'req' ORDER BY quotes.rdate ASC");
if($sql->execute()){
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$files[] = $row;
}
}
foreach ($files as $file):
$quote_id = $file['quote_id'];
$all_quotes[] = $quote_id;
if(!in_array($quote_id, $data)):
$date_time=explode(' ',$file['qdate']);
$insured=$file['insured'];
$status = $file['status'];
$user_id = $file['id'];
$username= $file['username'];
$country = $file['country'];
$company = $file['company'];
$pdfcount = $file['pdfnum'];
$pdf_path="all/$quote_id/$quote_id.pdf";
$new_quotes[] = array('id' => $quote_id,
'user' => $username ,
'country' => $country,
'insured' => $insured,
'status' => $status,
'date' => $date_time[0],
'time' => substr($date_time[1],0,8),
'company' => $company,
'pdfcount' => $pdfcount,
'pdf' => $pdf_path);
endif;
endforeach;
$all_quotes[]=-1;
$data_to_send = array();
$data_to_send['new_quotes'] = $new_quotes;
$data_to_send['all_quotes'] = $all_quotes;
$json_to_send = json_encode($data_to_send);
echo $json_to_send;
?>

Multiple sets of data insert at one call into separate divs by unique id AJAX

Currently when asking the server for data, when one single set is sent back like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
the div is inserted.
But lets say there's two sets with different notification id's like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
{"num":1,"notification_id":"819","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
Nothing happens
So I'll cut the code down as to show and example of what I have
success: function(response){
if(response.notification_id > notification_id){
$("#notif_ui"+ notification_id).prepend('
<div class="notif_text"><div id="notif_actual_text-'+response['notification_id']+'"
class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+response
['notification_triggeredby']+'.jpg\"
onerror=this.src=\"userimages/no_profile_img.jpeg\"
width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+response.num));
}
I was toying with the idea of maybe using
$.each(response, function (i, val)
But I'm still unsure.
EDIT
Exact response how it shows
{"num":1,"notification_id":"823","notification_content":"Lucy Botham posted a status on your wall","notification_throughurl"
:"singlepoststreamitem.php?streamitem_id=703","notification_triggeredby":"85","notification_status":"1"
,"notification_time":"2015-11-08 04:16:26"}{"num":1,"notification_id":"824","notification_content":"Lucy
Botham posted a status on your wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id
=704","notification_triggeredby":"85","notification_status":"1","notification_time":"2015-11-08 04:16
:27"}
AND MY WHILE LOOP
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
$json['notification_time'] = $row['notification_time'];
echo json_encode($json);
}}
First you need to build an array of notifications, rather than a single one:
<?php
$json = array(
'notifications' => array()
);
while ($row = mysqli_fetch_assoc($com)) {
if ($row['notification_status'] == 1) {
$num = mysqli_num_rows($com);
$notification = array();
if ($num) {
$notification['num'] = 1;
} else {
$notification['num'] = 0;
}
$notification['notification_id'] = $row['notification_id'];
$notification['notification_content'] = $row['notification_content'];
$notification['notification_throughurl'] = $row['notification_throughurl'];
$notification['notification_triggeredby'] = $row['notification_triggeredby'];
$notification['notification_status'] = $row['notification_status'];
$notification['notification_time'] = $row['notification_time'];
$json['notifications'][] = $notification;
}
}
echo json_encode($json);
?>
Then you can access the notifications array from JavaScript:
success: function(response) {
$.each(response.notifications, function(i, notification) {
if (notification.notification_id > notification_id) {
$("#notif_ui" + notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-' + notification['notification_id'] + '" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped' + notification['notification_triggeredby'] + '.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text());
$("#mes").text((i + response.num));
}
})
}
Note, completely untested, but hopefully you can see the difference!
Your php could be changed to
// you can just the the number of rows once outside the while loop
$num = mysqli_num_rows($com);
if($num){
$jsonNum = 1;
}else{
$jsonNum = 0;
}
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){ // this would be unnecessary if you add it as a where conditional to your sql query
// add the num to the array to match your current data structure
$row['num'] = $jsonNum;
$json[] = $row;
}
}
echo json_encode($json);

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Counting clicks with jQuery and displaying with Ajax

I'm hacking away at some code in order to have it register a click on an invisible div element, which expands an article to reveal it's excerpt while adding a +1 to the number of time's it's been clicked by anyone. Afterwards it updates an element with ajax with the number of clicks it's received.
At least, that's the goal.
The following code ends up breaking Wordpress and gives me the white screen of doom. This is taken from a simple click counter with an Ajax callback to update the number.
Where my problem lies is hacking away at this for it to register clicks on a different element.
Without wasting too much of anyones time, here's my question:
Wouldn't I just need to rename all post_like to post_reader? Someone's been telling my in person that it should work so check your server but that is ridiculous... it seems.
Note, below where you see post_reader, it had said post_like previously.
// post click to expand button
$timebeforerevote = 1;
add_action('wp_ajax_nopriv_post-like', 'post_reader');
add_action('wp_ajax_post-like', 'post_reader');
wp_localize_script('like_post', 'ajax_var', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce')
));
function post_like()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Busted!');
if(isset($_POST['post_reader']))
{
$ip = $_SERVER['REMOTE_ADDR'];
$post_id = $_POST['post_id'];
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$meta_count = get_post_meta($post_id, "votes_count", true);
if(!hasAlreadyVoted($post_id))
{
$voted_IP[$ip] = time();
update_post_meta($post_id, "voted_IP", $voted_IP);
update_post_meta($post_id, "votes_count", ++$meta_count);
echo $meta_count;
}
else
echo "already";
}
exit;
}
function hasAlreadyVoted($post_id)
{
global $timebeforerevote;
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(in_array($ip, array_keys($voted_IP)))
{
$time = $voted_IP[$ip];
$now = time();
if(round(($now - $time) / 60) > $timebeforerevote)
return false;
return true;
}
return false;
}
function getPostReadLink($post_id)
{
$themename = "toolbox";
$vote_count = get_post_meta($post_id, "votes_count", true);
$output = '<div class="post-read">';
if(hasAlreadyVoted($post_id))
$output .= ' <span title="'.__('I like this article', $themename).'" class="qtip like alreadyvoted"></span>';
else
$output .= '<a href="#" data-post_id="'.$post_id.'">
<span title="'.__('I like this article', $themename).'"class="qtip like"></span>
</a>';
$output .= '<span class="count">'.$vote_count.'</span></div>';
return $output;
}
The function called when clicked:
jQuery(".expand").click(function(e){
e.preventDefault();
readers = jQuery(this);
// Retrieve post ID from data attribute
post_id = readers.data("post_id");
// Ajax call
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-reader&nonce="+ajax_var.nonce+"&post_reader=&post_id="+post_id,
success: function(count){
// If vote successful
if(count != "already")
{
heart.addClass("readered");
heart.siblings(".count").text(count);
}
}
});
return false;
})
Invoking it within the appropriate div.
<?php echo getPostReadLink(get_the_ID());?>

Categories