I want to send data from php to a browser using JSON. I think I understand the process - see my example code below. But someone told me this is not the right way to do it. I have been researching for three days but because my English is poor I am not confident that I have found an answer.
What I am hoping for is a sample of code that will receive the JSON and pour it into html elements such as a div, and give it style via CSS, etc.
I really just want an example of how to do this so that I can learn from it and expand it myself for my own needs, but I am unconfident that this approach is correct and do not want to write more bad code.
Thanks
Javascript
$(document).ready(function() {
$.ajax({
type : 'POST',
url : 'server.php',
dataType:"json",
success : function (data) {
$("#orders").html(JSON.stringify(data));
}
});
});
PHP
<?php
$db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
$statement=$db->prepare("SELECT * FROM myfeilds");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
You don't need to call JSON.stringify on the data that gets returned in your response. This method is for converting a javascript object to a JSON string, but your PHP code should be sending a JSON string back already by the looks of it.
So it depends on what your returned JSON looks like, but usually it'll be something like this:
{"name":"Mike", "phone":"5551234", ...} etc
So in your success callback, you would do something like this:
$("#name").text(data.name);
$("#phone").text(data.phone);
And so on.
Note that I'm using the .text() method. You could use .html() as you've done but you probably don't need to unless your JSON strings contain HTML or you want to write out HTML like so:
$("#name").html("<p>" + data.name + "</p>");
As for styling, I would setup your styles in advance so that you don't have to do it in javascript as this will be more performant.
However, if for some reason you needed to then you could do something like:
$("#name").css({"display":block","color": "#000"});
Hope that helps.
Related
I am trying to send a row and column number of the clicked cell via GET method.
to php file, where I can check if this cell contains something or not.
For example that the URL will loke like this:
.php?c=3&r=5
I am using:
https://www.w3schools.com/jquery/ajax_get.asp and I have been trying to send data like it is listed on W3schools:
Request "test.php" and send some additional data along with the request (ignore return results):
$.get("test.php", { name:"Donald", town:"Ducktown" });
I am doing it like this:
$(document).ready(function() {
$("td").click(function(event) {
var clickedBtnID = $(this).attr('id');
values=clickedBtnID.split('.');
var row=values[0];
var col=values[1];
$.get("info.php", {"row":row, "col":col});
I was looking at some other examples on StackOverFlow, like:
How to send data to PHP file using JQuery Ajax?
I would like to say it that info.php is the diferent .php file, as the one we are working from. And another thing is that the best way to do this, would be to do it without refreshing the page. So is Ajax call the best way for this? I have tried many different things, but it seems like I can't send the data via GET method.
I'm not 100% sure I understand what you're looking to do, but I'll try to help!
Have you tried something like this? In your js file:
$.get("info.php?c=3&r=5");
Then in your PHP file:
//Retrieve the variables
$c = ($_GET["c"]);
$r = ($_GET["r"]);
//Then do what you need to do with $c and $r
Let me know if that helps.
I have tried this:
$.ajax({ url: 'info.php',
data: {'row':row, 'col':col},
type: 'GET',
success: {}
});
And it works perfectly. I don't know why the jquery $.get didn't work.
Okay, so I have this function in PHP that gets an attribute and returns an array. Something like this:
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
Everytime the parent select changes, the function getProvinces() should be executed with the new ID and the arrayWithProvince should be included as options in the child select.
I'm using jquery to handle the events, as I found somewhere. I need to do something like this.
$("#selectCountry").change(function() {
var parent = $(this).val(); //get option value from parent
var prov = <?php echo json_encode($pagina->getProvinces( <PARENT> )); ?>;
list(prov);
My problem is that I don't know how to tell the getProvinces($countryID) php function which is the new value of the parent.
Thanks in advance.
You should use javascript for that in order to refresh part of your page with dynamic content.Below is an example using jquery's ajax function.When the select with id #parent_select changes you call your php script and you append the returned data (the html of the child select in the example) in a div you want.
Javascript part would be something like this:
$("#parent_select").change(function() {
$.ajax({
url: "your_script.php?cid="+$(this).val(),
success: function(html){
$("#child_select_container").append(html);
}
});
});
And your_script.php code would look something like :
<?php
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
$countryID=(int)$_GET['cid'];
$provinces=getProvinces($countryID);
echo '<select id="child_select">';
foreach($provinces as $key=>$province){
echo '<option id="'.$key.'">'.$province.'</option>';
}
echo '</select>;
I havent tested the example.It is just a basic how to example.You should be able to work your way from here.But if you have any problems let me know.
As far as I know, you cannot execute the function without reloading entire page (I mean php should recompile it and pass it to the client).
You should use only JavaScript for that purpose. Store you arraylist in JS code, and validate it once upon form submission (just to be sure).
You need to make an Ajax request to the server.
Look at it this way: Your Javascript/jQuery is running on the client side (web browser) and you PHP is running on your web server.
So to communicate between the browser(jQuery) and the server(PHP) you need to make a Ajax request.
jQuery has a ajax function you could use, your best bet is to do some research on the subject as Ajax is something you will use all the time and understanding how it works is crucial.
I am not really sure how to phrase this question, so I will just ask the best I can.
I would like to know how to grab the contents of a webpage and place it in a string or array so I can parse the data.
This is the webpage: https://campusdata.uark.edu/api/buses?callback=?&routeIds=8
The webpage returns something like this:
?([{"id":25,"fleet":15,"name":"Fleet 15","description":"","zonarId":9,"gpsId":"8061088","latitude":"36.0680039","longitude":"-94.1758039","speed":0.000,"heading":89.700,"power":true,"date":"\/Date(1456339080000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":9999999999,"nextStop":"Garland Center","nextArrival":"8 mins"},{"id":33,"fleet":6,"name":"Fleet 6 ","description":"","zonarId":13,"gpsId":"8061090","latitude":"36.0818423","longitude":"-94.1707598","speed":0.000,"heading":181.700,"power":true,"date":"\/Date(1456339200000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":2.31887983012931,"nextStop":"South Creekside","nextArrival":"1 mins"}]);
I am not sure the best way to go about this... AJAX through JQuery? Maybe a php call? I don't know.
I have searched for this, but like I said, I don't know exactly how to phrase the question, so my search results have been sporadic at best.
Can someone help me please?
Seems like a JSONP call. You can use jQuery to easily fetch the data from the API end point. Please see the example below:
$.ajax({
url: "https://campusdata.uark.edu/api/buses?callback=?&routeIds=8",
// The name of the callback parameter
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
data: {},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
Here is a jsfiddle with working example.
Please make sure to include jquery in the page before trying this.
Your can use this in PHP
$site = file_get_contents("http://campusdata.uark.edu/api/buses?callback=&routeIds=8");
print_r(json_decode($site));
Reference
json_encode
file_get_contents
Get the page content with file_get_contents function. Remove illegal character. Convert the json format to PHP array:
<?php
$page = file_get_contents('https://campusdata.uark.edu/api/buses?callback=?&routeIds=8');
$page = substr($page, 0, -2);
$page = substr($page, 2);
var_dump (json_decode($page));
I'm new to cakePHP but am close to quitting using it due to my inability of getting jQuery to work with it.
I'm using cakePHP 1.3 and so thought the Html and Js helpers had made Javascript and Ajax redundant but I can't really find any help/api documentation on how to use Js that is sufficient.
All I'm trying to do first of all is send some data to cakePHP with jQuery and then get some data back into jQuery and alert() it. For some reason this just isn't working. Here is my code:
test.js
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '/activities/add_activity',
data: 'type=social',
dataType: 'json',
success: function(data)
{
alert(data);
},
error: function()
{
alert('wut');
}
});
});
activities_controller.php
function add_activity()
{
if($this->RequestHandler->isAjax())
{
$this->autoRender = false;
$this->autoLayout = false;
$this->header('Content-Type: application/json');
echo json_encode(array('result'=>'hello');
return;
}
}
Every time I click the button with class='social' I get the alert "wut" which means error.
I have the RequestHandler component and Javascript, Js, and Ajax helpers included in my activities_controller.php.
Also, test.js and jquery.js is linked using html->script(); in default.ctp and all other jQuery stuff is working so it's not that.
I've also got this in my beforeFilter() for activities_controller.php:
if($this->RequestHandler->isAjax())
{
Configure::write('debug',0);
}
parent::beforeFilter();
Any ideas what is wrong? Is it a jQuery thing or a cakePHP thing? Or both?
Thanks in advance,
Infinitifizz
P.S.
I have never done AJAX in jQuery before so maybe it is something to do with that that is messing up, I've only ever done simple javascript AJAX.
Don't give up on CakePHP. There is a learning curve, but it's worth it.
I would specify the url like this:
<?php $Url = Router::url(array('controller'=>'activities','action'=>'addActivity'),true); ?>
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '<?php echo $Url ?>';
...
On the CakePHP side, my method would be like this:
function addActivity()
{
$this->autoRender = false;
$this->autoLayout = false;
App::import('Helper', 'Javascript');
$javascript = new JavascriptHelper();
echo($javascript->object(array('result'=>'hello')));
exit(1);
}
I never use if($this->RequestHandler->isAjax()) although I'm sure some kind soul will tell me why I should.
I prefer to camelCase method names in line with CakePHP convention.
Note that this line in your code: echo json_encode(array('result'=>'hello'); is missing a closing bracket.
Also, I wouldn't use jQuery to do simple AJAX like this - it can make it difficult to debug, but that's just personal preference.
I hate the Ajax Helper in CakePHP... that is until I found this: http://blog.loadsys.com/2009/05/01/cakephp-jquery-ajax-helper-easy-scriptaculous-replacement/
Now I can use native CakePHP Ajax calls with jQuery! Look into this. I was able to solve all of my "simple" ajax issues with this darg-n-drop ajax helper replacements. I just drop this into the helpers directory in my app and replace the ajax.php that is there and viola! jQuery is working. You need to include the jQuery script in the layout of course. Try it, you will love CakePHP again!
I would recommend you to use CakePHP json layout to output the data from view instead of echo json data from your controller.
This probably is offtopic, but...
What I do in order to have the application's root in my javascript:
In the /app/views/layout/default.ctp I have following code
<?php
echo $javascript->codeBlock("var root = '".$html->url('/')."';");
?>
Your parameter url will look like:
url: root+'activities/add_activity',
this way even if you app is in a subfolder or in a tld domain the script will work properly.
Returning "wut" for me means that the script couldn't reach the page in your url parameter. Especially if you working in a subdirectory it will look in http://server.com/activities/add_activity. I am 99% sure that this is the problem :)
Another suggestion: Remove Ajax while it was meant to work with Prototype rather with jQuery
I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.