How to load article without page reloading in Yii & Ajax - javascript

I have an viewing articles from databases and every article view with hole page load. So I would load articles without page reloading, I think this is possible using Ajax but I'm not so strong about it.
This is my initial concept like below:
Layout:
CHtml::link($menu['items'][$itemId]['label'],
array('articles/view',
'id'=>$menu['items'][$itemId]['link'],
)
);
// This showing articles name & link
View:
<?php
echo $model->article_body;
?>
<script>
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: ('articles/view'),
success: function(data){
document.getElementById('articles').innerHTML = data;
},
error: function(){
alert('Somthing wrong');
}
});
</script>
Controller:
public function actionView($id)
{
$model=$this->loadModel($id);
$this->render('view',array('model' => $model));
}
Does someone can help me? Thanks

if i understood you correctly,
in your view file something like this.
echo CHtml::link($menu['items'][$itemId]['label'],
array('articles/view',
'id'=>$menu['items'][$itemId]['link'],
),array('class'=>'youclassnamehere')
);
echo '<div id="yourDivId"></div>';
in javascript your code should be something like e.g.
$(".youclassnamehere").click(function(){
$.ajax({
type:'POST',
url:$(this).attr('href'),
success:function(data){
$("#yourDivId").html(data);
}
error:function(data){
alert('Error occured please try again later..');
}
}),
return false;//this will not redirect your page
});
in controller action your code like e.g
public function actionView($id)
{
$model=$this->loadModel($id);
$this->render('view',array('model' => $model));
}
hope this will help you

You must return json:
public function actionView($id)
{
$model=$this->loadModel($id);
...
echo CJSON::encode(
array(
'status' => 'success',
'content' => $this->renderPartial('view',
array(
'model' => $model,
),
true,
true
),
)
);
}

I reach solution from above answer but I newly add like below:
array(
'onclick'=>'javascript:return false'
)

Related

What is the best way to post input data and insert them to the database with ajax in wordpress?

I developed a contact form with pure PHP and HTML. I wanna insert the input values into the database with AJAX. Here is my Javascript/jQuery code:
var email = jQuery("#email").val();
var data = {
'email': email
}
jQuery.ajax({
type: "POST",
url: "http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php",
dataType: "json",
data: data,
success : function(data) {
// do something
}
});
And my contactform.php:
$date = date('Y-m-d H:i:s');
global $wpdb;
$wpdb->insert('myTableName', array(
'email' => $_POST["email"],
'date' => $date,
));
My code works well. My question is what is the correct way to do that? Because I think it's not a good idea to create a .php file inside the WordPress theme and use it just for inserting data into the database. I think it has security issues and users can see my script URL (http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php) that used in my javascript file for using ajax.
Do you have better ways to do that?
Create a function for inserting data and also enqueue script for ajax call and pass it in url. example like:
function mytheme_admin_scripts() {
wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/admin_script.js');
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts','mytheme_admin_scripts' );
Enqueue your js file which you have wrote your ajax call and pass my_ajax_object.ajx_url in your ajax url.
jQuery.ajax({
type : "POST",
url : my_ajax_object.ajax_url,
data : data,
dataType: "json",
cache: false,
success : function(data) {
// do something
}
});

make like button by ajax in laravel (method=post)

I want to make like button in my laravel project by using ajax.
Would you please tell me what is wrong in my written code?
html part
<a id="bL-like-{{$file["User_Id"]}}-{{$file["id"]}}">like</a>
js
$("a").click(function() {
//like button
if(this.id.startsWith("bL-like-")){
var temp=this.id.substr(8);
var l_user=temp.substr(0,(temp.indexOf("-")));
var l_id=temp.substr((temp.indexOf("-")+1));
$.ajax({
type: 'POST',
url: '/like',
data:{user:l_user,link_id:l_id},
success:function(data){
alert('liked');
},
error:function(data){
alert('error');
}
});
}
});
route
Route::post('/like', array(
'as' => 'like',
'uses' => 'FileController#like'
));
FileController
public function like(Request $request)
{
$OBJ=new \App\File();
$OBJ->isActive=1;
$OBJ->isDeleted=0;
$OBJ->User_Id=$request['user'];
$OBJ->id=$request['link_id'];
$boolean=\App\File::increaseLike($OBJ);
}
increaseLike is in my model,that connect to db.
It always drives to error part of js.
I very appreciate if you help me.

WordPress admin-ajax returns "0" on the Viewer-Facing Side

I'm pretty new in Wordpress plugins, so I have a question for you guys. I have a problem with admin-ajax call on the viewer-facing side of site. I'm using shortcodes in wordpress posts, to make a link, which must call ajax action. Unfortunately admin-ajax.php returns 0 every single time. Take a look on my code and maybe you can help me to discover what i'm doing wrong.
PHP side:
class myClass {
public function __construct() {
if (defined('DOING_AJAX')) {
add_action( 'wp_ajax_myAction', array($this, 'myCallback') );
add_action( 'wp_ajax_nopriv_myAction', array($this, 'myCallback') );
}
}
public function myCallback() {
echo "test";
die();
}
}
and there is Ajax call in Javascript:
jQuery(document).ready(function($) {
var link = $('a.myLink');
link.on('click', function(e) {
$.ajax({
url: 'http://127.0.0.1/myapp/wp-admin/admin-ajax.php',
type: 'POST',
data: 'myAction',
success:function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
Do you have some ideas why that code isn't working and admin-ajax.php returns "0"?
Try to use the ajax call in this format :
jQuery(document).ready(function($) {
var link = $('a.myLink');
link.on('click', function(e) {
var details = {
'action': 'myAction'
};
$.ajax({
url: 'http://127.0.0.1/myapp/wp-admin/admin-ajax.php',
type: 'POST',
data: details, // data format
success:function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
hope it helps...
Solved! Two things:
data: 'myAction'
replaced by
data: {
action: 'myAction'
}
and in main plugin file I had
if ( is_admin() ) {
// there should be new myClass() too
} else {
$class = new myClass();
}
thanks for suggestions!
Try with Enque JQuery Form Plugin Before Your Ajax request.
add_action('wp_print_scripts','include_jquery_form_plugin');
function include_jquery_form_plugin(){
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-form',array('jquery'),false,true );
}

Jquery Ajax in Laravel 4 - NotFoundHttpException

.Hello y'all. I'm trying to learn ajax and am currently trying to have an input in a form be sent via a route to a controller and then echoed in a div.
For some reason I am getting a NotFoundHttpException error when I press the submit button for the form and am having trouble seeing what is wrong with my route.
If anyone can point out where I'm going wrong it would be greatly appreciated! Thank you!
View:
<form id="edit_price_form" method="POST" action="">
<input name="new_price" id="new_price"/>
<input type='submit' class='button tiny radius' id='edit_price_button'/>
</form>
Ajax request:
$(document).ready(function(){
$("#edit_price_form").submit(function(e) {
e.preventDefault();
//form_data
var form_data = $('#edit_price_form').serializeArray();
$.ajax({
url: 'edit_prices',
type: "POST",
dataType: "html",
data: form_data,
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
});
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
Controller:
public function edit_prices(){
$new_price = Input::get('new_price');
echo $new_price;
}
Thanks again!
The problem lies in your HTTP method. You're AJAX request looks like this:
$.ajax({
url: 'edit_prices',
type: "PUT",
...
But your route looks like this:
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
In short, you'll need to change your AJAX request from PUT to POST - Laravel is rejecting the PUT request because it's expecting POST.

Redirection in json code

Am not a json geek but really need your help. During form submission & after successful validation, the following code is executed thus returning a 'registration successful' message.
I want it to be able to redirect to another page instead of returning that 'registration successful' notification.
$json_response = array(
'status' => 'success',
'message' => $success_message,
);
$json_response = json_encode( $json_response );
echo $json_response;
I tried replacing the text with
header('Location: http://localhost/successful.php');
But in vain, Thanks in advance
You can't use a server-side redirect from an AJAX request. You need to return that data, and then redirect in the success handler of your javascript.
Something like this in jQuery:
$.ajax({
url: '/foo/',
success: function(data) {
if (data.status == 'success') {
window.location.assign('/newpage'); // <- redirect at this point
}
else {
console.log(data.message);
}
}
});

Categories