I'm currently doing an application which uses ajax in getting user inputs from form fields then concatenate it in a string, this works fine but I'm getting a
"POST 500 (Internal Server Error")
and cannot pass the data. How do I pass a string from view to controller with ajax and access it in a controller.
Here are my codes:
the script
<script>
// $(document).ready(function(){
function saveData(){
var con = document.getElementById('tiks').value;
// var dataString = {'conid':con};
alert(con);
var cct = $("input[name=csrf_token_name]").val();
var base_url = <?php base_url(); ?>;
$.ajax({
url: base_url + "welcome/newShortestPath",
type: "POST",
data: {'conid':con, 'csrf_token_name':cct},
success:function(){
alert("SUCCESS KALUY-I "+con);
$('#myForm')[0].reset();
}
});
}
controller
public function newShortestPath(){
echo "REACHED";
$var = $this->input->post('conid');
//$this -> load -> model('edge_model');
//$this->edge_model->setConstraints();
}
really need your help guys. thanks in advance. :)
UPDATE
Im no longer getting any error by fixing the errors at calling the base_url() function but at the same time I cant fetch the passed data, is there any other way fetching data from post to controller?
you have to echo the base_url and wrap your var with ''
var base_url = '<?php echo base_url(); ?>';
Update
based on the error you are getting which is:
Fatal error: Call to undefined function base_url()
as you mentioned in your comment.
what you have to do is to go to application/config/autoload.php
and find
$autoload['helper'] = array();
then change it to
$autoload['helper'] = array('url');
or manually load the url helper:
$this->load->helper('url');
read more here
Tips:
Tip 1:
You can setup all url:
var url = <?php echo site_url('welcome/newShortestPath'); ?>;
Tip 2:
Use site_url() instead base_url(). base_url must be used to resources (img, css, js, etc.)
To build URL's use site_url()
Related
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 am using Yii2 and socket.io for sending notifications. I have a client.js file which should emit an id of newly connected user to server.
The code responsible for this in my client.js is:
socket.emit('AddId', '<?php $model->id ?>');//of course it does not work but I need smth like this.
So how to pass a Yii2 model attribute to socket.io client.js?
Client.js code:
$( document ).ready(function() {
var socket = io.connect('http://localhost:8890');
socket.emit('AddId', '<?php $model->id ?>');
});
If you want send info about an user you could do this way
$( document ).ready(function() {
var socket = io.connect('http://localhost:8890');
socket.emit('AddId', '<?php echo Yii::$app->user->id ?>');
});
In Yii2 inside my index.php view I wrote:
$test = 'My text';//here could be any text data, model attributes etc
<script>
var test = "<?php echo $test ?>";
</script>
After this update I was able to use a variable (var test) in my notification.js.
notification.js is added also to AppAsset.php as following:
public $js = [
'js/notification.js'
];
notification.js file:
$( document ).ready(function() {
var socket = io.connect('http://localhost:8890');
socket.emit('AddId', test);//test is a variable (var test) from index.php file
});
Hi i have this data which i want that only a certain div will refresh using ajax. How will i able to pass the json_encode to the ajax what will load the data on a certain div using codeigniter.
Heres my controller below
$this->data['getNumberOfMessages'] = $this->mm->getNumberOfMessages($this->data['id']);
$this->data['countNumber'] = $this->data['getNumberOfMessages'];
$responseOnject = new stdClass();
$responseOnject->status = 'ok';
$responseOnject->StatusMessages=$this->data['countNumber'];
$this->output->set_output(json_encode($responseOnject));
this line of code here
$this->output->set_output(json_encode($response));
outputs this one
{"status":"ok","StatusMessages":20}
and i want that to pass through my ajax in my code below
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"),
success: function(data){
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
});
});
and target on my certain div so that it will automatically refresh
below is my code
<tr>
<th>
<a href="#" id="<?php echo $id; ?>" data-messageid="<?php echo $id; ?>" data-href="<?php echo base_url().'profile'?>" title="messages">
<span class="badge"><?php echo $countNumber; ?></span>
message(s)</a>
</th>
</tr>
when i tried to alert(data.StatusMessages);it return undefined.
can someone pls help me figured this thing out? ive been stuck in this.. my code really works but i want to be ajax, only certain div refresh without refershing my entire page.
Any help is muchly appreciated.
You need to decode the response JSON first in order to be able to access it as a JS object. This is how it's done in JS:
JSON.parse(JSONStringHere);
So, your success callback should be:
success: function(data){
data = JSON.parse(data); // this is what decodes JSON
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
As I said in the comments, you're not calling the right URL with AJAX (although you said you do and that it returns that JSON string; if so, the code above would work). This doesn't look like it would give you a URL:
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"), // <---- what is the value of this?
Once you fix that, your code will work.
For JSON data your controller should have the following line to output
UPDATE
Just noticed your problem is that codeigniter is outputting html along side your ajax response.
To Make this go away, Your code in the controller should be like this:
$this->output
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($responseOnject))
->_display();
exit;
This would force the output library to display & the exit to stop displaying anything else.
If you do not set the application/json content type, your response won't be treated as JSON And you'd have to use JSON.parse in your javascript code to convert it to json which is a bad practice.
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
Hi guys Im trying to make a drop-down list of countries and when the user select a country that redirect to a specific page created dynamically actually i manage to make the redirection work using javascript, but i need to take more parameters to the method inside the controler like the county "id" with out exposing it on the uri, so is that possible using $_post also i should not use button submit.
this is my code
view page
<?php echo form_open('site/country');
$options = array();
$js = 'id="country" onChange="window.location.href= this.form.CTRY.options[this.form.CTRY.selectedIndex].value"';
$options['#'] = "(please select a country)" ;
foreach ($list as $row):
$value= site_url()."/site/country/".url_title($row->name);
$options[$value] = $row->name ;
endforeach;
echo form_dropdown('CTRY', $options,'',$js);
//$test =array ('number' => 10)
//echo form_hidden($test);
echo form_close();?>
this is my method in controller
function country($data)
{
echo 'this is taking you to county= '.$data;
}
Why don't you do something like #Joseph Silber described.
Use jQuery to perform an ajax request when the drop-down list is changed, also managing the redirect?
Something like;
$('#my-drop-down').change(function() {
$.ajax({
url: '/site/country',
type: 'post',
data: $("#my-form").serialize(),
success: function( response.redirect ) {
window.location.href = response.redirect;
},
error: function( response ) {
alert('Oops');
}
});
});
By using serilaize(), you can post all data from the form, or just add the parameters you want to pass.
E.g data: 'id='+$('#id').val()+'&country='+$('#country').val()