wordpress create user after form submit with ajax call - ajax

i am submitting on form in my wordpress template which goes to remote website now i want to create user with that from fields.but if the form submitted normally then user will not created and form will be redirect to remote url so i use ajax call for this,how ever the user is created but after success function it shows 404 file not found and form does not get submitted.here are the codes first one is ajax request from form fields
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
$na(document).ready(function(){
$na('#infuse').click(function(){
alert('start');
var name=$na('#inf_field_FirstName').val();
var password=$na('#inf_field_Password').val();
var email = $na('#inf_field_Email').val();
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email+'&password='+password,
cache: false,
success: function(){
jQuery("#inform").submit();
}
});
});
});
</script>
here is code in user.php file
<?php require('./../../../wp-blog-header.php'); ?>
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$password=$_REQUEST['password'];
wp_create_user( $name, $password, $email );
?>
how ever user created in admin that means ajax works but after that it shows 404 error in console and the form submit process stops

use
<?php require('./../../../wp-load.php'); ?>
in place of
<?php require('./../../../wp-blog-header.php'); ?>

Use:
<?php require('../../../wp-load.php'); ?>
Instead of:
<?php require('./../../../wp-blog-header.php'); ?>

Related

codeigniter Click button to call a view

I am having a view with 2 buttons in my codeigniter view:
<div class="btn-main col-md-3 col-md-offset-3">
<button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
</div>
<div class="btn-main col-md-3">
<button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
</div>
I would like to call another a controller to launch then a view when the button is clicked
I tried out to call the controller simu_mono by javascript, putted on /controller/simu_mono.php but doesn' t work
$(document).ready(function(){
$("#simu-mono").click(function(){
type:'GET',
url:'simu_mono'
});
$("#simu-multi").click(function(){
});
});
simu_mono.php:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$this->load->view('simu_mono');
echo 'Hello World!';
}
}
?>
Thanks for your helps
Cheers
Please, if u want to redirect only use following code:
$(document).ready(function(){
$("#simu-mono").click(function(){
window.location = base_url + "/simu_mono";
});
$("#simu-multi").click(function(){
window.location = base_url + "/simu_multi";
});
});
Note that you might need base_url, use this snippet to load base_url in JavaScript variable
<script>
base_url = <?= base_url()?>
</script>
put code above in some kind of view that is loaded always (before any other JavaScript code is executed)
Additional step would be to set up routes that take care of ugly underscore symbol (_)
something like:
routes.php
$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";
this way you go to your page and controller following way: yourserver.ufo/simu-mono and yourserver.ufo/simu-multi
You're not doing any class of AJAX call within your javascript. I assume you're using jQuery, so, your call should be something like:
$("#simu-mono").click(function(){
$.ajax({
url: "http://your-url.com/controller/method",
type: 'post', // <- Or get option, whatever you prefer
dataType: 'json', // <- This is important to manage the answer in the success function
//data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
success: function(data){
if (data.view) {
$('#here_view').html(data.view); // <- '#here_view' would be the id of the container
}
if (data.error){
console.log(data.error);
}
}
});
});
This will call your method, where you will have to indicate you want to pass the view:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$return = array(
'view' => $this->load->view('simu_mono')
);
echo json_encode( $return );
}
}
?>
json_encode will allow you easily pass vars and data from PHP to your javascript, and manage them in the client view. As you see in the javascript, I added data.error, this is just in case you'll have more logic, maybe change the view you're sending, send an error if you sent data and want to control them, etc.
Of course, in your javascript you could take the url from the clicked button, and in data.view parat of the success function, you may print in the screen a modal, send the view to a container, whatever you wanted, XD

yii controller action won't fire from form

I'm trying get a simple ajax call working with yii, not using the native yii means. My goal is to populate state and city fields on input from a zip code field, using a db look up in the create action. I have a separate javascript file,
$('#Accounts_zip').bind('focusout',function(){
$.ajax({
type: 'POST',
url:'/gatesadmin/index.php?r=Accounts/Ziplookup',
data: {zip:$('#Accounts_zip').val()},
success: function(datain, textStatus, jqXHR) {alert(datain.statecode);} ,
error: function(jqxhr, textStatus, errorthrown){alert(errorthrown);},
dataType:JSON
});
alert($('#Accounts_zip').val());
});
and in my AccountsController I have:
public function actionZiplookup()
{
$z = new ZipDao();
$row = $z->GetCityStateByZip($_REQUEST['data']);
header('Content-Type: application/json; charset="UTF-8"');
echo CJSON::encode(array('output'=>$row));
}
and my form is out of the box generated CRUD:
...
<div class="row">
<?php echo $form->labelEx($model,'zip'); ?>
<?php echo $form->textField($model,'zip',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'zip'); ?>
</div>
...
I know the javascript is working because I get my alert, and if I call the URL directly yii fires the actionZiplookup event because I'm getting the returned json. I just can't seem to be able to get the form to invoke the ajax successfully because I get External Server error in the jquery ajax failure event. I've combed through the net and the closest examples I can find embed the javascript in the form itself and use the Yii::app()-createUrl() method to define the url, but there has to be a way getting the controller action to fire while keeping javascript code in a separate file.
Any help would be greatly appreciated.
It turns out what I was missing can be found here:
How to get response as json format(application/json) in yii? It all has to do with telling the controller to ignore the layout, etc.

How to send a parameter and update an element using ajax in cakephp 2.x

I have an input field "#PostTitle" in which the user can enter a URL.
I want to send the user's input (upon change or upon exiting the field) to an action in my Posts controller which returns an array. Without CakePHP I think this would look something like this:
$(document).ready(function(){
$('#PostTitle').change(function(){
$.ajax({
type: 'POST',
url: '/posts/setPostImages',
data: $(this).serialize(),
success: function(data){
do something;
},
error: function(message){
console.debug(message);
}
});
return false;
});
});
The action in the Posts controller sets an array of links called $imageArray
(I CURL the page and return an array of all the images on that page, if it's of any interest).
Then, after I make the request, I would like to update an element which depends the contents of that array. The element contains the following code:
<div id="slider-wrap" class="boxframe">
<div class="coda-slider" id="slider-id">
<?php foreach ($imageArray as $image): ?>
<div class="crop">
<?php echo $this->Html->image($image); ?>
</div>
<?php endforeach; ?>
</div>
</div>
Any help is appreciated!
Edit: If I try this, the action isn't called at all:
echo $this->Js->link('update',
array('action' => 'setPostImages'),
array(
'update' => '#selectImage',
'data' => 'www.stackoverflow.com',
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
);
If you want to generate this JS with CakePHP, take a look at JsHelper's event method and request method
The action the POST request hits should render your element and respond with HTML. JsHelper::request will then replace the contents of the element specified by the update param with your HTML.
Personally, I find it fairly obtuse to generate Javascript with a PHP framework. It quickly becomes difficult to do what you want. If you have even a moderate amount of Javascript, I recommend just writing it directly (you already seem to know how to do this!).
Your edit refers to a possibly different issue. What kind of Javascript errors are you getting in your browser's console when you click the link generated by that snippet?

CodeIgniter Ajax form - submitting form

I'm new to stackoverflow and to CodeIgniter and I'm currently experimenting on some simple code examples I have found on the Internet in order to get a start. The one I'm working on right now is a form which uses CI and Ajax (jQuery) along with saving the inputs of the form in a database and then display the most recent of them on the same page as the form.
If I confused you it's the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files just below.
Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Message_model');
}
function view()
{
//get data from database
$data['messages'] = $this->Message_model->get();
if ( $this->input->is_ajax_request() ) // load inline view for call from ajax
$this->load->view('messages_list', $data);
else // load the default view
$this->load->view('default', $data);
}
//when we pres the submit button from the form
function add()
{
if ($_POST && $_POST['message'] != NULL)
{
$message['message'] = $this->security->xss_clean($_POST['message']);
$this->Message_model->add($message);
}
else
{
redirect('message/view');
}
}
}
?>
Model:
<?php
class Message_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function add($data)
{
$this->db->insert('messages', $data);
}
function get($limit=5, $offset=0)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
return $this->db->get('messages')->result();
}
}
?>
Views
default.php:
<!-- called using message/view -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<?php echo base_url('js/jquery-1.8.1.min.js'); ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
</script>
</head>
<body>
<?php echo form_open("message/add"); ?>
<input type="text" name="message" id="message">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
<div id="content"></div>
</body>
</html>
messages_list.php:
<!-- called from ajax call -->
<ol>
<?php foreach ($messages as $cur): ?>
<li><?php echo $cur->message; ?></li>
<?php endforeach; ?>
</ol>
The problem mainly lies in the 1st of the views (default.php). That is, if I omit the e.preventDefault(); line from the javascript code then the form loads a different page (message/add as the form action parameter implies) which is a blank page, also cancelling the ajax behavior of my application that way.
On the other hand, if I actually add this line then the add method of my message controller isn' t called, thus not adding what I've typed into the database.
Finally, I tried the following js code instead of the other above:
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
but that way it seems as the $.post() crashes because nothing is executed in the function which is supposed to run on a successful post() call.
Any help appreciated and sorry for the big post. :)
You are correct that you must call e.PreventDefault();, but you must also deal with the response from the callback function, which you are not. The callback takes a few arguments but the first one is what you're interested in, it is the response from your server. I've denoted it as r below:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function(r) {
//do something with r... log it for example.
console.log(r);
});
});
});
I've also removed $.("#content").load(...);. This would actually perform another AJAX request when the first one is complete.
Now, inspecting your controller...please refrain from using $_POST. CodeIgniter provides you with $this->input->post() as part of the Input Library. If you turn on Global XSS filtering in config/config.php you won't have to xss clean it either. You can clean on a post-by-post basis by using $this->input->post('name', true);
I recommend this instead:
function add(){
$m = $this->input->post('message', true);
if($m){
$this->Message_model->add($m);
}
}
The problem doesn't lie with the CI, its the JS that is wrong,
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("<?php echo base_url(); ?>/message/view");
$('#message').val('');
});
});
});
The e.preventDefault() is used to stop the default behaviour of the submit button (which will take you to message/add), which we don't want. You are correct in adding the URl paramter to the $.post() function later, but in the callback function, the .load loads the URL that is passed to it into the #content, so without passing any url, of course there won't be anything to load.

how to pass parameters using auto redirect droplist in codeigniter

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()

Resources