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.
Related
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
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.
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));
As a novice js and jqplot programmer, I need guidance on passing an array of value from php to an external javascript for plotting (using jqplot). I am confused about the order and how html, php & external js, jqplot is called. A short sample code structure will be very helpful to follow. We may use the following sample codes as guide. Thanks
$(document).ready(function(){
var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});
Instead of the fixed data points above, I want them to dynamically loaded via an array from the following php script.
<?php
$Start_Value = $_POST['Start'];
$End_Value = $_POST['End'];
for($i=$Start_Value;$i<=$End_Value;$i+++)
$Plot_Val[$i] = $i + 2;
json_encode($Plot_Val);
?>
You have several options. Here are the 2 easiest:
Just 'paste' the array from PHP as a JavaScript global variable.
Add <script>var myData = <%= json_encode($Plot_Val); %>;</script> at the top of your page and then use myData in place of the data array.
Even better option is to use Ajax to call the PHP page from JavaScript and get the results , separating front-end and back-end code.
Best way is to use AJAX, something like this in JS:
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
Update: To get your values from a form, you cannot put form action to js, but rather use js to get the values from a form. So the form itself shouldn't do a POST request, but rather the js should take the values from a form and send the POST.
Something like this:
<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>
JS, we will wrap the above AJAX code into a function:
function submitValues(startValue, endValue) {
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
}
$(document).on('click', '#submitButton', function(){
var start = Number($('#start').val());
var end = Number($('#end').val());
//I guess you need numbers instead of text, that's why they are wrapped inside Number()
submitValues(start, end);
});
This should work.
Keep in mind that I have no idea what your form looks like, this is just a dummy example, but it should be similar enough. You get the form values with the jQuery's .val() method and then give those values to the ajax function.