jquery .load() and wordpress usability - php

I'm working on wordpress theme, you can take a look at: greenzoner.pl. What I want to do is showing all posts usability in the middle div, i.e single posts, comments, attached pictures etc. 2 side divs should never reload. I am open to any alternatives to method I try to use (maybe IFRAME?).
To load sigle post I used jquery .load()
$.ajaxSetup({ cache: false });
$(".openpost, .comments-link").click(function() {
var post_url = $(this).attr("href");
$(".container").load(post_url);
return false;
});
$(".closepost").click(function() {
$(".container").load(index.php .postlist);
return false;
});
I've encountered a major problem - I cant use ajax comments ( i tried many plugins, tutorials, etc, nothing works) - so basicly when you post reply, you get redirected to eg. http://greenzoner.pl/?p=32#comment-26. My current js for comments is:
var commentform = $('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv = $('#comment-status'); // define the infopanel
commentform.submit(function(){
//serialize and store form data in a variable
var formdata = commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl = commentform.attr('action');
//Post Form with data
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown) {
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus) {
if (data == "success")
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
else
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
});
});
and php:
add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status) {
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
switch($comment_status){
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
echo "success";
$commentdata = &get_comment($comment_ID, ARRAY_A);
$post = &get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
break;
default:
echo "error";
}
exit;
}
}
Other problem with using this method, is post linking.

Related

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

How to reset ckeditor save event

On a previous ajax call I get all articles for a selected Page.
Then I display them and bind this function - on click - to each of them. This is working only one time.
When I want to change a second or third article the article id inside the ajax call keeps holding its first value.
CKEDITOR.replace( 'editor1' );
function editArticle(article){
// id changes for each article as it is supposed to
var id = article.attr('data-id');
var text = article.html();
$('#ckModal').modal();
$('.modal-title').text('Editing Article: '+id+' on Page: '+pageTitle);
CKEDITOR.instances.editor1.setData(text);
CKEDITOR.instances.editor1.resize('100%', '350', true);
CKEDITOR.instances.editor1.on('save', function(e){
e.cancel();
var html = CKEDITOR.instances.editor1.getData();
if(html){
$.ajax({
type: 'POST',
url: '/admin/nodes/edit',
cache: false,
data: {'html' : html,
'articleId' : id }
}).done(function(msg){
// next two lines did not work
//CKEDITOR.instances.editor1.fire('save');
//CKEDITOR.instances.editor1.stop('save');
// id stays the same
console.log(id);
// I echo an 'ok' string when update worked from php
if(msg === 'ok'){
article.html(html);
$('#ckModal').modal('hide');
}else{
//alert(msg);
}
}).fail(function(xhr, status, error){
console.log(JSON.stringify(xhr));
console.log("AJAX error: " + status + ' : ' + error);
});
}
});
}
I had to cancel the save event to get and set Data and perform the ajax call.
But how do I restart or reset the 'save' event - if this is what is causing the problem. I am not so shure anymore ....
Got it working by destroying editor instance in ajax done function and creating a new one after it.
function editArticle(article){
var id = article.attr('data-id');
var text = article.html();
//CKEDITOR.replace( 'editor1' );
$('#ckModal').modal();
$('.modal-title').text('Editing Article: '+id+' on Page: '+pageTitle);
CKEDITOR.instances.editor1.setData(text);
CKEDITOR.instances.editor1.resize('100%', '350', true);
CKEDITOR.instances.editor1.on('save', function(e){
e.cancel();
var html = CKEDITOR.instances.editor1.getData();
if(html){
var title = $('.modal-title').html()
$('.modal-title').prepend(spinner);
$.ajax({
type: 'POST',
url: '/admin/nodes/edit',
cache: false,
data: {'html' : html,
'articleId' : id }
}).done(function(msg){
//console.log(id);
$('.modal-title').html(title);
if(msg === 'ok'){
article.html(html);
$('#ckModal').modal('hide');
CKEDITOR.instances.editor1.destroy();
CKEDITOR.replace( 'editor1' );
}else{
//alert(msg);
}
}).fail(function(xhr, status, error){
console.log(JSON.stringify(xhr));
console.log("AJAX error: " + status + ' : ' + error);
});
}
});
}
You are assigning multiple event listeners on your editor instance 'editor1', one for each article. What happens is when you click save, the first listener (the first article assigned) called cancels all others with e.cancel().
I see you achieved what you wanted by destroying your editor. Doing this removes event listeners, and solves your problem. You could achieve the same with calling e.removeListener() in the handler, this way removing itself after the first run and avoiding the need to recreate the editor. Also note that destroying editors and recreating them is leaking memory (some versions worse than others #13123, #12307), so one should probably avoid doing that if possible.
Both solutions make the save button unusable after a save; of course it will work after another article is chosen for editing. So my suggestion is to remove all previous listeners from your save command before assigning a new one, like this:
// ... in function editArticle ...
CKEDITOR.instances.editor1.resize('100%', '350', true);
CKEDITOR.instances.editor1.getCommand('save').removeAllListeners();
CKEDITOR.instances.editor1.on('save', function(e){
// ...

My update with php and jQuery Ajax its not working

I have this "Read More" link:
echo '<p>'.$readNewsResult['content'].'<a class="test" href="#fancybox'.$readNewsResult['id_news'].'">Read More</a></p>';
When I click in this link, my goal is to update views column of my news table.
So I have a jQuery where Im passing id of my news, and it is working fine, when I click on "Read more" link I get an alert message saying: "action=update&update=311", where 311 is id of my clicked news.
My jQuery until now:
$(function(){
var read = $('.news');
read.on('click','.test',function(){
var updateid = $(this).attr("id");
var updatedata = "action=update&update="+updateid;
alert(updatedata);
$.ajax({
data: updatedata,
beforesend: '',
error: '',
success: function(updateR)
{
alert(updateR);
}
});
});
});
But now with php, Im trying to get update action and id, and do update on my news table, but its not working, because it seems that I never enter in my switch condition.
I tried to give some "echos" inside my case, and when I click on my "Read more" link my echo never appears.
Do you see where might be the problem??
$action = $_POST['action'];
switch($action)
{
case 'update':
$id = $_POST['id'];
$updateViews = $pdo->prepare("UPDATE news SET views=:views WHERE id=:id");
$updateViews->bindValue(':views', '1');
$updateViews->bindValue(':id', $id);
$updateViews->execute();
break;
}
At the very least you are trying to work with $_POST['id'] in your PHP but you are actually creating an URL parameter called update which contains the ID in your JavaScript.
The actual issue is that you are lacking an URL argument to your $.ajax call.
You are also naming your var udpdatedata on this line:
var udpdatedata = "action=update&update="+updateid;
but are referencing updatedata in the $.ajax call:
data: updatedata,
As such your query parameters are never added to the non-existent URL.
An extra one:
sucess: function(updateR)
Is actually spelled success, note the double c.
Where is your ajax controller url, I mean url and also type of call type,
$.ajax({
type: 'POST',
url: '/url/myphpfunction',
data: updatedata,
beforesend: '',
error: '',
sucess: function(updateR)
{
alert(updateR);
}
});
Here is the tutorial http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
You had a few things wrong with your ajax function. The first was that you should be passing through an object of values instead of a string. Then you need to specify a method of getting to your script. Then you need to set the URL to your script. See the comments below:
$(function(){
var read = $('.news');
read.on('click','.test',function(){
var updateid = $(this).attr("id");
// pass data as a JS object
var udpdatedata = {action:'update', update:updateid};
alert(udpdatedata);
$.ajax({
// set the method to post
type: "POST",
// the URL to your PHP script
url: "pathtoscript/script.php"
data: updatedata,
beforesend: '',
error: '',
success: function(updateR)
{
alert(updateR);
}
});
});
});
Your PHP also had an error, you're passing through 'update', not 'id':
$action = $_POST['action'];
switch($action)
{
case 'update':
// you're passing through 'update', not 'id'
$id = $_POST['update'];
$updateViews = $pdo->prepare("UPDATE news SET views=:views WHERE id=:id");
$updateViews->bindValue(':views', '1');
$updateViews->bindValue(':id', $id);
$updateViews->execute();
break;
}

Form submission using ajax and page view moderation after the submission

At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.

jQuery ajax call won't update mysql after pressing back button

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Categories