I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that
Related
I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.
hi i am working on a codeigniter project. I want to execute a php function after an interval of 10seconds. When a user visits that specific page after 10 seconds i want that php function to be executed. In that php function i have set a counter which adds 1 to the specific table into the database. I have tried using AJAX but didnt get the desired result. Kindly explain me with examples as i am new in ajax. Thanks in advance...
#Majid Golshadi s answer is the right answer.
Working version is here
Please in view that is loaded all the time (like header_view.php)
add this few lines
<script type="text/javascript">
var _baseUrl = "<?= base_url() ?>";
</script>
This makes that your base_url is usable in JavaScript anywhere in page (but make sure to have it somewhere on "TOP" of page)
and literraly use #Majid Golshadi s answer in this way
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: _baseUrl + "/your/controller/param",
type: 'post',
data: {"token": "your_token"}, });
}, 10000);
});
using jquery this will be the easiest and fastest way to do that
`//setting timeout to 3 seconds = 3 thousand milli seconds
setInterval(function(){
//ajax call
$.ajax({
url: _baseUrl + "/controller_name/function_name/", //the url where you want to fetch the data
type: 'post', //type of request POST or GET
data: {"data": "value"}, }); //data passed to controller
},3000);`
in your controller you may use
function function_name(){
$var = $this->input->post();//getting data passed from ajax
//process here...
echo json_encode($var)//parses and returns the processed value
}
try this
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('your/controller/address');?>",
type: 'post',
data: {"token": "your_token"},
});
}, 10000);
Example
in your view
$(document).ready(function(){
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('MyController/Mymethod');?>",
type: 'post',
data: {"token": "12majid18"},
});
}, 10000);
});
and in Your Controller write method like this
public function Mymethod()
{
$token = $this->input->post('token');
if ( $token == '12majid18' )
{
/*call your model and insert your data in Table*/
}
}
you can try this:
window.jQuery(function(){
var y=setInterval(function() {
window.jQuery.post(url,{"token": "your_token"},function(res){
alert(res);
});
}, 10000);
});
Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.
I have a PHP-Script that expects:
$_REQUEST['asdf']['bsdf']['csdf']
to be set when it is called, and I cannot change this.
I want to call this PHP-Script via ajax:
myurl = 'example-url.com';
myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
value = 'somevalue';
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf][myid]': value},
success: function (data) {
/* blabla */
}
});
It does not work though, because the var "myid" is not filled with the supposed value "csdf".
Can someone help me how to do this?
PS: I cannot access the PHP-File, so no changes in structure possible...
Try something like this:
var myurl = 'example-url.com';
var myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
var value = 'somevalue';
var param = {};
param[myid] = value;
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf]' : param},
success: function (data) {
}
});
You can build the param object outside the data you pass via the ajax call to keep the correct key in place.
in JS
... {
...
data: {[['first', 'array', 'nested'], 'other', 'in', 'parent', 'array']},
...
}
In PHP getting the POST vars is with other sentence
http://php.net/manual/en/reserved.variables.post.php
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