I have form with inputs in html.
Then I added this javascript (jquery) stroke to read and collect all value or data from form.
var formData = $("#form").serialize();
When I
console.log(formData);
Output will show:
calc-ownership=ooo&calc-activity=restaurant&calc-tax=usn&calc-tax-2=charge&calc-bank=partners&calc-who-payments=client&operations_count=0&calc-nomenclature=slim&documents_count=0&calc-who-docs=client&staff_count=0&calc-more%5B%5D=patent&calc-more%5B%5D=alcohol&period=&price=&price_sber=&rate-name=&email-to=
Then I found function in jquery called post
$.post(path, formData, success, "json");
Request look like:
do.php?bank=partners
As you see it makes post request to my do.php.
Now how I can read this query and work with this data?
I found analog to $.post in jquery. It is $.ajax
Full code:
$.ajax({ url: path, method: "POST", data: {formData: formData} });
It works well.
But I want to work with $.post
I am looking at my url at the moment. And it looks : https://stackoverflow.com?ask=32321
I need something similar to read my query from javascript this url with php
Ok I will explain with example,
If you want to get url parameter values to you have to use,
<script>
let my_variable='<?php echo $_GET['url_param_name'];?>';
</script>
above for more help and understanding. Now you want to send form data to php for processing as I got your answer.
This is sample form.
<form id="my_form" name"my_form" method="POST" onsubmit="return send();">
First name:<br>
<input type="text" name="first_name" value="Mickey">
<br>
Last name:<br>
<input type="text" name="last_name" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
To post above form I will use javascript function,
<script>
function send() {
$.ajax
({
type: 'POST',
url: './path/your_php_file_where_form_data_processed.php',
data:$('#my_form').serialize(),
success: function () {
// do what you need to do on succeess
},
error: function (x, e) {
// for error handling
if (x.status == 0) {
console.log('You are offline!! - Please Check Your Network.');
} else if (x.status == 404) {
console.log('Requested URL not found.');
} else if (x.status == 500) {
console.log('Internal Server Error.');
} else if (e == 'parsererror') {
console.log('Error. - Parsing JSON Request failed.');
} else if (e == 'timeout') {
console.log('Request Time out.');
} else {
console.log('Unknown Error. - ' + x.responseText);
}
}
});
return false;
}
</<script>
Now you need to check carefully your form element names. In php file. Let's look it.
<?php
//include_once './../../classes/Database.php'; import if you have database configurations
//session_start(); make sure to use sessions if your site using sessions
if(isset($_POST))
{
var_dump($_POST); //this will echo your form inputed data.
//if you want use one by one posted data
echo $_POST['first_name'];
echo $_POST['last_name'];
}
else
{
echo 'Data not comes here';
}
?>
Thought this might help your task.
When you see the form elements as a query string, you're not making a POST request, but a GET request.
Change your Ajax code to:
$.ajax({
url: path,
type: "POST",
data: formData
});
What's changed:
I've changed method: 'POST' to the correct attribute: type: 'POST', which will make the Ajax request to make a POST request instead of the default GET.
Changed data: {formData: formData} to just data: formData. There's no need to post it as json when you've already serialized the data.
If you rather want to use $.post, then use:
$.post(path, formData);
Just to be clear, both the $.ajax and $.post-requests above will make identical requests.
Now, in your PHP-code, you can access the values like this:
$calcOwnership = $_POST['calc-ownership'];
...to get the posted data.
I would recommend that you read the documentation about the methods you're using:
jQuery Ajax
Dealing with forms in PHP
I may have misunderstood your question, but in php you can take values from post using $_POST['variable_name'].
<?php
$documents_count = $_POST['documents_count']
?>
In fact this, in your url is not a query, are variables. sorry if it's not what you asked.
Related
I have a button, which on click should insert the users into table.
Basically im stuck in calling the controller function from my javascript.
HTML button.
<div class="continue_btton">
<input type="submit" name="submit" id="SaveSettings" value="<?php echo $this->translate('Update'); ?>" class="update bdr_rds2" onclick="if($('input[name=target_criteria]:checked').val() == 'optedin_users')
{
return someFun()
} else
{
return validateForm()
}
">
</div>
UPDATED:
Javascript
function someFun(){
var urlInsert = '#Url.Action("myFunAction")';
$.get(urlInsert, function () {
});
}
Also tried below, but the controller func not calling
function myFunAction(){
var formData = $("#Preference").serialize();
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
dataType: 'html',
success: function (data) {
$('span.targetCount').text($.trim(data));
},
error: function (jqXHR, textStatus, errorThrown) {
var error = $.parseJSON(jqXHR.responseText);
var content = error.content;
console.log(content.message);
if (content.display_exceptions)
console.log(content.exception.xdebug_message);
},
});
}
Controller.php - Doesnt seem to be called
public function myFunAction(){
echo '+++myFUN---';exit;
}
Error:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
Tried dataType as html, json and text. Still same error.
My guess is either your post data or your response object is not considered valid json and that is why Firefox throws an error (maybe Chrome is more forgiving). What you could check is whether the request is send correctly and whether the response from the server actually arrives and whether it is valid json. You should consider returning valid json from your myFunAction method in your controller (instead of just printing a string like you do right now):
public function myFunAction(){
$data = '+++myFUN---';
return new JsonModel([
'data' => $data
]);
}
Check more on how to properly return Json in Zend for example on this blog post here: https://akrabat.com/returning-json-from-a-zf2-controller-action/
Valid json response should have a content-type header set to application/json and have a valid json string in the response body. Zend JsonModel will help you with this.
When you post data you should also set the content-type of the request to application-json, like that the server understands that you are sending a json object with data.
I never use JQuery but I think it is done like this if I am not mistaken:
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
contentType: "application/json",
});
I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );
so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}
I have to say I saw a dozens of topics similar to my problem, but most of them were typos or spelling.
My PHP file does not seem to receive any data from AJAX POST function (I'm getting Undefined Index). Here is my code:
var login = $("#log_l").val();
var pwd = $("#pwd_l").val();
alert(login);
alert(pwd);
$.ajax({
type: "POST",
url: 'app/menu/login.php',
data: {
login1: login,
pwd1: pwd,
},
cache: false,
success: function (data) {
if (data == 'fail') {
alert('test2');
$('#failure_log').show();
}
else {
document.location = " {$conf->action_root}postlogin";
}
}
});
return false;
And the login.php:
$login = $_POST['login1'];
$haslo = $_POST['pwd1'];
...
I tried with both:
login1:login,
pwd1:pwd,
And:
'login1':login,
'pwd1':pwd,
But in both ways I receive "Undefined index" error in .php file on 'login1' and 'pwd1' variables.
I checked that ajax 'reaches' file and it even receives the echos from .php file, but the variables are not sent/received.
Do you have any ideas what might be wrong?
You need to use file_get_contents to capture ajax calls or you need to define. Check this
How to get JSON data in php ?
Or
you need to set the ajax call as form_encoded_url
contentType: "application/x-www-form-urlencoded",
refer this link
Submitting HTML form using Jquery AJAX
I've made a simple autoload function that loads content when you scroll down on a website. However, there seems to be a few problems when i enable CSRF protection in Codeigniter.
I'm not using a form, so i don't know how i can send the token from A to B when i'm doing my post request as you scroll.
My JavaScript
if (location.href == baseurl) {
$(window).scroll(function(){
if ($(window).scrollTop() > $('body').height() / 2) {
if(doScroll == 1) {
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
$("#wrapper_content").append(data);
if(data == 'Det finnes ikke flere bilder i databasen, WTF!? Send inn forslag ASAP!') {
doScroll = 0;
}
ID++;
});
}
}
});
}
Since Codeigniter expects a TOKEN on all POST request i can't get this to work when CSRF i enabled. Any suggestions?
Error when CSRF is Enabled
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
If i turn CSRF off, everything works great...
You might like to try this code I've used. It works great:
<script type="text/javascript">
$(function(){
$('.answerlist').each(function(e){
$(this).click(function(){
var valrad = $("input[#name=answer]:checked").val();
var post_data = {
'ansid': valrad,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>online/checkanswer",
data: post_data,
success: function(msg){
/// do something
}
});
});
});
});
</script>
As others say - you have to post the CSFR token name and its value with the AJAX request parameters. Here is a simple solution to append it automatically to every AJAX request.
Here is what I put on my main view, so this code is on every page before loading the other javascript files:
<script>
var csfrData = {};
csfrData['<?php echo $this->security->get_csrf_token_name(); ?>']
= '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<!-- ... include other javascript files -->
</body>
</html>
And here is a part of a javascript file that I include on every page:
$(function() {
// Attach csfr data token
$.ajaxSetup({
data: csfrData
});
});
If you want, you can echo both the token name and the hash somewhere appropriate. Something like this.
echo $this->security->get_csrf_token_name()
and
echo $this->security->get_csrf_hash()
Or, you could use form_open() as usual and use the hidden input that is generated for you from your javascript. Disabling the CSRF-functionality is the wrong way to go.
Having reviewed my situation I believe the best option is to use CSRF but reset the token on each attempt. Otherwise the ideas expressed earlier about re-using the cookie token would allow an attacker to resubmit data hundreds of times using the same token which defeats the object of the point.
As such I have created the following function:
public function resetCSRF(){
$this->security = null;
$_COOKIE[$this->config->item('csrf_cookie_name')] = null;
load_class('Security', 'core');
$this->security->csrf_set_cookie();
return $this->security->get_csrf_hash();
}
If for example an ajax based login form fails - call this function in your PHP and then on the javascript side that receives the failure (this solution uses Jquery and a getCookie function from w3schools) would then simply call:
$('input[name="csrf_test_name"]').val(getCookie('csrf_cookie_name'));
Basically what you need to do is get the expected csrf value from the cookie (named 'ci_csrf_token' by default), then post it along with your other data.
You would need to modify this line:
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
to:
$.post(baseurl + 'ajax/images',{'id' : ID,'ci_csrf_token' : $.cookie('ci_csrf_token')}, function(data) {
Might need to install the cookie addon (I'm not really sure; I use mootools). Here is more information: http://aymsystems.com/ajax-csrf-protection-codeigniter-20.
Previous suggestions work great, but rather than using a variable that you can apply in every data-post, I find it simpler to use the ajax-setting to automatically apply this token to every post:
$(document).ajaxSend(function(elm, xhr, s){
if(s.data){
s.data += '&';
}
s.data += '<?php echo $this->security->get_csrf_token_name(); ?>=<?php echo $this->security->get_csrf_hash(); ?>';
});
(works with jquery-1.9.1. I'm not sure about other jquery-versions)
The only problem with a few of the above answers is that a csrf token is only valid for one request, so if you make a post request via ajax and do not refresh the page you will not have the current csrf token for your next ajax post request. This is my solution:
In your CodeIgniter Controller:
$data = array('data'=> 'data to send back to browser');
$csrf = $this->security->get_csrf_hash();
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));
$data = the data to return to the browser
$csrf = new csrf token to be used by the browser for next ajax post request
Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request
Then in your next ajax request (javascript):
var token = data.csrf;
$.ajax({
url: '/next/ajax/request/url',
type: 'POST',
data: { new_data: 'new data to send via post', csrf_token:token },
cache: false,
success: function(data, textStatus, jqXHR) {
// Get new csrf token for next ajax post
var new_csrf_token = data.csrf
//Do something with data returned from post request
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
}
});
Also remember that where I've got csrf_token:token replace crf_token with the name of your token found in application/config/config.php on line that states $config['csrf_token_name'] = 'csrf_token';