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;
?>
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 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. :)
I am having problems passing the variable to the php page.
Here is the code below:
var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string
$.ajax({
type: "POST",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
PHP:
$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here
$con=mysqli_connect("localhost","root","pass","mydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");
mysqli_close($con);
}
I'm I missing something? The actual data is saving to the database BUT $first and $second value is not being passed to the php file.
You are using the POST type, retrieve it in POST :
$first = $_POST['first'];
$second = $_POST['second'];
Or change your JQuery call :
$.ajax({
type: "GET",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
This is appening because your are passing data throw POST method and try to get with GET so change those two lines
$first = $_POST['first']; //This is not being passed here
$second = $_POST['second']; //This is not being passed here
Or simply change your method to GET in your jquery
type: "GET"
You are using type: "POST" in ajax and trying to fetch using $_GET, try
$first = $_REQUEST['first']; //This is not being passed here
$second = $_REQUEST['second'];
And there is a method to pass data like that
$.ajax({
type: "POST",
url: "test.php",
data: {first: varFirst,second: varSecond},
success: function(){
alert('seccesss');
}
});
And there you can use
$_POST['first'];
$_POST['second'];
Hope it helps.