Get json array from php to javascript with $.getJSON() - javascript

I have application.php page where json array is echoed with php. On the client i want to get the json array with $.getJSON() on button click when form is submitted(submitHandler). The problem is that if I run alert() or console.log() in $.getJSON() nothing happens(i only see GET execution in console).
Code:
$.getJSON('../views/application.php', function(data) {
alert('alert1');
if(data) {
document.write(data.resp);
alert('alert2');
}
else {
alert('error');
}
});
GET http://localhost/app/views/application.php

you can use var temp in your script and store your data inside that variable.
var x;
<script type="text/javascript">
x='<?php echo $comparisonResult; ?>';
</script>

Sounds like a use case for sessionStorage or cookies.
Use sessionstorage if you don't need to support IE7.

I think the best way is to return the needed server data in the response of your first post request, just like this :
$.post( "/first.php", function( serverData ) {
var param = serverData.something;
...
$.post( "/second.php", param, function( data ) {
...
});
});
If you are using the two request in two different pages, you can store serverData in localStorage.
Edit after your clarification:
If you need to get data before ajax post when you click on a button, you can do this way :
$("#second-button").click(function() {
$.getJSON("/data.php", function (serverData) {
var param = serverData.something;
$.post("/second.php", param, function(data) {
...
});
}
});
Edit 2
For some reason (wrong url, invalid json, and so on) your $.getJSON fail.
Try this for debug:
$.getJSON("/data.php", function (serverData) {
console.log(serverData);
}).fail(function(j, t, e) {
console.error(e);
});

Related

Can't get AJAX request to return data from controller

I have a page with a list, with a number of checkboxes. When I check the boxes and click submit, I want an AJAX request to take the value of the checkboxes, stick them into an array, send that array to my 'setCourses' method, where I will use the array values to pull data out of the DB and then send that data back to the page as JSON. This is my first time trying AJAX so sorry for any silly mistakes!
The AJAX request seems to work, sending the array to the controller method, but I can't get the success function to return the data I want to send back from the controller. Here is what I have so far:
setCourses Method
public function setCourses(Request $request) {
$courses = $request->get('selectedCourses');
//Here I will use the "$selectedCourses" array above to query the database for specific info,
//but for now I am just trying to get the AJAX to return anything!
return response::json($courses);
}
AJAX to get checkbox values, add to array and send request
$('.submitCourses').on('click', function(){
var selectedCourses = $("input:checkbox[name=courseID]:checked").map(function(){
return $(this).val();
}).get();
console.log(selectedCourses);
$.ajax({
url: 'report-generator/custom/selected',
type: 'GET',
data: { selectedCourses: selectedCourses },
success:function(courses){
console.log(courses);
}
});
});
try this one
to change use helper function instead of facade
return response()->json($courses);
var obj = { selectedCourses: selectedCourses };
$.get('/eport-generator/custom/selected', obj,
function (response) { console.log(response);}
).fail(function () {
console.log("error");
});

How to receive array using AJAX which calls PHP script?

So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted

JQuery: parsing ajax call versus imbedded str

I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.

JSON reply parse on JS

I need to parse reply from server, have a code:
$.getJSON('http://connect.mail.ru/share_count?callback=1&url_list=http://www.google.com&func=test', function(data) {
$('#ml_counter').text(data);
});
as a reply on http://connect.mail.ru/share_count?callback=1&url_list=http://www.google.com&func=test request server gives:
test(
{
"http://www.google.com":{"shares":574,"clicks":65}
});
How can I get "574" from this?
callback: function(result) {
var yourVal = result['http://www.google.com'].shares;
}
In your situation:
.text(data['http://www.google.com'].shares);
Note that returning the url as a parameter isn't really comforting. You're way better of returning just the child object or a list of domain-objects (where one of the properties is something like url and another is the { shares .... } object.

pass a value to a variable in javascript where these values are responses in json

I want to pass a value to a variable in javascript. These values are responses in json.
$.getJSON('url.php?id=login&email='+document.getElementById("txtemail").value+'&password='+document.getElementById("txtpassword").value, function (data)
{
alert(data.status);
alert(data.msg);
alert(data.user_id);
alert(data.session_id);
});
I want to store session_id in a variable and then have to send it to a url. How can i do this?
Thanks for any help...
Do you mean something like this?
var ses_id = data.session_id;
jQuery.post("<url>?session_id="+ses_id);
have a look at http://api.jquery.com/jQuery.post/
you can use console.log to debug your javascript a little bit more efficiently. http://getfirebug.com/logging
compare this to the post of the previous poster:
$.getJSON('url.php', 'id=login&email='+document.getElementById("txtemail").value+'&password='+document.getElementById("txtpassword").value,
function (data) {
console.log(data);
var session_id = data.session_id;
$.post('url2.php', session_id, function() {
alert('success');
});
}
});

Categories