Not able to transfer variables from javascript to php using ajax [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I tried sending data stored in an array(emp) using ajax and other string variables like 'gtotal' in code but data has not been transferred to the PHP file. It doesn't show any error but when I removed the isset() function it says unidentified index. I tried with different variables but no luck so far. Console function is working in HTML file and returning the values passed but data has not been collected in PHP file-like return value of $_POST shows empty array.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script >
$('#btn').click(function(){
var grandtotal=document.getElementById("gt");
var x =grandtotal.textContent;
var gtotal= String(x);;
var emp={};
emp.name=gtotal;
if(x=== '₹0'){
alert("Add to your cart")}
else{ $.ajax({
method: "POST",
url: "connect2.php",
data: emp,
success: function(data){
console.log(data);
}
});
// location.href='connect2.php'
}});
</script>
<?php
print_r($_POST);
if(isset($_POST['gtotal']))
{
$gtotal = $_POST['gtotal'];
echo $gtotal;
}
?>

The problem is that no item called gtotal is being sent in the $_POST.
Do a var_dump($_POST) to check exactly what is being sent.
You asked for an object to be sent which has an item name. If you see that in the dump then you need to use $_POST['name'] not $_POST['gtotal']

Related

How to convert PHP function to become called using Ajax [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Edit: I am not directly trying call a PHP function using Javascript. The application routing will help frontend to hit the correct function.
I think my problem might have a simple solution, but I am not able to figure it out.
I have a bunch of PHP functions that output HTML. Something like:
<?php
function sample1($param1)
{
//make DB query and loop and print HTML
?>
<div class='some-class'>
Some dynamic output here...
</div>
<?php
}
?>
So like I said there are a bunch of such functions. And I want to call them using Ajax so that their values can be returned and I can print them/update DOM using Javascript. I know that I can update all the functions so that the HTML they generate can be stored into a string and then I can each that string. But is there an easier, cleaner solution to this problem?
Because you are not providing me the javascript ajax call i will focus on the php side.
I am using a simple get Ajax call:
$.get( "https://someKindofLink.php?callFunction=Hallo&doctor=who", function( data ) {
alert( data );
});
On the php side we need to check is the function exists and the run it with all variables in $_GET:
if (isset($_GET['callFunction'])) {
if(function_exists($_GET['callFunction'])){
echo $_GET['callFunction']($_GET);
exit;
}
}
function hallo($params)
{
return "Goodbye".$params['doctor'];
}
I would not advise this approach for security reasons but it should get the job done.

Multiple files not appearing on server side [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a problem when I'm trying to upload files to my server. I have done this many times before so I'm not sure why this is happening now. Nothing has changed to my knowledge.
What's happening is the following:
submit the 1, 2, etc... files through the uploader
check the headers it clearly shows N amount of files.
test php file and put the line print_r($_FILES); it will show only one file, the last one on the file stack specifically.
Just for reference I am using the jquery plugin Bootstrap File Input by Krajee.
file input plugin docs
http://plugins.krajee.com/file-input
JS
$.ajax({
url : '../assets/server/trade/submitTradeForm.php',
type : 'post',
data : data,
dataType : 'JSON',
success : function(response){
if(!response.errors){
if($('#images').get(0).files.length > 0){
$('#images').on('filebatchuploadsuccess', function(event, data, previewId, index){
//$('#tradeForm')[0].reset();
bootbox.alert(data.response.success_message);
});
$('#images').on('filelock', function(event, filestack, extraData){
extraData['trade_form__id'] = response.trade_form__id;
});
$('#images').fileinput('upload');
}else{
bootbox.alert(response.success_message);
}
}else{
bootbox.alert(response.error_message);
}
}
});
PHP
<?php
print_r($_FILES);
if(!empty($_FILES)){
if(!empty($_FILES)){
$names = array();
$files = array();
$mime_types = array();
foreach($_FILES['file']['name'] as $name){
array_push($names, $name);
}
foreach($_FILES['file']['tmp_name'] as $temp){
array_push($files, $temp);
}
foreach($_FILES['file']['type'] as $type){
array_push($mime_types, $type);
}
}
?>
Thank you ahead of time for any and all assistance!
Since the form wasn't posted along with how your file inputs are named, the name attribute for each file requires it to be accessed via an array.
For example:
<input type="file" name="file[]"> with the square brackets.
The brackets declares/signifies it as an array.
Therefore, PHP took in a file alright, only one and is the last one used because of the missing array declaration.
References:
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/features.file-upload.multiple.php

Best way to pass a PHP array to JavaScript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I wondering what the appropriate way is to bring in an array created in PHP and make it available to JS/jQuery (my front end)?
Dont get me wrong.. it 'works'..as far as functionality.. but I have a HUGE openly defined (multi-dimensional, object array) displayed in the source code...etc Nature of the beast? or a better/different way?
quick example
<?php
$totalEntries = mysql_num_rows($result);
$totalEntriesArray2 = json_encode($totalEntriesArray);
?>
<script>
var totalEntriesArray = <?= $totalEntriesArray2 ?>;
</script>
this works. I access the array as intended (multi-dimensional, object array..etc)
Is there a better/cleaner/simpler way similar to above?
I would propose using an Ajax request on the frontend that fetches the JSON array whenever the page is loaded.
A simple way of doing it would be via jQuery.
Backend PHP file (getarray.php) :
<?php
$totalEntries = mysql_num_rows($result);
totalEntriesArray2 = json_encode($totalEntriesArray);
echo $totalEntriesArray2;
?>
Frontend Javascript file (either in page or seperate .js file) :
// Execute Ajax request
$.ajax({url: "/getarray.php", dataType: "json"})
// When complete do something with data
.done(function(data) {
console.log(data);
});
You can get the array using AJAX in jQuery, so you won't have this array shown in your source code.

Pass jquery variable to php within same jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am beginner on coding I need help on passing jquery variable to php inside the same jquery
<script language="javascript">
$(document).ready(function(){
$("#option1).change(function(test));
$("#option2).change(function(test));
function(test){
var select1 = $("select1").val();
var select2 = $("select2").val();
var phpselect1 = '<?php $select1 = '+select1+'?>';
var phpselect2 = '<?php $select2 = '+select2+'?>';
}
});
</script>
I want to pass the the jquery variable to php in this way but I can't pass it anyway. Is there any way to pass the variable like this to php? please help me. ...
Here is an example
AJAX:
var select1 = $("select1").val();
var select2 = $("select2").val();
$.ajax({
url: 'yourphpfile.php',
data: {data1 : select1, data2 : select2},
type: 'POST',
success: function(data){
//do something with the returned data
}
});
Server-side PHP (yourphpfile.php). To assign a value passed from AJAX, do the following;
$phpselect1 = $_POST['data1']; //should be value of select1 from JS
$phpselect2 = $_POST['data2']; //should be value of select2 from JS
PHP is handled server side (step 1). Javascript is done on the client-side (step 2). You're trying to tell the page to do something on the step that has already been done.
Also, you're trying to assign PHP variables using JS? If you need data to get to PHP, use GET/POST variables and pass relevant data to the PHP upon a page load/refresh.
You are doing it wrong. You need to use Ajax to send a Get or Post request to the server. In that request you can put your variable.

Run PHP file to get value for field [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I know I can include a PHP file with an echo to use as a value in form:
value="<? include('generatecode.php'); ?>">
But is it possible to send a value to this php file before it generates the code? For example in this PHP file it has an if statement relating to a value...
if ($value == 1) { do this } else { do this }
Is there any way I can use a checkbox that sends $value to this php file and updates if the box is checked or unchecked?
Thanks in advance.
You need Ajax to do this:
Lets suppose u have a checkbox with an id of #check then :
$('#check').click(function() {
var checkVal;
if($(this).is(':checked')) {
checkVal = 'checked';
} else {
checkVal = 'unchecked';
}
$.post('generatecode.php', {input : chechVal}, function(data) {
// do something with the data returned from generatecode.php
alert(data);
});
});
In the generatecode.php file:
//catch the checkVal variabe u sent
$checkVal = $_POST['input'];
//do somthing with it, depending what you do the output will be in the *data* variable in the above js script
if($checkVal == something) {
//do something
} else {
//do something else
}
NOTE :
What the above code does is from the page you are at the moment catches if the checkbox with id #check is checked or not.Then sends to generatecode.php the relative checked or unchecked ,there this gets caught in a PHP variable and depending on its value performs an operation which result then gets back to your starting page as a jquery variable data, which then you can manipuate as you like instead of alerting it as i did above.
Hope this helped feel free to ask for any clarifications.
You can assign a value to your variable in your main file. As soon as you include the file, $value will be available in your included file.
<?php
$value = 1;
?>
value="<?php include('generatecode.php'); ?>">
This is kind of a weird way of assigning a value to what I assume is an HTML input element. Typically, you would generate some value and assign it to a variable in your include file and then output the variable.

Categories

Resources