I have a register page in which via ajax request i want to redirect the user to the logged in page. But, this particular ajax request does a redirect but doesn't pass on the session after the POST request
var dataString = 'name='+ name + '&email=' + email1 + '&password=' + password1;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://localhost/ci/index.php/login/add/",
data: dataString,
success: function() {
window.location.href = "http://localhost/ci/dashboard";
}
});
The login/add function is taking the values via POST request which then puts these value in session and does a redirect. The same thing is happening perfectly without a ajax request in plain php/CI. But, not happening via ajax request.
Here's the php code if it helps
if ($this->input->post("add") == "Sign up") {
$data_array = array(); //this array contains post data
$output = $this->user_model->add_new($data_array);
if($output == TRUE){
$this->session->set_userdata('logged_in', '1');
}
$data = array(
'name' => form_error('name'),
'email' => form_error('email'),
'password' => form_error('password')
);
echo json_encode($data);
}
The login/add function is taking the values via POST request which then puts these value in session and does a redirect. The same thing is happening perfectly without a ajax request in plain php/CI. But, not happening via ajax request.
It because previously you perform a synchronous request, while with jQuery ajax you are perform asynchronous request(this to say that your javascript is may ignore some part of your PHP script). Try adding async parameter in your ajax and set it to false
Related
I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:
I am using this ajax call params to pass data:
var formData = new FormData();
formData.append('file', selectedFile);
formData.append('subject', 'test subject');
formData.append('message', 'test message');
url: 'my/endpoint',
type: 'POST',
data: formData,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false
Here is my endpoint:
function test_endpoint(WP_REST_Request $request){
return $request->get_body();
//return wp_mail( $to, $subject, $body, $headers, $attachments );
}
I can see the data:
So basically I am trying to access the form parameters so I can put them into an email. I can't figure our how to access file, subject and message?
You can't or at least shouldn't call ajax directly when using Wordpress.
There is a mechanism built in to deal with ajax calls.
More or less what you have to do is:
Write the function of what will be executed on the server when the ajax call is triggered and then bind it to an ajax callback action.
add_action( 'wp_ajax_nopriv_myaction', 'my_ajax_processing_func' );
add_action( 'wp_ajax_myaction', 'my_ajax_processing_func' );
function my_ajax_processing_func() {
<Your processing here>
}
note the 'myaction' part in the add_action(). In the form data sent from the client, there has to be an action parameter set to this identifief (myaction) for the binding to take place.
Also in the form the url has to be set to the admin_url( 'admin-ajax.php' ). The way of getting hold of this url is to download it to the js script using wp_localized_script().
You can find a full explanation here:
Using AJAX With PHP on Your WordPress Site Without a Plugin
Also chck out this article to add a nonce to the form for security reasons.
How to Add a WordPress AJAX Nonce
I found out that it was my ajax. So I switched to straight XHR and it worked:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'my/endpoint', true);
xhr.onload = function () {
console.log('response',JSON.parse(this.responseText));
};
xhr.send(formData);
I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?
I have a system implemented in CodeIgniter, I am trying to send some data in a text area of Rsform component via POST to the url referring to my CodeIgniter system, I have tried usign AJAX request to send the post data using the following code
<script>
alert("jsc");
var data;
data='test from joomla!';
$.ajax({
type: "POST",
url : 'http://localhost/cii/index.php/login/getNews/',
data: {news:data},
cache: false,
success: function(html){
alert(html);
}
});
getNews controller:
function getNews() {
//print_r($this->session->userdata);
header('Access-Control-Allow-Origin: *');
echo "news is ".$news=$_POST['news'];
$data = array ( 'username' => "null", 'is_logged_in' => false, 'news'=>$news);
$this->session->set_userdata($data); //var_dump($_POST); //
print_r($this->session->userdata); session_start(); echo session_id();
}
but it failed, is there any other options ?
Use something like Firebug in mozilla firefox to observe what data is being posted to the app to check if your ajax call is working.
Then in your codeigniter controller method, simply put this code to see if the data is getting to it.
function getNews()
{
foreach($_POST as $key => $val)
{
$options[$key] = $this->input->post($key);
}
var_dump($options);
}
I'm tryin to validate an input field with an ajax call to a cakephp controller
My Ajax is:
$("#UserAlphaCode").change(function () {
$.ajax({
type: "post",
url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
data: ({code : $(this).val()}),
dataType: "json",
success: function(data){
alert (data);
},
error: function(data){
alert("epic fail");
}
});
});
My controller code
function checkCode() {
Configure::write('debug', 0);
$this->autoRender = false;
$codePassed = $this->params['form']['code'];
$isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
if ($isCodeValid == 0){
$codeResponse = false;
} else {
$codeResponse = true;
}
echo json_encode ($codeResponse);
}
I'm pretty sure I'm using $this->params wrong here to access the data sent from the ajax request. What should I be doing instead?
Try something like:
$codePassed = $_POST['code']
you might also try putting:
$this->log($codePassed,LOG_DEBUG);
somewhere in there and examine the output in tmp/logs/debug.log
Using firebug will help debug the transport.
Don't know why it would be returning null, but I normally use $this->data to fetch form data.
And did you try debug($this->params)? If you don't have a non-AJAX form to test the request from, use Firebug or Wireshark to see what is being return by the server for the debug() call—since it will break jQuery's AJAX handler by not being in JSON.