I have code but any error.
Use of undefined constant id - assumed 'id'
$(document).on('click', '#UpdateForm', function () {
id = $(this).data('id');
name = $('#name').val();
address = $('#address').val();
country = $('#country').val();
$.post("{{ URL('peoples.'+id+'.update') }}", {name:name, address:address, country:country, id:id}, function (data){
//
});
});
You can't use javascript variable in php code. Php code run's on the server side and javascript code runs on the client side. You can't ask the browser to run php code.
read for more :
Use javascript variable in php code
How can I use a JavaScript variable as a PHP variable?
Related
I have an anchor tag and would like its data-id to be sent to a function in the controller which would in turn retrieved data from the database through the model.
However the data is not getting past the controller. The ajax response is showing that the data was sent but controller shows otherwise.
Here is my ajax code:
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url();?>Designs/business_cards",
type:"POST",
data:{sub_item_id:sub_item_id},
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});
I had set datatype:"json" but the data was not being sent so I removed the datatype and it worked,the ajax part that is.Or atleast the response showed that data was sent.
My controller code is:
function business_cards(){
$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id);
$this->load->view('category/business-cards',$data);
}
My model code is:
public function get_quantities($sub_item_id){
$this->db->select('quantities');
$this->db->where('id',$sub_item_id);
$query = $this->db->get('sub_products');
return $query->result_array();
}
HTML Code which includes the anchor tag
<?php foreach ($results as $object):?>
View Prices
<?php endforeach?>
The data-id is displaying the correct value as per the iteration.
When I check the result array of the model code it is an empty array showing that the $sub_item_id was not passed in the controller. What could be the problem?
I just copied your code and I was able to get the value in the controller.
In your controller function do var_dump($id). Then in your developer tools (F12) check the console. Since you have console.log(data) that var_dump should be in the console. It won't show on the screen.
Some other things to check:
Does your db have records with that ID? Could your db result array be empty because it actually should be?
Are you sure that the data-id actually has a value when you click the tag?
it is not passed to the controller because you forgot to put a parameter inside the function of your controller.
Note: you cannot use input post because you're not using form.
function business_cards($id){ //put a parameter here, serve as container of your passed variable from **ajax**
//$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id); //pass the id to your model
$this->load->view('category/business-cards',$data);
}
change your ajax code to this..
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url('Designs/business_cards/"+sub_item_id+"');?>", //pass the id here
type:"POST",
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});
I've been struggling for a few days with this issue and I really hope you can help me out.
I've created a plugin, which is located in:
'/wp-content/plugins/my-cool-plugin'.
My plugin allows users to post a custom post type via a form on a public page, basically anyone should be able to post something.
Using jQuery, I listen to when my frontend form is submitted and using Ajax I pass the data from the form to a php file to process it into a post.
This file is located at:
'/wp-content/plugins/my-cool-plugin/inc/processor.php'.
Below is the content of my processor file:
$var1= $_POST['some'];
$var2= $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish',
'mcp_1' => $var1,
'mcp_2' => $var2
);
$post_id = wp_insert_post( $new_post, $wp_error );
if ($wp_error == 'false'){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
When I test my form, it results in the following error:
Call to undefined function wp_insert_post() on line ... which is the following line:
$post_id = wp_insert_post( $new_post, $wp_error );
Do I need to include something since I'm not in the WordPress 'scope' anymore?
Or is there another (much better) way for inserting custom posts from a front end form?
Why are you running the file out of wordpress scope? That is not the best practive. Instead you could run it in wordpress scope and user wordpress native ajax.
add_action('wp_ajax_yourplugin_create_post', 'yourplugin_create_post');
add_action('wp_ajax_nopriv_yourplugin_create_post', 'yourplugin_create_post');
function yourplugin_create_post() {
// your code here
}
Then you would need your ajax url to be passed from php to js:
function your_plugin_ajaxurl() {
?>
<script type="text/javascript">
var yourPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','your_plugin_ajaxurl');
Then you can use your ajax request but you would need to indicate action:yourplugin_create_post and url = yourPluginAjaxUrl
Try adding
require(dirname(__FILE__) . '/wp-load.php');
It took me some time to process Nick's answer, but I finally got it to work! Like Nick said, I dropped using the process file because is was out of the scope of WordPress. I moved my post creation from my proces file to a new function in the plugin init file (my-cool-plugin.php), as Nick suggested. This resulted in the following new function:
add_action('wp_ajax_coolplugin_create_post', 'coolplugin_create_post');
add_action('wp_ajax_nopriv_coolplugin_create_post', 'coolplugin_create_post');
function coolplugin_create_post() {
$var1 = $_POST['some'];
$var2 = $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish'
'post_title' => 'Some title'
);
$post_id = wp_insert_post( $new_post, $wp_error );
// check if there is a post id and use it to add custom meta
if ($post_id) {
update_post_meta($post_id, 'mcp_1', $var1);
update_post_meta($post_id, 'mcp_2', $var2);
}
if ($wp_error == false){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
}
I also had to change the way I inserted my custom values into the newly created post, because the wp_insert_post() function only accepts default post parameters (see the wp_insert_post documentation for these parameters).
Next to my insert/create post function I also had to make some adjustments to my javascript file, which retrieves the filled in data from my form. Therefore (as Nick suggested) I needed to pass my Ajax URL from PHP to JS by adding the following function to my-cool-plugin.php like this:
function your_plugin_ajaxurl() { ?>
<script type="text/javascript">
var coolPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
add_action('wp_head','your_plugin_ajaxurl');
By adding the coolPluginAjaxUrl variable to the head I'm able to use the URL in my javascript to post the data to when my form is submitted, like this:
$( '#form' ).on( 'submit', function(e) {
var request;
e.preventDefault();
var val_one = $( '#val-one' ).val();
var val_two = $( '#val-two' ).val();
var formData = {
action: 'coolplugin_create_post',
some: val_one,
data: val_two,
};
request = $.ajax({
type: 'POST',
url: coolPluginAjaxUrl,
data: formData,
});
});
The formData holds the coolplugin_create_post action defined in PHP and the request is posted to the coolPluginAjaxUrl URL, defined in the head.
Thanks Nick for pointing me into the right direction and I hope that my solution will also help others. Please note that I've stripped my code of several security measures for others to easily understand how the code works.
I'm struggling with the render() method in Laravel 5.
When $whatever->render() is runned, it takes the controller method name as the route by default.
Example:
When i run this command in DelasController#updateFilter, the pagination route is set to whatever.com/marketplace/updateFiler?page=2, which does not make a sense to me.
Problem:
I want to keep the route as simple as whatever.com/marketplace?page=2.
Question:
Can anybody gives me a hint on how to solve this?
Thank you for your time and a discussion.
Looking forward for a reply.
I have an application in which various paginated lists are displayed in "windows" on the page and are updated via AJAX calls to the server. Here's how I did it:
Set up a route to render the whole page, something like this:
Route::get('/marketplace', function ($arguments) {
....
});
Set up a route which will return the current page of the list. For example, it might be something like this:
Route::get('/marketplace/updateFiler', function ($arguments) {
....
});
In your Javascript code for the page, you need to change the pagination links so that, instead of loading the new page with the URL for the link, it makes the AJAX request to the second route. The Javascript could look something like this:
$('ul.pagination a').on('click', function (event) {
// stop the default action
event.stopPropagation();
event.preventDefault();
// get the URL from the link
var url = $(event.currentTarget).attr('href');
// get the page number from the URL
var page = getURLParameterByName(url, 'page');
$.get('marketplace/updateFiler', { page: page }, function (data){
// do something with the response from the server
});
});
The getURLParameterByName function is simply a helper that extracts the named parameter from a URL:
var getURLParameterByName = function (url, name, defaultValue) {
// is defaultValue undefined? if so, set it to false
//
if (typeof defaultValue === "undefined") {
defaultValue = false;
}
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ?
defaultValue :
decodeURIComponent(results[1].replace(/\+/g, " "));
};
I adapted this code from an answer I found here on Stack Overflow: https://stackoverflow.com/a/901144/2008384.
I am building a store locator for a website that I am building in Laravel. Since the blade file calls the js file tht is on the assests folder. It doesn't recognize the URL like this
$.ajax({
url: '{{ URL::action('getLocation') }}',
// ...
});
This is how I have my route.php
Route::post('/getLocation', array('as'=>'getLocation','uses'=>'FrontController#getLocation'));
So it doesn't find the file. How can I call this function in the ajax URL?
Here is a demonstration of how i would achieve this
I might be late here. This is just a sample code to help understand people
who visit this question. Hope this helps anyone who visits here.
in my routes.php i define a named route
Route::post('getLocation',array(
'as'=>'getLocation','uses'=>'FrontController#getLocation')
);
added name route as data-url in my somehtmlform.blade.php file
{!! Form::open() !!}
{!! Form::text('input-name',null,array('class'=>'form-control search-input','data-url'=> URL::route("getLocation") ))
{!! Form::close() !!}
my search.js file catches the data-url and use it as post url
$('.search-input').each(function(){
$(this).on('change',function (e) {
search(this)
});
});
function search(self) {
var query = $(self).val();
$.ajax({
url: $(self).attr('data-url'),
type: 'post',
data: {'q':query, '_token': $('input[name=_token]').val()},
success: function(data){
console.log(data);
},
error: function(data){
// Not found
}
});
}
You can use this package, it gives almost all laravel helper functions which can be used in js files too.
You may try this:
// Add this in your filtes.php file (feel free to store where you like)
View::composer('layouts.master', function($view) {
$ajaxUrl = json_encode(array('url' => URL::action('getLocation')));
$view->with('ajax', $ajaxUrl);
});
Add this in you master.blade.php file's (master layout) <head></head> section (place it before your js file):
<script>var ajax = {{ $ajax or 'undefined' }}</script>
Now you can use this as:
// ajax.url
console.log(ajax.url);
Read here, similar thing.
It looks like you're using the wrong method for generating the URL.
Try switching from URL::action() to URL::route().
URL::action() is used to generate a URL to a given controller action, but then you need to write it like this:
URL::action('FrontController#getLocation')
URL::route() generates a url to a route which is named in the route definition, using "as" => "routeName". In your case:
URL::route('getLocation')
Hope this helps!
If you call your ajax function from a .js file,
try to change the blade part '{{ URL::action('getLocation') }}' to '/getLocation'
or pass a full url like: 'http://domain.com/getLocation' and it should work.
in js file, you can't not use the Url::action for route
just do
url:"/getLocation"
I have a sample code:
in default.php:
<?php
JHTML::_('behavior.mootools'); /* to load mootools */
$ajax = "
/* <![CDATA[ */
window.addEvent('domready', function() {
$('start_ajax').addEvent('click', function(e) {
e.stop();
var url = 'index.php?option=com_xxx&controller=xxx&task=updateAjax&format=raw';
var x = new Request({
url: url,
method: 'post',
onSuccess: function(responseText){
document.getElementById('ajax_container').innerHTML = responseText;
}
}).send();
});
})
/* ]]> */
" ;
$doc = &JFactory::getDocument();
$doc->addScriptDeclaration($ajax);
?>
And controller of default.php i using code:
function updateAjax() {
echo date('Y-m-d D H:i:s');
}
When i run code is error undefined method JDocumentRaw::addCustomTag(), how to fix it ?
I think you wrong in call jquery using for ajax:
$document =& JFactory::getDocument();
$document->addCustomTag("call jquery library or script other");
And you try:
if($document->getType() != 'raw'){
$document->addCustomTag("call jquery library or script other");
}
This is because you are setting the "format" parameter to "raw", usually by adding &format=raw to the end of the URL you are using to access your component. This triggers Joomla to use the JDocumentRaw renderer instead of the standard JDocument renderer. You can resolve this by choosing one of the following (whichever is more appropriate):
Remove the "format=raw" from the URL of the linked page and use an alternate method to get your page to display as expected, such as adding tmpl=component or template=system to the URL
Add a check for if "format" is set to raw, in which case do not add the scripts at all
Extend the JDocumentRaw class with your own which implements your own methods for adding scripts and use format=yourRendererName instead of format=raw