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);
}
});
Related
I'm trying to create a search field on the top navbar with ajax. Since it's on the navbar, it has to be present on all pages, therefore the URL is constantly changing.
$.ajax({
type: 'GET',
url: CURRENT_URL,
dataType: 'json',
data: {
search: userSearch
},
success: function (){...
I'm working with Laravel, so i tried this on the navbar page:
<script>
var CURRENT_URL = "{{url()->current()}}"
</script>
The CURRENT_URL is displayed fine if i try to console log it, but ajax gives an error "Source map error: Error: request failed with status 404".
How can i insert the current URL into the ajax request?
You can use location.href instead of CURRENT_URL
$.ajax({
type: 'GET',
url: location.href,
dataType: 'json',
data: {
search: userSearch
},
success: function (){...
or
<script>
var CURRENT_URL = location.href;
</script>
Hopefully, this can help. Here's my approach to make my url dynamically I get the URL in every forms var URL = $('#example_form').prop('action'); then the URL variable must append or set via Js/Jquery. check my example below.
<script type="text/javascript">
var URL = $('#example_form').prop('action');
$.ajax({
type:'GET',
url: URL+'/clearContent',
beforeSend: function (xhr) {
var TOKEN = $('meta[name="csrf-token"]').attr('content');
if (TOKEN) {
return xhr.setRequestHeader('X-CSRF-TOKEN', TOKEN);
}
},
data:{
get_category_id : $('.parent-id').val(),
},
success:function(data){
if (data.response.status == true) {
// your codes here
}
},
dataType: 'json',
complete: function () {}
});
This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??
Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try
As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.
Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code
I'm trying to make a json call with jquery but noting happened. My code:
javascript:
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
}
});
});
});
</script>
PHP
$output = array(
'percentage' => "50"
);
echo json_encode($output);
Any suggestions?
The code looks fine to me,
EDITED
Also try removing the protocol and use url: "//<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
if you add and error callback to the ajax call you should get some error printouts to let you know what is going on
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error : function (e1, e2, e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});
EDIT:
i just had a thought, if i remember correctly jquery ajax doesnt like using full url's if possible try using a relative path
I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()
I am trying to send data to my PHP script to handle some stuff and generate some items.
$.ajax({
type: "POST",
url: "test.php",
data: "album="+ this.title,
success: function(response) {
content.html(response);
}
});
In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname is I get nothing, I try to get the album name by $albumname = $_GET['album'];
Though it will say undefined :/
You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.
Try sending the data like this:
var data = {};
data.album = this.title;
Then you can access it like
$_POST['album']
Notice not a 'GET'
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});