extracting array data from (data) in an AJAX call - javascript

This does not answer the question - jQuery Ajax return html AND json data
I can not use the wrap method because I do not have a single html string. I am not using Phery, I have tried the first option here and the second nested call runs before the first so that data is undefined- jquery Use two done callbacks in same function, one with datatype json one without and we are not using html5 only for this. Therefore the referenced answer does not address the question.
In my .done function I have (data) returning. This data is a mixture of php echo's and a single JSON_encode array. Sample data:
.....
//other divs and data above this point
<div id="test">text</div>
{"ids":["1","5","2","6"]}0
AJAX
.done(function(data) {
console.log(data);
func2(json_string)
})
I want to be able to extract and separately work with the array {"ids":["1","5","2","6"]}0. I am trying to pass it along to another function, but only that portion of the data

Here's a very simple content-negotiation example using a query string parameter...
In your PHP, break up your HTML and JSON parts like this
<?php
$format = $_GET["format"] ?? "html";
if ($format === "json") {
header("Content-type: application/json");
echo json_encode(["ids" => [1, 5, 2, 6]]);
exit;
}
?>
.....
//other divs and data above this point
<div id="test">text</div>
Then in your JavaScript code, fetch the two parts using
$.ajax(my_ajax.ajax_url, {
dataType: "html",
// etc
}).done(html => {
// html content here
})
and
$.ajax(`${my_ajax.ajax_url}?format=json`, {
dataType: "json",
// etc
}).done(json => {
// json content here
})

Related

Php file called by ajax isn't echoing javascript code

I'm trying to create a page where a user can upload a file and select the people they want to email it to. Once they click submit, I prevent page refresh and reset their inputs in the form. Now I want to place their previously entered information into a table on the same page (different section of the page).
If you did want to proceed with this concept, you would capture the output of the PHP script in a done() function, insert it in an element on the page, and run eval(). Like this...
$.ajax({
type: "POST",
url: "../FileDrop/dbSystem.php",
data: {tags: JSON.stringify(tags), file:
$('input[name=fileName]').val()};
}).success(function(result) {
$( '#element' ).html(result);
$( '#element script' ).each( () => { $(this).html().eval() })
});
But it would make alot more sense to return data that you use to execute the javascript in your page - that is, keep all that logic together rather than splitting some of it off into a PHP file.
<?php
// php process that checks for 'valid'...
// create a json response
$output = array('valid' => 1);
echo json_encode($output);
?>
.... and in your JS
.success(function(result) {
// result is a stringified JSON object. We need to convert it into an actual JSON object with parse()
result = JSON.parse(result);
// might not matter, but result.valid will be a number which JSON converts into a string. By adding the + right before the variable, that tells JS to use it as a number for the comparison
if (+result.valid == 1) {
$(".outputDiv").show();
}
});

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.

How is dynamically created array in jquery is accessed in PHP

I have created a script that adds items on click into an array.
$(document).ready(function()
{
var array_ids = [];
$('.add').click(function()
{
array_ids.push($(this).parent().siblings('.row_id').html().trim());
alert(array_ids);
});
});
Items are coming from mysql database so I am storing primary keys of items. keys are stored in array like this manner
1,2,3,4,5
Now I want to access this array in php so that I could store in database one by one.
I thought to doing some ajax and this is my code
$('.show').click(function(e)
{
//e.preventDefault();
$.ajax(
{
method: 'POST',
url: 'createsale.php',
data: {items: array_ids},
success: function()
{
alert('done');
}
});
});
I get the done alert but couldn't manage to get it stored in database. Can anyone tell how do I insert those items in mysql?
Send the value from Javascript by using Json {"key":value} or array [1,2,3]. While getting them to use them in PHP, you can use json_decode() to convert the Json or array from Javascript to PHP.
If you want your information from PHP to Javascript, Just use the funtion json_encode() that will send a json string.
Ref: json_encode, json_decode
your createsale.php file should has something like this below code to receive array Data & dont forget to escape your data using mysql_real_escape_string before doing any mysql query
<?php
if(isset($_POST["items"]) && $_POST["items"] !=""){
$arr = $_POST["items"];
//convert JS array to PHP array
$arr = json_decode($arr,true);
//then you have your PHP array => new array(1,2,3,...);
/* use for/forEach loop
for($i=0;$i<count($arr);$i++){
do the task
}
*/
}
?>

POST an Array using Jquery

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

jQuery $.ajax to pass multidimensional array to PHP

I am using jQuery and PHP to write JSON data to my server. I'm processing a decent amount of repeating numeric data (~.75kb), so I want to pass the data to PHP in the form of a multidimensional array.
At the moment I cannot manage to get the data to PHP in a form that it can recognize. I've tried various combinations of sending/receiving as arrays and objects with no success.
The best case scenario would be one in which I pass a the array to the PHP and the PHP converts it to a readable form. I'd rather not use associative arrays or any serializing on the part of the Javascript.
Code... This is giving me a 500 internal server error, which no longer occurs if I omit the passed data variable. (I'm not yet using $data in the php file yet because I know it's not working.)
function generateData() {
// code here
return [ one[ sub_one[], sub_two[] ], two[], three[], four[] /* Etc... */ ]
}
function saveData() {
$.ajax({
url: "scripts/save.php",
data: {
"area":"testing",
"location":"testing",
"name":"testing",
"data":generateData()
}
});
}
<?php
$area = $_GET['area'];
$location = $_GET['location'];
$name = $_GET['name'];
$data = $_GET['data']);
# Performing operations with variables...
echo 1;
?>
Thanks for any help you can offer.
Found a solution:
"data": {
data: generateCellData()
}
The above code passes data as an object to PHP, whereby I can access the original array as $data("data"). I'm still somewhat baffled by why this works when I'm already passing the data and other parameters as an object.

Categories