I think I am getting close on this, but for some reason the json data doesn't print out when it gets to the php page.
Here is my form with some dummy data:
<form id="add_form" action="javascript:void(0);">
<fieldset>
<input type="text" value="5" name="dogs" id="dogs" />
<input type="text" value="10" name="cats" id="cats" />
</fieldset>
</form>
Here is the related function (runs from a button, not shown above):
function add()
{
$.ajax({
type: 'POST',
cache: false,
url: 'add.php',
data: { json: $('#add_form').serialize() },
success: success
});
}
Finally the php that I can't seem to make work:
$json_object = json_decode($_POST['json']);
echo $json_object;
What I am really after is being able to get at the values for each element in the form (no matter how many form elements there are). As always, appreciate any advice you are willing to give.
Instead of,
function add()
{
$.ajax({
type: 'POST',
cache: false,
url: 'add.php',
data: { json: $('#add_form').serialize() },
success: success
});
}
You have to use,
function add()
{
var data = $('#add_form').serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'add.php',
data: data,
success: success
});
}
Then access like,
$_POST['dogs'];
there is no need to decode json because your form data passed to php page as "POST" type. so just do as follow.
$json = $_POST['json'];
print_r($json);
If you want to send JSON, you have to create JSON first. .serialize does not return JSON, it returns a query string, as you can read in the documentation:
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>.
Maybe you want:
data: { json: JSON.stringify($('#add_form').serializeArray()) },
but that seems to be overly complicated. Just use
data: $('#add_form').serialize(),
and access the data on the PHP side via $_POST['form_field_1'], etc.
Related
I have this code for example
<?php
if(isset($_POST['goose'])){
echo '<div>goose</div>';
}
?>
<form action="goose.php" method="POST">
<input type="submit" name="goose" />
</form>
How can I write something like this but in AJAX? I don't know this language.
I recommend using jQuery.
$.ajax({ // begins our async AJAX request
type: "POST", // defining as POST
url: "goose.php", // page to request data from
data: ["goose":$("input[name=goose]").val()], // define POST values
success: function(output){
alert(output);
},
error: //do something else
});
Because we have set the type to POST our data will need to be in the form of an associative array with "goose" being equivalent to $_POST["goose"].
data: ["goose":$("input[name=goose]").val()],
The success is what will happen if the data is able to be sent correctly with output being what is returned. In our case output = <div>goose</div>.
success: function(output){
alert(output);
}
error can also have a function but here you will want to tell the script what do do if say goose.php is un-reachable.
No need for extra frameworks. Just use fetch api.
<form action="goose.php" method="POST" onsubmit="submit(event, this)">
<input type="submit" name="goose" />
</form>
Javascript:
function submit(event, form) {
event.preventDefault();
fetch(form.action,{
method: 'post',
body: new FormData(form)
}).then((data) => {
console.log(data);
});
}
I am trying to pass an input field which has its values to be in an array with some other input fields into PHP using jquery-Ajax formData, everything seems to work fine except that I am having problems with successfully passing the array values and I have tried a whole lot which without evident success.
firstly i tried SerialiseArray() method. Here is my code below
<form>
//other input field below...
.
.
.
//this is the code to include my array which is in _categories-list.php
<div class="form-group">
<label for="artist">Select Categories </label>
<?php include('../_categories-list.php') ?>
</div> </form>
var Category = $('#categoriesList').serializeArray();
$.each( Category,function(i,field){
formData.append('categoriesList', field.value + "");
});
$('.msg').text('Uploading in progress...');
ajaxcall = $.ajax({
url: 'page-videoFunc.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',});
This particular method I used only sends one value of the chosen options in the array. example:
//output: let's say the person chooses blues, hip-hop
hip-hop //will be the only value sent
I also tried another method similar
<form>
//other input field below...
.
.
.
//this is the code to include my array which is in _categories-list.php
<div class="form-group">
<label for="artist">Select Categories </label>
<?php include('../_categories-list.php') ?>
</div> </form>
var Category = $('#categoriesList').serializeArray();
formData.append('categoriesList', Category);//note that code changes here from the above method used
$('.msg').text('Uploading in progress...');
ajaxcall = $.ajax({
url: 'page-videoFunc.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',});
This one sends all the values of the array that is chosen but sends but as an object example:
//output
[object object] [object object]
And lastly, I tried this: serialize();
<form>
//other input field below...
.
.
.
//this is the code to include my array which is in _categories-list.php
<div class="form-group">
<label for="artist">Select Categories </label>
<?php include('../_categories-list.php') ?>
</div> </form>
var Category = $('#categoriesList').serialize(); //Note i used just serialize() here
formData.append('categoriesList', Category);
$('.msg').text('Uploading in progress...');
ajaxcall = $.ajax({
url: 'page-videoFunc.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',});
Which partially works and sends all the values but in a format i seem not to get a way to get the values out, example:
//output
categoriesList%5B%5D=blues&categoriesList%5B%5D=hip-hop
I don't know how to get only the values from the query strings in this method so I could put it into the database
Please help me provide a solution to any of the above method I am using, I have worked on this nearly 42 hours and its slowing down my project
call the ajax like.
var Category = $('#categoriesList').serialize();
$.ajax({
url: 'page-videoFunc.php',
type: 'post',
data:{
action:'update_data',
form_data:Category
},
});
In page-videoFunc.php file, parse the form_data using parse_str.
if($_POST['action'] =='update_data'){
parse_str($_POST['form_data'], $my_form_data);
echo "<pre>";
print_r($my_form_data);
}
After using parse_str to cut off added URL to serialized data, to get all values of the array, you should do this:
parse_str($_POST['name'], $output);
$x = $output["name"];
foreach ($x as $key => $value) {
echo $value;
}
I have written front end simple login application using Jquery, ajax and json, I want to send json information to php and it has to retrieve the data of json and if successful it has to redirect to another page, Here is the simple front end code I am using.
!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="login.css">
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("#submit").on('click',function(){
var person={
user:$("#user").val(),
pass:$("#pass").val(),
}
$.ajax
({
type: "POST",
url: '/test/login.php',
dataType: 'json',
async: false,
data: person,
success: function () {
}
})
});
});
</script>
</head>
<body>
<div id="loginstyle">
<form action="login.php" method="post">
<table>
<tr>
<td>
Email:</td><td><input type="email" name="email" id="user" ></td>
<tr><td>Password:</td><td><input type="password" name="password" id="pass"><td></tr>
</table>
<input type="submit" value="submit" id="submit">
</div>
</form>
</body>
</html>
Can anybody suggest me how to decode the json data and print the user and pass in login.php
You have to do it this way
$.ajax
({
type: "POST",
url: '/test/login.php',
dataType: 'json',
async: false,
data: person,
success: function (data) {
var res = $.parseJSON(data);
//DO SOMETHING WITH res
//IF res is some value, redirect, otherwise not.
}
});
1st: You can use e.preventDefault() while submit to prevent reloading the page
$("#submit").on('click',function(e){
e.preventDefault();
2nd: while you use type: "POST", and pass user: and pass: you need in php
<?php
echo($_POST['user']);
echo($_POST['pass']);
?>
and in ajax success callback function
success: function (data) {
alert(data);
}
in this case maybe no need to use json as a dataType
3rd : It will be good to Take a look at
What does "async: false" do in jQuery.ajax()?
$.ajax - dataType
encode json using php?
How to get JSON data on ajax call
how to parse json data with jquery / javascript?
when you call $.ajax, function, you define a parameter called successful and you usually give it a function to be executed once the call is successful meaning: the server has been called with the given parameters and a response was received. The response could (or could not) contain additional data passed in the data variable that you would use when calling the successful function.
Here is the tricky part: although the parameter is called successful, in your context, the provided credentials might not be valid, so, in your PHP code, you would notify the ajax call that the login attempt was not accepted, and you might want to pass the information inside the data variable.
The above scenario describes an unsuccessful login attempt, but a successful ajax call. Here is what you need to do in your javascript code to distinguish whether the user should be forwarded to next page or not:
$.ajax({
type: "POST",
url: '/test/login.php',
dataType: 'json',
async: false,
data: person,
success: function (data) {
// your php code should populate the (data) variable
// in this example I used the variable as a string,
// but you could use json notation and have a more
// complex structure (like data.valid = true)
if (data == "valid_credentials") {
window.location.href = 'nextpage.php';
}
else
{
alert('the provided credentials were not accepted.');
}
}
});
Have a ajax request sending data to a WordPress action which works fine however I can receive the nonce value perfectly but the email input isn't being sent. I know I'm targeting the right value. It does not want to get the value of the email input. If I hardcode a value into the input it will see it. I need to get the user entered value and send that to the ajax script. The code is also run on document load and is after the form values have been rendered.
Input field looks like this:
<input type="email" name="cjd_email" id="cjd_email" class="cjd-email-input"/>
The jquery selector looks like:
var cjd_email = $('#cjd_email').val();
The ajax call is:
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: {
action: 'cjd_subscribe',
nonce: cjd_nonce,
email: cjd_email
},
cache: false,
success: function(data) {
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
}
else {
console.log(message);
}
}
});
Thanks :)
I am assuming you are having a class on form i.e. cjdajax. Then use serialize method to send data instead of any other.
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: $('.cjdAjax').serialize(),
cache: false,
success: function(data) {
//your code
}
});
Depending on the browser you use, type=email might not be supported by jQuery / JavaScript and thus the valid() method could return rather strange values. As an alternative, one can use type=text with input validation.
Also, you should Review the success function : You attempt to apply the find()-method on text rather than a DOM element. The code could be corrected if the server returned a JSON-encoded string, so in JavaScript you could convert the string back into an object.
In PHP one could write print(json_encode($yourArray, true)); (notice how the true flag is required for associative keys), while
...
success: function(data){
var yourObject = JSON.parse(data);
if (yourObject.responseData === "success")
console.log(yourObject.message);
},...
could replace the respective current JavaScript passage.
Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.
First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);
In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.
There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.