I have some FormData that are going to be sent into another PHP file using Ajax Post.
var formElement = document.getElementById("form-id");
var form_data = new FormData(formElement);
var csrf_arr = csrf.split("=");
form_data.append(csrf_arr[0],csrf_arr[1]);
$.ajax({
type: "POST",
url: "your-url",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
location.reload();
}
})
What I'm trying to do here is to append a new single data inside the form_data
From my assumption, I could make it just by doing this
form_data.append("key","value");
But it is not sent through the ajax post or even not appended to the form_data as part of the FormData.
Am I making any mistake here or even there is certain rule for that?
Please give any help.
Thanks in advance!
Dear all of my friend,
I'm sorry. Actually it is just a mistake from myself.
I have fix this myself and found the mistake right inside my code.
-- The javascript code --
$( '#submitYours' ).on('click', function(){
var formElement = document.getElementById("form-id");
// Value of formElement consist of pair of data like:
// qst_additional_name_for_the_key=value_of_the_key
var form_data = new FormData(formElement);
form_data.append('break','break');
// to prevent confusion, i'm putting the csrf variable value here
// but i'm not using this as printed variable later, just for security check
var csrf = "your_csrf_token_name=bb6ff34c26ff938822dd339c1682bbcc";
var csrf_arr = csrf.split("=");
var x = 0;
for(x = 0; x < elementId.length; x++){
form_data.append(elementId[x], elementVal[x]);
// Appended data above is just an additional data from some array of data
// and the format is the same with formElement
// qst_additional_name_for_the_key=value_of_the_key
}
form_data.append("master_id",master_id);
form_data.append(csrf_arr[0],csrf_arr[1]);
addLoader("overlay-loader");
runInAnimate("overlay-loader", "bounceInUp");
$.ajax({
type: "POST",
url: "url.php",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
runOutAnimate("overlay-loader", "overlay-loader", "bounceOutDown");
location.reload();
}
})
});
-- The url.php code --
$temp = '';
$arr_in = '';
foreach($_POST as $key => $value){
if(!#$value) continue;
if(substr($key, 0, 4) == 'qst_'){ // This is the real problem.
// The only data taken from the form_data
// are the data containing string "qst_" in it
if(is_array(#$value)){
foreach(#$value as $val){
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$val)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else{
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$value)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else if($key == 'break'){ // remember my additional data? The string "break"
// i just have to chek it here and put into my $arr_in variable,
// so that I can use it now, because the previous conditional allow
// only data containing string "qst_"
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}
print json_encode(array('status' => 'success', 'message' => #$arr_in));
The conclusion is, nothing wrong if we just append the form_data manually
form_data.append('your_key','your_value');
Everything just the matter of how you access the data after it sent to another file.
My Mistake, everyone!
I'm sorry and thanks a lot for your help. :)
Related
I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);
I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code
I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});
I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});
I have the code at the bottom that get's a name from a hidden input type, and I want to send that to a php page but the ajax data returns empty. The console.log on line 4 returns the value, but the console.log on the bottom returns empty. I tried changing the way I assign data inside the ajax call according to this article but this didn't change anything. Any ideas?
$('.uploadImage input[name="userImage"]').on("change", function(){
var image = new FormData($('input[name="userImage"]')[0].files[0]);
var name = $('.hidden').attr("name");
console.log(name);
$.ajax({
type: "POST",
url: "includes/ajax-image.php",
processData: false,
data: name,
success: function(data){
console.log(name);
}
});
});
ajax-image.php
<?php
$name = $_POST["name"];
$dir = ("../user_img/".$name."");
if (!file_exists($dir)) {
mkdir($dir,0700);
}
?>
I added the ; at that line
Feel free to edit both of my code's, I really don't have and idea what to do next
The processData option here is not needed remove that and try again
try this
$('.uploadImage input[name="userImage"]').on("change", function(){
var image = new FormData($('input[name="userImage"]')[0].files[0]);
var name = $('.hidden').attr("name");
$.ajax({
type: "POST",
url: "includes/ajax-image.php",
processData: false,
data: {"name": name },
success: function(data){
console.log(data);
}
});
});
<?php
$name = $_POST["name"];
$dir = ("../user_img/".$name."");
if (!file_exists($dir)) {
mkdir($dir,0700);
}
echo $name;
?>