Codeigniter echo/var_dump not working - php

Why doesn't var_dump work here, the ajax call is successful, but there is nothing printed, not even a string literal print from the PHP.
My controller
function check_links() {
$matches = $this->input->get('matchesJSON');
var_dump($matches);
//$this->load->view('publish_links_view');
}
Ajax call
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: 'matchesJSON='+matchesJSON,
url: 'publishlinks/check_links',
success:
function(response) {
}
})

I assume you're expecting it to var_dump to the browser.
Ajax happens "behind the scenes", so it wouldn't output to your browser, you'd have it in your success handler's response argument.
if you want to test it just hit the url directly with your browser.
http://ciroot/index.php/publishlinks/check_links?matchesJSON=test%20text
Also, you can monitor all of your AJAX requests / responses with the Browser extension Firebug, very useful in situations like this.

it seems to be a problem with your ajax call, not with codeigniter
start with removing dataType: 'json' - jQuery will find type of content itself as it's not json
and you need to output response in your function:
function(response) { window.alert(response) }

Related

Cross domain jquery json

I have tried tons of thing to get json data from another url with jQuery. I have working code in php, but dont have any idea how to do it in jquery.
PHP:
$skin = rawurlencode($market_hash_name);
$skin2 = str_replace('%0A', '', $skin);
$link = "http://steamcommunity.com/market/priceoverview/?country=EU&currency=3&appid=730&market_hash_name=".$skin2;
$json2 = file_get_contents($link);
$obj2 = json_decode($json2);
$mediumPrice = $obj2->median_price;
Example of jQuery that i have tried:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU&currency=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
});
Typically a easy way around that is to create a Proxy, that is just a fancy word for saying have something else send and receive the data between the end points.
This can be as simple as using ajax to a PHP file on your server, from that PHP file using CURL to your endpoint, back to the output through echoing the return of the CURL script.
That way you can get around the restrictions on JavaScript. You mention
I have working code in php
So it should be relatively trivial to pipe the ajax call through that code and back.
Ok so instead of doing this
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU&currency=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
Do this
$.ajax({
type: 'GET',
url: 'http://yoursever.com/proxy.php/?country=EU&currency=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'json',
success: function (data) {
alert(data.median_price);
}
});
Then in proxy.php or whatever you chose to name it, use your working php code to make the call then simply return that data to the client through JSON as per normal AJAX. Then you are technically calling the remote sever using PHP and don't have the cross domain issue. But because you are using your sever as a Proxy you can still do it in real time.

PHP script not echoing data when called via AJAX

I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.

ajax always going to error

Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.

Call php function in javascript without waiting for response

I know how to use $.ajax. I have a Codeigniter project so I just call:
url:'<?php echo base_url()."somecontroller/somefunction"?>',
This is all ok but ajax waits for the response. I just want to the call the url as you would by typing it in your browser. I don't want to wait for the response because the controller does a redirect and then loads a view. Also i need to be able to send some data via POST.
How can I do this?
You can use the following for sending asynchronous request with additional parameters.
$.ajax({
type: "POST",
url: url,
data: data, // additional parameters
async:true,
success: function(response){
}
});
If you want the request to be synchronous, set async:false.
For post, type:POST
Refer http://api.jquery.com/jQuery.ajax/
Do you can try this ?
Change the (alert) function with your function
$.ajax({
url: 'test.html',
async: false,
success: function () { alert('hello people from the world'); }
});
Never use async: false.
Since Javascript runs on the UI thread, an async: false request will freeze the browser until the server replies

Jquery ajax error - Requests adding GET var

My ajax function has stopped working all of a sudden.
function get_file_info()
{
$.ajax({
type: "GET",
url: "http://localhost/includes/get_file_info.php",
dataType: "json",
jsonp: false,
jsonpCallback: "callbackName",
success: function(data) {
return data;
}
});
}
I did some debugging and found that the ajax request is going to
http://localhost/includes/get_file_info.php?_=1297356964250
I am just would like to know what it is and can be used for, also how to remove so the ajax request is like below so it works again.
http://localhost/includes/get_file_info.php
Many Thanks
If you add:
cache: true,
to your call it will remove the timestamp which is there to always call a different URL's so the browser doesn't cache the result. This is standard for calls except for datatypes script and jsonp.
As others have stated though, it would be good to change the server side to stop turning away anything with GET's, maybe check if the get is a _ and only numeric, if not then turn it away...
The "_=1297356964250" query string is jQuery's method of preventing the URL being cached and returning an old result. Adding this ensures that you're retrieving a new response every time.
This is not the cause of your request breaking down. It must be from another issue. Have you tried logging your response and seeing what it returns?
success: function(data) {
console.log(data);
}

Categories