I am trying to send some data on button click to a controller and display the response in a content div back in the view. However i am facing problem while sending the data to the controller. Here is what i am trying to do :
test.php
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "1"
},
success: function(response){
$('#content').html(response.first);
}
});
});
$("#btn2").click(function(event){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "2"
},
success: function(response){
$('#content').html(response.first);
}
});
});
});
</script>
<input type="button" id="btn1" value="Button1 Content" />
<input type="button" id="btn2" value="Button2 Content" />
<br>
<div id="content"></div>
route.php
Route::get('ajax-example', function(){
return View::make('test');
});
Route::get('get-response/{id}', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
AjaxController.php
public function getResult($id){
if($id==1){
$content = "Hello";
}
else if($id==2){
$content = "World";
}
return Response::json(array('first'=>$content));
}
Error
Can anyone please help me out here. I am a bit confused right now. Thanks :)
if you need to get the parameter do this,
Input::get('id');
and route
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
because your ajax request is something like, host/get-response?id=5 and this is not compatible with Route::get('get-response/{id}'.., because this route needs something like host/get-response/5
Another way, you can keep your route as u declared and change the ajax request url,
$.ajax({
type: 'GET',
url: 'get-response/'+1,
dataType: 'json',
data: {},
success: function(response){
$('#content').html(response.first);
}
});
ok so i guess i figured it out what was causing the problem.
I changed my route to
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
and in controller i added
public function getResult(){
$id = $_GET['id'];
Now it seems to working just fine :)
Related
a problem with ajax because everytime when I want to click submit button then shows everythink in linkbar like 127.0.0.1:8000/?token[...] etc with every parameter it looks like method GET in form html but I haven't any method there. I think my code don't even try to execute Routes because I haven't any issue with json or database
$('#saveBtn').on('click', function () {
ajax: {
url: "{{route('res.Add')}}",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
///BUTTON
<button type="submit" class="btn btn-primary" id="saveBtn">Add</button>
And Route link
Route::post("/res/Add", "ResController#addRes")->name('res.Add');
I want to learn ajax.
Basically I begin to understand it, but I have one problem
here is my js code
$('#click').on('click',function () {
var a="good";
$.ajax({
url:'/ggg.php',
method:'post',
data:{
info:a
},
success:display_data
})
});
here is my html code
<input type="submit" value="do it" id="click">
here is my php code
<?php
echo $_POST['info'];
that's what I see in console.log
and the word "good" should appear
Use type instead of method. Also success might be a function.
$('#click').on('click',function () {
var a="good";
$.ajax({
url:'/ggg.php',
type: 'post',
data:{
info:a
},
success: function (data) {
//document.write(data)
console.log(data)
}
})
});
Reference
First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.
I'd have this html:
<form method="post" action="?c=Logo&action=save" id="form">
<!-- some inputs -->
<img src="" data-filename="new-logo.png">
<input type="submit" value="submit">
</form>
Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].
// $_POST['new-logo'] = $('img').data('filename')
$logo = new Logo($_POST['new-logo']);
$logo->save();
I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)
SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)
You could also make the data array from scratch like this:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: {key1:"value", key2:"value2"},
dataType: "json",
success: function(data) {
//do success stuff here
},
error: function() {
//do error stuff here.
}
});
});
You can add it as a hidden input.
$("#form").submit(function() {
$(this).append($("<input>", {
type: "hidden",
name: "new-logo",
value: $(this).find("img").data("filename")
});
});
you can add this to you're post request like this :
$('#form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
var datastring = $form.serializeArray();
datastring.push({name:'new-logo', value:$form.find('img').data('filename')});
$.ajax({
type: "POST",
url: $form.attr('action'),
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
});
$logo = new Logo($_POST['new-logo']);
Is "new Logo" a function or something? Pretty sure that can't have a space.
I'm trying to make an app where if you click on a div, the data-id will be put into a variable, which will give PHP the select parameters to look for. Here's my code to better explain it.
HTML:
<div class="box" data-id="caption"></div>
JQuery:
$('.box').click(function () {
var caption = $(this).data('id');
});
After Googling I found the best way to do this is through AJAX, which I then proceeded to try:
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: ({ caption }),
success: function(data){
console.log(data);
}, error: function() {
console.log("error");
}
});
However, this doesn't seem to work. If there's a better way to do what I mentioned above, I'm open to new ideas.
EDIT
Here is my PHP code.
if(isset($_GET['caption'])){
echo $caption;
$select = "SELECT * FROM pics WHERE text = '".$caption."'";
}
?>
Look through the api at jQuery.
Your data key should contain a json object -
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: {caption: caption},
success: function(data){
console.log(data);
}, error: function(error) {
console.log(error);
}
});
First, I'm using the codeigniter framework and I'm a beginner in JS and AJAX, so please bear with me.
I read this question, so I tried to follow the answers.
This is the script (UPDATED):
$(function() {
$( "#datepicker").datepicker().click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
});
});
And this is my datepicker HTML code:
<input type="text" id="datepicker" name="datepicker"
value="<?php echo isset($umat['tanggal_lahir'])?$umat['tanggal_lahir']:""?>"/>
My questions are (UPDATED):
Is the URL I provided in AJAX above correct?
How should I pass the data from AJAX to PHP (url: "<?php echo base_url(); ?>backend/umat/add")?
Thanks for your help :D
What you have missed here:
your click event is outside of the doc ready handler, that should be inside doc ready so that when page gets ready the element should be available to click.
You have missed a closing }); tag of the click event.(does not matter though)
so try this:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: {frmData : $('#form_daftar').serialize()}, // <----send this way
success: function(data) {
console.log(data.date);
// here data is the returned data from the specified url and make sure
// that url is generating a proper json structrue.
// suppose there is a key named date which holds the submitted date so
// data.date will get you the date.
}
});
}); //<----you missed this closing of click function.
}); //<----------put everything before this closing of doc ready handler.
Although you can chain it too like this:
$(function(){
$( "#datepicker").datepicker().click(function() {
//......ajax function in click here
});
});
See a demo here
Another approach would be to use the datepicker inbuilt methods to trigger ajax request like
$('#datepicker').datepick({
dateFormat:"yyyy-mm-dd",
onSelect:function(){
$.ajax({
type: 'POST',
url: "<?php echo site_url('backend/umat/add'); ?>",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
}
});
Check the manual or inbuild functions and callbacks with your datepicker js.
try it:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").change(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
});
php get data form ajax:
<?php
$date = $_POST["datepicker"];
?>