Laravel 5 jquery getJSON not working - php

I am trying to get JSON data from API on Laravel 5 , The route gives me correct
Data in the browser but when trying to access this route in JQuery it failed.
the route is:
http://localhost:8000/search/student/all
worked finally in the browser and the data is displayed in json format
but this script failed:
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
I replaced localhost:8000 with 127.0.0.1:8000 but nothing changed.
Note: I generated the json response using Laravel
$students=App\Student::all();
return response()->json($students);

In jquery you can do like something below
$.get( "http://localhost:8000/search/student/all", function(data ) {
var obj = jQuery.parseJSON(data);
console.log(obj);
});
Another possibility use jsonp
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
$.ajax({
url:"http://localhost:8000/search/student/all",
dataType: 'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
console.log(obj)
},
error:function(){
}
});
Basic example of using .ajax() with JSONP?

Try like this...
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result.students, function(i, field){
$("div").append(field.name + " ");//name is database field name such as id,name,address etc
});
});
});
</script>
PHP
$students=App\Student::all();
echo json_encode($students);//or return $students->toJson();

Related

Error in Ajax code to get response from codeigniter

I want to send my request to CodeIgniter to get response from my database:
$(document).ready(function(){
$('.confirm_send').on('click',function(){
var base = '<?php echo base_url(); ?>';
var confirm_send_id=$(this).attr('id');
$.ajax({
'url': base + 'my_site/confirm_send',
'type':'post',
'dataType':'json',
'data':{
'id':confirm_send_id
},
'success':function(){
alert("sucssess");},
'error':function(){
alert("Error");
}
});//end of ajax confirm send button
});//end of confirm send button
});//end of jquery
But I am getting an error.
Try This:
$('.confirm_send').on('click',function(){
var base = '<?php echo base_url(); ?>';
var confirm_send_id = $(this).attr('id');
$.ajax({
url: base + 'my_site/confirm_send', //make sure it is a valid path
type: 'POST',
data:({'id':confirm_send_id}),
success : function(response){
alert("Success");
},
error : function(response){
alert("Error");
}
});//end of ajax confirm send button
});
Its a server side coding issue thats why it`s getting issue you can check error using response window it will display coding error.
You can't inject PHP code into JavaScript. Remember that whatever script or css that you define will be run in the user's browser - and browsers don't interpret PHP code neither have direct access to your server.
You've gotta hard-code the base_url variable.
If you don't know it just echo base_url(); on a page and copy it.
$(document).ready(function(){
$('.confirm_send').on('click',function(){
var base = 'http://yourproject_base_url'; //Set the full base url manually here.
var confirm_send_id=$(this).attr('id');
$.ajax({
'url': base + 'my_site/confirm_send',
'type':'post',
'dataType':'json',
'data':{
'id':confirm_send_id
},
'success':function(){
alert("sucssess");},
'error':function(){
alert("Error");
}
});//end of ajax confirm send button
});//end of confirm send button
});//end of jquery

Multiple Ajax Calls while one Ajax call is still running

I got some progressbar Update Issues. What I like to do is, fire a ajax call which takes some time to complete and during the this call I'd like to fire ajax calls, set by an interval, to update my progressbar.
Since I could not find a solution and only found the Browser's restriction, which would match here. It's always max 2 calls active.
Still, my second call stays pending in Google Chrome, untill my first (main) call finished.
EDIT: full jquery script
// update cars cache
$('#cars_cache_update_run').bind('click', function(){
// remove button
$(this).remove();
// hide import widgets
$('#products_import_widget').css('display', 'none');
$('#vehicles_import_widget').css('display', 'none');
$('#orders_import_widget').css('display', 'none');
$('#test_data_widget').css('display', 'none');
// show blind
$('#cars_cache_update_info').css('display', 'none');
$('#cars_cache_update_blind').css('display', 'inline');
var carsUpdateInterval = setInterval(function() {
getImportState('http://localhost/index.php/import/import_state/cache_update', 'cars_import_progressbar');
}, 1000);
// ajax request
$.ajax({
url: "http://localhost/index.php/import/cars_cache",
async : true,
success: function(data){
$('#cars_cache_update_blind').css('display', 'none');
$('#cars_cache_update_success').css('display', 'inline');
clearInterval(carsUpdateInterval);
},
error: function(thrownError){
$('#cars_cache_update_blind').css('display', 'none');
$('#cars_cache_update_error').css('display', 'inline');
$('#cars_cache_update_error_msg').html(thrownError);
}
});
});
function getImportState(url, id)
{
$.ajax({
url: url,
success: function(data){
var json = $.parseJSON(data);
$.each(json, function(i, item) {
var progressbar_value = json[i]['state'];
$( "#"+id ).progressbar({
value: progressbar_value
});
})
}
});
}
Another funny thing, if I call the interval request by $.get I'll get a strange error..
Working with Codeignitor Framework.
GET http://localhost/[object%20Object] 404 (Not Found) jquery.1.7.min.js:4
send jquery.1.7.min.js:4
f.extend.ajax jquery.1.7.min.js:4
f.(anonymous function) jquery.1.7.min.js:4
(anonymous function)
Many Thanks for your help already, been trying for hours now.. Maybe I'm just a noob.. Haha.
rootless
Don't call multiple ajax with intervals. Try something like this:
function updateProgress(){
$.ajax({
url: "http://localhost/index.php/import/import_state/cache_update",
success: function(data){
var json = $.parseJSON(data);
$.each(json, function(i, item) {
var progressbar_value = json[i]['state'];
$( "#cars_import_progressbar" ).progressbar({
value: progressbar_value
});
});
updateProgress(); // after success, call the same function again
}
});
}
updateProgress(); // start updateProgress
Hope it helps :]

Get div content with jQuery for PHP

UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

data in mysql show after barcode split and matches character

i need some code for the next step..this my first step:
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
});
</script>
after matches..i want the result can connect to data base then show data from table inside <div id="value">...how to do that?
you can start here. $.ajax();
You should have some server side scripting knowledge also.
You will need to do it using an ajax call (matches will be a parameter for the call). The php script called through ajax will have to fetch the data and give it back to the calling page.
There you will need to parse the ajax response and display what you want.
A helpfull tutorial can be found here.
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
$.ajax({
type:"post",
url:"process.php",
data:params,
cache :false,
async :false,
success : function() {
alert("Data have been input");
$("#value").html(matches);
return this;
},
error : function() {
alert("Data failed to input.");
}
});
return false;
});
</script>
and i change my process.php become:
select itemdata as version from settingdata where version = "tunerrange";

Categories