Ajax receive a collection of objects from Laravel - javascript

I currently am attempting to create my own instant messenger for my site (NOT using a plugin - am attempting to hand make this for learning purposes) and I am looking to try to send an ajax request to the server for a list of all messages between two users. My question is this: can ajax 'read' a collection of Message objects sent from Laravel (doubt it) or does it need to be formatted in a certain way/manner? I initially thought to use lists to get the sender_id along with the message (the order is by date by default), however, I don't think that javascript can read PHP's (not)-arrays. The only viable solution I have came up with thus far is to send either 1 array with sender_id followed by the message for the entire conversation OR 2 arrays- one with all sender_id's in order and a second with all messages in order.
Thanks.

You can use JSON for communicating between PHP and JavaScript (look up PHP json_encode and json_decode functions), it'll allow you to pass complex arrays almost natively between the languages.
EDIT: a few examples to give some indication how it works, I'm using jQuery for my examples here
Requesting information from a PHP script via AJAX:
$.ajax({
method: 'GET',
dataType: 'json',
success: function(data) {
for (i in data.messages) {
output(data.messages[i]);
}
}
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can output:
$messages = array(
array(
'id' => 1,
'message' => 'Awesome',
'sender' => array(
'id' => 1, 'name' => 'John',
),
),
);
echo json_encode(array('messages' => $messages));
Sending information using JSON via AJAX:
// Example data object, you can have this infinitely nested
var data = [
{id: 1, "message": "test" }
];
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can then read this using:
$data = json_decode(file_get_contents('php://input'), true);
// This becomes a simple 2D PHP array which is an exact representation as your JS object. The above example data can be output as:
foreach ($data as $message) {
echo $message['id'] . ' - ' .$message['message'];
}

Related

Cannot read NULL variable in PHP after posting JSON array through .ajax()

I'm having a problem like many other people, being able to read a PHP array variable after having sent it through ajax() post. Ajax is succeeding and displaying the returned data, which is NULL. I have already thoroughly researched SO solutions for this JSON/PHP problem, and my problem description shows 'almost' EVERY solution on SO so far.
On the PHP side I've tried:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
(Skipping over $HTTP_RAW_POST_DATA (deprecated) because it's equal to file_get_contents('php://input')
and also:
$data = json_decode($_POST["a_arr"], true);
I've already tried clearing the UTF-8 BOM with the sed command
sed '1s/^\xEF\xBB\xBF//' < index.html > index2.html
My .ajax() looks like this:
$.ajax ({
url:"file.php",
method:"post",
contentType: "application/json; charset=utf-8",
data: { a_arr : JSON.stringify(arr) },
})
.done(function(response){
$("#status").html(response);
});
On the Javascript side here is my array:
var arr = [{"name":_name, "phone":_phone, "email":_email, "repname":repname, "repnumber":repnumber, "office":office}];
ajax_post(arr);
I've checked to make sure there is no JSON formatting error, the following successfully shows me a valid JSON formatted array:
var data_arr = JSON.stringify(arr);
document.getElementById("status").innerHTML = data_arr;
You need to change to:
data: JSON.stringify(arr),
When you give an object to the data: option, it converts it to URL-encoded format, not JSON.
Or you can leave the data: option as it is, but get rid of the contentType: option, and then you should use
$data = json_decode($_POST['a_arr'], true);

How to fetch data from the database into a javascript file and store it in array?

I am building a currency converter app for my school project and at the moment I am trying to get data from the database into a .js file. The exact goal is to get data from the database and save it into an array within a .js file.
As far as I know there is no way to get data from the database directly into a JavaScript file, so I am trying to make use of JQuery and PHP combination as pointed out in this thread.
I have a database called 'currencies' which has six columns: id, basecur1, basecur2, basecur3, basecur4, basecur5.
id field is for user id, and basecur_ fields are for storing user's prefered currencies and can only contain three characters of a currency code (like USD or GBP) or be empty. I need to get a result looking like const array_name = ["EUR", "GBP", "USD"];
Please note that I am using CodeIgniter PHP framework for back-end.
In this file query.php I am trying to create an array from the data fetched from the database and echo it:
<?php
$current_user = $this->session->user_id;
$query = $this->db->get_where('currencies', array('id' => $current_user));
$row1 = $query->row();
$base_currencies = array($row1->basecur1, $row1->basecur2, $row1->basecur3, $row1->basecur4, $row1->basecur5);
$post_data = json_encode($base_currencies);
echo $post_data;
?>
Unfortunately, I don't have deep understanding of JavaScript, so I can't really say what's wrong with this JS code, which is taken from the thread mentioned above, but it doesn't really work for me:
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = JSON.stringify(data);
}
});
return result;
}
});
var array_name = $.getValues("query.php");
Any help will be much appreciated.
Because of these line you already have a valid json string:
$post_data = json_encode($base_currencies);
echo $post_data;
exit;
and since you already set the dataType: 'json' jquery will parse the result as a json string regardless of the header.
Thus:
success: function(data) {
result = data;
}
You can debug using console.log it is a valuable tool for learning and making sure you are getting what you want at various points in your code. As another user suggested, make sure you aren't getting any 404 errors in the console. query.php doesn't look like a valid CodeIgniter route.
In your php file.
header('Content-Type: application/json');
in your ajax function
success: function(response){
console.log(resposne)
}
see if you are getting anything
I think you are not passing a valid url
try adding an error function to get some info:
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = data
},
error: function(error) {
alert(error);
}
});
return result;
Update: Try to output the variable directly as alex has suggested

Send array with Ajax to PHP script in wordpress

I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps

How can I return an array and HTML data in an AJAX response?

I have an array like this in my PHP page named new1.php:
$arr = ['value 1', 'value 2', 'value 3'];
$html = '<div>huge data with all tags like a page</div>';
$response = json_encode('array' => $arr, 'html' => $html);
echo $response
In the calling page, when I console.log(data.html) it gives undefined. The same happens for console.log(data.array);. Here is my AJAX code:
$.ajax({
url: "new1.php",
type: "POST",
data: { somedata: somedata },
dataType: "text",
success: function(data) {
console.log(data);
console.log(data.html);
console.log(data.array);
}
});
Most importantly, I want to know what is the best way to return a page with other data from AJAX response?
from your php code where you do json_encode add this to the top of the page
header("Content-Type: application/json");
then your encode should take in array as parameter instead
json_encode(array("array"=>$arr, "html"=>$html));
it should see your record as json now and please change ur dataType to json from Jquery intelligence guess from the server state (jquery) it will automatically take json instead
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
You should be json parse, because you are json encoding from php file, and as there is data type of your ajax is text so you need to parse the json.
$.ajax({
url:"new1.php",
type:"POST",
data:{somedata:somedata},
dataType:"text",
success: function(data){
data = JSON.parse(data);
console.log(data);
console.log(data.html);
console.log(data.array);
}
});

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Categories