Why isn't this PHP getting my links array?
function check_links() {
$matches = $this->input->get('links');
if($matches == true) {
echo json_encode('matches is true');
} else {
echo json_encode('matches is false');
}
//echo json_encode($matches);
}
The JS
var linksStr = $("#links").val();
var matches = linksStr.match(/\bhttps?:\/\/[^\s]+/gi);
alert(matches.length);
for(var i = 0; i < matches.length; i++) {
alert(matches[i]);
}
var links = JSON.stringify(matches);
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: links,
url: 'publishlinks/check_links',
success:
function(response) {
alert(response);
}
})
I'm confused a bit with what is trying to be achieved here.
But the JSON.stringify needs to be assigned to a value,
var links = JSON.stringify(matches);
like links
var links = 'links='+JSON.stringify(matches);
Then in your function, $matches should now contain your json-encoded links.
So you can use that,
function check_links() {
$matches = $this->input->get('links');
...
$matches = json_decode($matches); // do stuff
....
Related
I'v been trying for last 2 hours to pass parameters from my jquery to PHP.
I cannot seem to figure this out.
So my code goes following
var something = getUrlParameter('month');
function Refresh()
{
$.ajax({
type: 'POST',
url: 'getCalendar.php',
data: {test:something},
success: function(data){
if(data != null) $("#calendarDiv").html(data)
}
});
}
getUrlParameter is
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
I just cant seem to be able to pass anything to my php file.
Thanks.
My goal is to pass ?month=something&year=something into PHP file, so I can based on that display calendar.
Url of example:
http://chanceity.com/calendartest.html
But it doesn't work because my php file is not getting those params.
$.ajax({
type: 'POST',
url: 'getCalendar.php',
cache: false,
dataType:'json',
data: "data=" + {test:something},
success: function(data)
{
$("#calendarDiv").html(data)
},
error:function()
{
$("#calendarDiv").html('Could not get results')
}
});
and next go to your php file get the results and echo the variable back thats it
$value = htmlentities($_GET['data']);
if(!empty($value))
{
$results = 'action you want to do ';
}
else
{
$results = '';
}
echo json_encode($results);
You can also do it with just javascript
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
I have a function which gets the value of each checked checkbox i was able to get the value successfully by using an alert example it results to 1,2,3 which is correct but when i get it from php the array size is always 1.
HTML CODE:
function doit() {
var p = [];
$('input.cb').each(function () {
if ($(this).is(':checked')) {
p.push($(this).attr('rel'));
}
});
$.ajax( {
url:'page.php',
type:'POST',
data: {list:p},
success: function(res) {
alert(res);
}
});
alert(p)
}
PHP CODE:
<?php
$list = $_POST['list'];
echo count($list);
?>
Use this code :
var jsonData = JSON.stringify(p);
$.ajax( {
url:'page.php',
type:'POST',
data: {list:jsonData},
success: function(res) {
alert(res);
}
});
And in PHP :
$list = json_decode($_POST['list']);
I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}
i have a simple ajax call which returns html codes,
//=======-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-==-=-==-=-=-=-=
//SEARCH Submit ===============================================================================
$('.clicked_search').live("click",function() {
var from = $('#from').val();
var to = $('#to').val();
var sel = $('#sel').val();
var BegDT = new Date(from);
var EndDT = new Date(to);
var sum = BegDT - EndDT;
alert (BegDT +" b"+ EndDT +" e"+ sum);
if(sum > 0 | from == "" & to != "" | from != "" & to == ""){
$('.inv_date').show();
}
else{
$("#app_panel").html('<div id="flash" align="left" ><img src="img/clientimg/ajax.gif" align="absmiddle"> <span class="loading">Loading Request...</span></div>');
$("#clock").html('<div id="flash2" align="left" ><img src="img/clientimg/ajax.gif" height="15px" align="absmiddle"> <span class="loading"><font size="1">Loading Request...</font></span></div>');
$.ajax({
type: "POST",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(html){
$("#flash").hide();
$('.inv_date').hide();
$("#app_panel").append(html);
}
});
$.ajax({
url: "database/clientpanel/logs/search_clock_log.php",
cache: false,
success: function(html){
$("#flash2").hide();
$('.inv_date').hide();
$("#clock").append(html);
}
});
}
return false;
});
but i also want it to return values that was produced from the php which the ajax called,
session_start();
include("../../dbinfo.inc.php");
// connect to the database
$client_id = $_SESSION['clientid'];
//===========THIS PHP VALUES RIGHT HERE===================================
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
//====================================================================
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
how can i return the "html code" together with the "php values" using one ajax call?
You could transfer your data in a JSON format.
Within your PHP, you'll build an array with all the data you want to pass back for the AJAX call.
$results = array(
'html' => $html,
'variable1'=>'value1',
'variable2'=>'value2',
...
);
Now you encode this array into a JSON format using json_encode() -
$jsonString = json_encode($results);
echo $jsonString;
This is the value that you echo out of your PHP.
Now in your jQuery $.ajax request, you'll need to specify the dataType:json, and you'll be able to access all the parameters in your success callback -
$.ajax({
type: "POST",
dataType: "json",
...
success: function(data){
...
$("#app_panel").append(data.html);
// also available :
// data.variable1 and data.variable2
}
});
acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}