I have a function for making a post request.
$('#save').click( function() {
...
$.ajax({
type: 'POST',
url: 'logic/save.php',
data: { 'json': JSON.stringify( post ) },
dataType: 'jsonp',
success: function( data ) {
console.log('success!')
}
});
}
The request handler is written in php, as you can see, and performs operations with mysql. Because of my poor knowledge of php and requests, I do not see any success! output in the console. Php code runs fine, and the mysql queries runs with no errors.
What I want is to be able to write something in php code at the end so that my code in js could receive it as a positive response (like 200, OK) and the success! line in the console will then (I believe) appears.
What code should I add to the php file?
UPDATE: since many of people requested the php code, here's the link to it. Thank you for fast replies, guys.
First, you should switch from jsonp to json, as you have no need for jsonp in this case. The following instructions assume you have made that change.
The bug is in your PHP code when you respond back to the client. You do so with this line:
print_r( "New item inserted.\n" );
However, jQuery is expecting you to be returning JSON back from your endpoint (and, truthfully, it should, because sending back plaintext to an ajax client is almost never the right way). We can make this work with jQuery by changing the line above to something like this:
print json_encode( array('success' => true, 'message' => "New item inserted." ) );
You should find yourself in the success callback in your client. This code would work for your success handler:
{ // ...,
success: function(response) {
if (response.success) {
alert(response.message);
}
}
}
You'll probably want to use something other than an alert, though. But that's up to you.
Related
Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).
The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK.
I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]
Any help greatly appreciated.
view_index.php
function search(){
var term = document.getElementById("mainsearch").value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: term,
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
controller_site.php
function search(){
$gotcha = $this->input->post('term');
return $gotcha;
}
The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key
Try with this:
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: {'term': term }
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:
data: term,
POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try
data: {foo: term},
and then
$gotcha = $this->input->post('foo');
You need to change return to echo as AJAX response works on whatever echo from called function.
So, you can code like :
function search(){
$gotcha = $this->input->post('term');
echo $gotcha;
}
or
function search(){
echo = $this->input->post('term');
}
The responseText property returns the response as a string, and you can use it accordingly
It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.
Now, for the error:
The success callback takes 3 parameters
You need to pass key-value pair in the data argument of the .ajax call
Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side
1 the callback:
Your success callback function should look like this:
function (data, status, response) {
}
Where:
data is whatever you are echoing from your controller's method. You'll probably want JSON.
status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.
Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.
If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.
2 the sent data
As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:
function search($term)
And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")
If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:
$.ajax("url", {
type : 'POST',
data : $('#form').serialize(),
dataType : 'json',
success : function(data, status, response) {} error : function(response, status error) {}});
3 handle errors
If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:
function search() {
$term = $this->input->post("term")
if($term == FALSE) {
//return a 404 so that you can catch .error on jquery
} else {
echo $term;
}
}
Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.
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.
I must be missing something simple here. Firebug shows data being sent exactly as it should in NET tab (NET tab-> Post -> Parameters). PHP function will not even echo simple text.
The PHP:
add_action('wp_ajax_nopriv_process_json', 'process_json_received');
add_action('wp_ajax_process_json', 'process_json_received');
function process_json_received(){
echo "ANYTHING...";
exit;
}
The JS/Jquery (sending correctly)
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
$.ajax({ url: 'http://localhost:12345/site_name/wp-admin/admin-ajax.php',
data: {data: data},
type: 'post',
dataType: 'json',
success: function (response) {
alert("Got this from the server: " + response);
console.log( response );
$('body').append(response); // <-- Append the ajax response to the page body
},
complete: function(XMLHttpRequest, text_status) {
},
error: function (response) {
alert("Error getting php file");
}
});
Again, it doesn't matter what is in the PHP function, the response is always 0. It could be an "enqueue_scripts" thing but ajax request is sending exactly as it should. NET tab in Firebug shows perfect json data so the problem has to be with the PHP function (or correct access to it). Maybe Wordpress is somehow blocking it??? Has to be something simple - I'm hoping a fresh set of eyes will help. Thanks in advance...
Because ANYTHING... isn't correct json format. Try echo json_encode(array('msg' => 'test')); This causes that JQuery have a parsing error (not error from receive)
Change the line in javascript from
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
to
var data = { action: 'process_json', value_name: 'value' };
Wordpress expect POST Data so it can read $_POST['action], you should never Stringify it, but use core javascript object only.
Read more about it : http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
EDIT:
Also change data: {data: data}, to data: data,
:) I miss that last time.
OK, I got it using the following code:
In main PHP plugin file:
echo "<script src='URL PATH TO/ajax_file.js' type='text/javascript'></script>";
add_action( 'wp_ajax_foobar', 'foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'foobar_handler' );
function foobar_handler() {
// Handle request then generate response
echo "ANYTHING..."; // do stuff here
die(); // avoids extra 0 at the end of the response
}
In ajax_file.js: (referred to above in script tag)
jQuery(document).ready(function($) {
$('#id_to_submit_button').click( function() {
var data = {
action : 'foobar',
Whatever : '1234',
}
;
// ajaxurl only needed for front - facing public pages, comment out for back end pages
var ajaxurl = 'http://SITE_URL/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
}
);
}
);
}
);
As soon as I included the script in this way it worked, it would not when placed in a PHP function as many sources suggest. I tried soooo many other ways that should have worked. I went step by step on the Wordpress codex pages (many times) and several other tutorials. Enqueueing scripts, registering scripts, following all recommended practices. I still don't understand why this way works for me and all the other "correct" ways didn't. Could be something in my local server environment. Big thanks to those who answered and tried to help. God knows I have gotten the quick answer on StackOverflow enough times, I hope this saves someone the long hours I spent testing and troubleshooting...
How can I return the value yes or no to php function .If not can i do the same jsonp functionality with curl ?
$.ajax({
url: 'www.example.com/trck.php',
type: 'GET',
data: 'adrs='+getHost( document.domain ),
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'methodCallback',
success: function( data ) {
if( data.message == "yes" ) { return yes;
} else {
return no;
}
},
error: function( error ) {
console.log( error );
}
});
by line return the value **yes** or **no** to php function I mean can I have php function which will call the above ajax script get its returned value ..
EDIT
After after some research I got to know that I can't return ajax value to php function.
Can I have the same functionality above ajax is doing in curl and how?
What do you really want to do?
PHP is STATELESS. That means you can NOT get any data back from the client to continue the script. If you call it back, the script will start again from the beginning like it has never been started.
Then curl can be used to connect to a server, you client is a client. That mean if he do not called you, the router/firewall will deny you the route.
The possible solutions :
If you really want to 'push' data Then, you should use PHP SOCKETS. I never tried, so I can't give you more informations.
Send a unique token with you PHP answer and make a second AJAX call with this token. If the token is correct, then you can send a new data, you know in wich state is you client & wich client it is.
Change your architecture or the way you think it. If the data is not correct, then, ask for the data again!
I've never worked with JSON before and it's not going well...
I have a PHP script that returns a JSON array(is that the correct term?)
The script returns:
{"items":1000,"mitems":0,"donations":0,"total":1000}
NOTE: The script also sets the Content-Type to application/json
Here is my front-end javascript to handle that response:
function ajax(){
$.ajax({
url: '../ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function( data ){
// data.responseText is what you want to display, that's your error.
alert(data.responseText);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
When that function is called I get an alert with the following message:
{"items":1000,"mitems":0,"donations":0,"total":1000}
If everything was successful, I should get an alert that says success, right?
Can someone please tell me what is going on here?
Thank you!
This is the least documented thing in jquery what you need to do is alert the actual error in order to debug it. so do the following:
function my_ajax(){
$.ajax({
url: '/ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function(jqXHR, textStatus, errorThrown){
// data.responseText is what you want to display, that's your error.
alert(jqXHR+","+textStatus+","+errorThrown);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
So two things I've done:
Change the name of the function (ajax is kinda a bad name :S) and improved the error reporting.
You should be getting the alert "success" yes. So something is going wrong.
EDIT:
Just noticed another thing, I dont think "../" would be a great way to reference the url, usually its either "/foo/ajax" which will allow you to use this function on any page.
It could be that your PHP script returns an error status code and even though it prints out the correct result, it still fails. I tested your scripts on my system and I got the 'success' alert. Then I changed my PHP script to the following:
<?php
header('Content-type: application/json', true, 401);
echo '{"items":1000,"mitems":0,"donations":0,"total":1000}';
?>
Note that the third parameter of the header function sets the http response code to 401 - Even though the correct output is sent back to the client; officially, the request has failed because of that status code. After running this code, I got the exact same problem as you.
So in summary, there might be something in your script which is causing a non-fatal error which doesn't show in the output of the script.
Are you defining the MIME type in your HTTP response?
Try adding a Content-type header to the output of your script.
<?php
...
$output = json_encode(...);
header('Content-type: application/json');
echo $output;
...
?>
You can also try using the mimeType parameter in your $.ajax() call to override the response type.
http://api.jquery.com/jQuery.ajax
Are you running your PHP scripts under Apache or on their own (chmod u+x on the script)? You probably need to use a PHP framework such as Zend, CodeIgniter or CakePHP and define a controller action that handles your AJAX request to have a proper HTTP response.
As the guy above me said, you should be using the json_encode(); function in PHP then echo'ing that output.
Make sure you encode an array though:
<?
$send = array(
'items' => '1000',
'mitems' => '0',
'donations' => '0',
'total' => '1000',
);
echo json_encode($send);
?>