POST an Array using Jquery - javascript

I am trying to UPLOAD multiple file using Post jQuery method but I get an error of undefined index when trying to view the array result. Tried to search the answers but still unable to do it. What is the correct way to do this. Below are the example of my codes,
HTML
<input type="file" name="others[]" multiple="multiple">
jQuery
$(document).ready(function(){
$("#submit").click(function(){
var array = [$("input[name='others']").val()],
others = {
"upload[]": array,
},
id = $("input[name='id']").val();
$.post('updated-file-others.php',
{
others : others,
id : id
}, function(data){
$("#result_post").html(data);
});
});
});
PHP
if(isset($_POST['id'])){
$id = $_POST['id'];
$others = array($_FILES['upload']['name']);
}
echo "<pre>"; print_r($others); echo "</pre>";

A couple of things
$("input[name='others']") doesnt match others[] in your HTML. Why dont you use an id and match it?
You might need to ensure that you have
enctype="multipart/form-data" inside your form.
whats the output of $("input[name='id']").val(); You have not provided any clue in your code.
Refer to php documentation on file upload - Uploading multiple files
Refer to this stackoverflow question - Multiple file upload in php

I would suggest formatting your desired array as a JSON string, and then using php_decode to convert it to an array.
$json = '["apple","orange","banana","strawberry"]';
$ar = json_decode($json);
echo $ar[0]; // apple
More info about JSON with PHP can be found here:
http://www.dyn-web.com/tutorials/php-js/json/decode.php

The file upload via ajax using $.post doesn't work this way, to achieve this, you must configure the ajax call as follows:
$.ajax({
type: 'POST',
url: your_url,
data: new FormData($('#form-id').get(0)),
processData: false, //set it to false to send a DOMDocument, or other non-processed data
contentType: false //pass false to tell jQuery to not set any content type header
}).done(function (data) {
alert('success');
})
This will send you the entire form to the server, and there you can process the files and other fields as you want.
You can read a little more about the processData and contentType configuration in the jQuery ajax documentation
Please let us know if this work for you,
Greetings

Related

How to get values from url to js?

I am having the trouble to find a solution how I can get the values from the object which is requested from link from my web..
The thing is that I was created method in PHP to get the data from the database of the values of one object which I have to parse in my modal window so I don't have to refresh page to get details about my product.
Here is PHP code to get the details which perfectly works and my URL returning the $data object with values.
Controller.php
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',$data);
}
And the model function for php:
public function getOrderInfo($id){
$this->db->query("SELECT * FROM ORDERS WHERE id ='$id'");
$row = $this->db->single();
return $row;
}
And the thing is that I learned easily how to get id in javascript of my object which has the id in database.
here is code to get id and i understand it how it works:
HTML:
<a class="fa fa-file-audio-o edu-back-restart" href="#"
data-toggle="modal" data-target="#InformationproModalftblack"
id="<?php echo $activeOrders->id; ?>"
onclick="showDetails(this)">INFO</a>
NOTWORKING CODE:/mytry/
Javascript to get object id and to get object and its values (object and values is my problem):
<script>
function showDetails(a) {
$("#"+a.id).click(function () {
alert(a.id);
});
//NOT WORKING-How to get object from url?
$.ajax({
url: "localhost/test/orderinfo/280",
method: "GET",
datatype: Object,
success: function(response){
var customer =response;
console.log(response);
}
});
}
</script>
I don't know how to get whole object from that url with js or ajax and i don't know how to get object values as : id, name, street..
Thank you so much for you help...
sorry if i have some mistakes in explanation the problem.
When you are running the ajax call, the URL field should be referencing the PHP script that you are trying to run, e.g:
url: "localhost/test/orderinfo/Controller.php",
Next, make sure the PHP script is calling the orderinfo() function at some point. If you have this function in a larger script and don't have any logic for invoking it, I would recommend putting the function in a smaller PHP file whose sole purpose is to return the output of that query. For example:
//Whatever you need to import to make your query calls
//Whatever variables you need to initialize for your query calls
$temporary_id = "ABC123";
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',$data);
}
return orderinfo($temporary_id);
If you could provide any information about the object you are returning as well as the output of that console log, that would be extremely helpful.
Edit: Just noticed the comments, you could pass the id value in as data:
url: "localhost/test/orderinfo/Controller.php",
data: {'id':id_variable},
And then in the PHP, get the id value using $_SESSION['id'];.
Alternatively, you could pass it as a URL parameter:
url: "localhost/test/orderinfo/Controller.php?id=ABC123",
data: {'id':id_variable},
And get in the PHP using:
$id = $_GET['id'];
The value of the ID should be stored in that PHP variable as ABC123.
Hope this helps.
The best way for sending data from PHP to JS is encoding them as JSON object with json_encode.
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',json_encode($data));
}
so in your JS you can decode it with parseJSON like
<script>
function showDetails(a) {
$.ajax({
url: "/test/orderinfo/280",
method: "GET",
datatype: JSON,
success: function(response){
var obj = jQuery.parseJSON(response);
console.log(obj);
}
});
}
</script>
Note that you don't need to return whole $data in this object, and probably you even should not do it for performance and security reasons.
Instead, just prepare the object with only the data required for JS and send them as shown.

Failing to send to $_POST but $_SESSION says something else

I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}

post json data to php and echo result

I'm a struggling learner of php and javascript and Have been searching frantically for a solutionbut to no avail. I am trying to send a json object/string from one page to another using php and then echo the results in that new page (eventually to generate a pdf using tcppdf) . So basically some javascript generates an object, pageStructure, in one page, which I then stringify:
var jsonString = JSON.stringify(pageStructure);
alert(jsonString);`
The alert pops up fine.
I now want to send (post) this to another php file getdata.php and then play around with it to construct a pdf.
I have tried posting with forms but updating the value of an input in the form with jsonString won't work.
**ADDITION - EXPLANATION OF MY PROBLEM HERE
I created a form as follows:
<form action="getdata.php" method="post">
<textarea type="hidden" id="printMatter" name="printMatter" value=""></textarea>
<button type="submit"><span class="glyphicon glyphicon-eye-open" ></span></button>
</form>
I have some code after constructing jsonString to set the value of the textarea to that value:
document.getElementById('printMatter').value = jsonString;
alert(document.getElementById('printMatter').value);
A submit button activates the form which opens the getdata.php page but I noticed two things:
(1) before sending the jsonString string is full of escapes () before every quote mark (").
(2) when getdata.php opens, the echoed jsonString has changed to include no \s but instead one of the values ('value') of an object in the json string (a piece of svg code including numerous \s) - for example (truncated because the value is a very long svg string, but this gives the idea):
{"type":"chartSVG","value":"<g transform=\"translate(168.33333333333334,75)\" class=\"arc\">...
has changed to integers - for example:
{"type":"chartSVG","value":"12"}
I don't understand how or why this happens and what to do to get the full svg code to be maintained after the form is posted.
**
I have tried using jquery/ajax as follows:
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
success: function(){
alert('it worked');
},
error: function(){
alert('it failed')}
})
I'm getting the success response but I end up on the same page instead of getting the new php file to just echo what it is being sent!
The php script contains the following:
<?php
echo $_POST['printMatter'];
?>
But this doesn't work. Nor does trying to add a header to the php page (e.g. header('Content: application/json'). I end up staying on my original page. How do I get this to leave me on the new page (getdata.php) with an echo of the json string?
Can anyone explain what I am doing wrong or how I can get what I want?
Thank you so much.
**ADDITION
This is indicative of how I get the jsonString object:
function item(type,value) {
this.type = type;
this.value = value;
}
for (i=0;i<thePage[0].length;i++) {
pageid = thePage[0][i].id;
var entry = new item("page",pageid);
pageStructure.push(entry);
}
var jsonString = JSON.stringify(pageStructure);
So I end up with a series of pages listed out in the jsonString.
Try changing $_POST to $_GET since your AJAX request is doing a HTTP GET and not a HTTP POST.
UPDATE
This doesn't leave me on the page I want to be on. I don't want to refresh the page but just redirect to a new page that receives the posted json data.
By this is essentially a page "refresh", though perhaps "refresh mislead you because it can imply reloading the current URL. What i meant by refresh was a completely new page load. Which is essentially what you are asking for. There are a few ways to go about this...
If you data is pretty short and will not violate the maximum length for a URI on the webserver then you can jsut use window.location:
// send it as json like you are currently trying to do
window.location = 'getdata.php?printMatter=' + encodeURIComponent(jsonString);
// OR send it with typical url-encoded data and dont use JSON
window.location = 'getdata.php?' + $.serialize(pageStructure);
In this case you would use $_GET['printMatter'] to access the data as opposed to $_POST['printMatter'].
If the data has the potential to produce a long string then you will need to POST it. This gets a bit trickier since if we want to POST we have to use a form. Using JSON and jQuery that is pretty simple:
var form = '<form action="getdata.php" method="post">'
+ '<input type="hidden" name="printMatter" value="%value%" />'
+ '</form>';
form.replace('$value%', jsonString);
// if you have any visual styles on form that might then you may
// need to also position this off screen with something like
// left: -2000em or what have you
$(form).css({position: 'absolute'})
.appendTo('body')
.submit();
If we wanted to just send this as normal formdata then it would get more complex because we would need to recursively loop over pageStructure and create input elements with the proper name attribute... i wouldn't got that route.
So the final way (but i dont think it would work because it seems like youre tryign to generate a file and have the browser download it) would be to send it over AJAX and have ajax return the next url to go to:
JS
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
type: 'json',
success: function(data){
window.location = data.redirectUrl;
},
error: function(){
alert('it failed')}
});
getdata.php
// do something with the $_POST['printMatter'] data and then...
$response = array(
'redirectUrl' =>$theUrlToGoTo
);
header('Content-Type: application/json');
print json_encode($response);
You are using AJAX. By nature AJAX will not refresh the page for example if you do this:
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
success: function(data){
alert('it worked');
alert('You sent this json string: ' + data);
},
error: function(){
alert('it failed')}
});
Also note that i changed your type from 'get' to 'post'... The type set here will in part determine where you can access the data you are sending... if you set it to get then in getdata.php you need to use $_GET, if you set it to post then you should use $_POST.
Now if you actually want a full page refresh as you implied then you would need to do this another way. How you would go about it i cant say because you havent provided enough of an idea of what happens to get your jsonString before sending it.

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Passing JavaScript ID Value to PHP for download

I am pretty new to PHP but I am learning fast.. I have been trying to use AJAX to Pass An ID to PHP.
With this ID I use SQL to get the path of a file from the database than use it to download the file.
However after some research this is not possible and I couldn't understand alternives... maybe there is a workaround?
These are my JavaScript function; I used JSON because I was passing an Array of IDs because I intend to use it in future for multiple downloads. I get the IDs from a table row click.
$('.btnDownload').click(function() {
$.ajax({
url: 'scripts/downloadFile.php',
type: "POST",
data: {id: JSON.stringify(fileID)}
});
});
And my PHP to attempt to download the file;
<?php
$data = $_POST['id'];
$data = json_decode("$data", true);
$countArray = count($data);
$counter = 0;
while($countArray > $counter){
$getID = $data[$counter];
// My sql connections and queries, jumped to the fetch part
$filePath = $fetch['filePath'];
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename='.basename($filePath));
readfile($filePath);
exit;
$counter++;
}
?>
How ever this script alone works when I give a static path and run it with my browser.
I would like some help on alternatives on achieving the results.
To solve the problem relating to the popup not popping up, try something like this instead of ajax:
$('.btnDownload').click(function(event) {
var url = 'scripts/downloadFile.php?id=' + JSON.stringify(fileID);
window.location.href = url;
event.preventDefault();
})
The user should be presented with a "save file" dialog and the browser will remain on the same url due to the disposition headers set by the php file.
The parameter that you're passing to downloadFile.php is called id, not ID (for example: data: {id: JSON.stringify(fileID)})
You need to update your PHP assignment to use the correct key as follows:
$data = $_POST['id'];
Mega.co.nz uses a similar approach. It requests the downloads per AJAX in order to allow a custom download progress bar. Once the download is finished, it is copied (technically it is downloaded from cache onto disk). You could do it somewhat like the following code. Of course, if you want to implement a custom progress bar, you'd need to fetch the unfinished response and update respectively.
$('.btnDownload').click(function(){
$.ajax({
url : 'scripts/downloadFile.php',
type : 'POST',
data : {id : JSON.stringify(fileID)}
})
.done(function( response ){
location.href = 'data:,' + btoa(response);
});
});
btoa converts the input into a Base64 encoded string which you can then use in conjunction with the Data URI Scheme to issue a download.

Categories