This is the response in php. I can confirm the datas are ok.
$ajax_response = array(
'product_code' => $ajax_products,
'filter' => $ajax_filter
);
echo json_encode($ajax_response);
exit();
Here is the code in javascript :
$('#pr_category_filter').submit(function (event) {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function (data) {
if (data.product_code != null) {
$('#pagination_contents').replaceWith(data.product_code);
}
if (data.filter != null) {
$('#category_filter').replaceWith(data.filter);
}
},
error: function (request, status, error) {
return false;
}
});
event.preventDefault(event);
});
This code works well on Chrome and Opera. However, this code doesn't work on Firefox because the php "echo" is displayed on Firefox instead of ajax response. I also tried to put a console.debug('invoked') in the javascript. No result is displayed in Firefox in contrary of Chrome. Do you know the reason ?
The response is the same into browsers tools development.
Thanks
The function .preventDefault() does not accept any arguments.
Probably Firefox therefore does not accept this and simply submits the form. Chrome however does not really care and does accept it.
So change
event.preventDefault(event);
Into
event.preventDefault();
That should do the trick
You need to use the header() function in PHP to specify the content-type of the response you're returning to the AJAX call. Try the following (place it before you echo the response):
header('Content-Type', 'application/json');
Related
I have this script:
<script type="text/javascript">
jQuery(document).on("click",".pending-post-approve-link",function(e){
jQuery('#review_post_status').val('approve');
var globalVar = jQuery(this).find('.review_post_id').val();
jQuery('#review_post_current_id').val(globalVar);
jQuery('#post-preloader-'+globalVar).fadeIn(500);
$.fn.wpjobusSubmitFormFunction();
});
$.fn.wpjobusSubmitFormFunction = function() {
var globalVar = jQuery('#review_post_current_id').val();
jQuery('#wpjobus-pending-posts').ajaxSubmit
({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: jQuery('#wpjobus-pending-posts').serialize(),
type: "POST",
success: function(response)
{
jQuery('#post-preloader-'+response).fadeOut(100);
jQuery('#post-'+response).fadeOut(100, function()
{
jQuery(this).css('display', 'none');
});
return false;
}
});
}
});
</script>
When this script runs, it gives me empty response. I don't know what causing this problem. This is happening in the success function of the ajax success: function(response).
Any help would be appreciated.
You might have done some of those steps, but myself I would take this approach to find the issues:
Use a tool such as Google Chrome console or Firebug for FF to check if your request is being sent to the expected url, and that it is getting an expected response.
If it is not getting the expected response, the issue is serverside and you should look there. You can also make some breakpoint using the same tools (console/firebug) to see if the parameters which you are passing look as expected (you can check the POST header details instead too).
Finally you can try placing a breakpoint on the success function to be sure that it gets executed at all and that the response is an empty string, and not something else.
I hope this helps.
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
My PHP code on Xampp
<?php
$data = ((**Refer the JS fiddle Link below for JSON data**));
//header('Content-Type: application/json');
echo $data;
?>
my client Javascript code
function clickbtn(){
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
contentType:'json',
//data: JSON.stringify(data),
success:function(dataF){
console.log('SuccessMsg:'+dataF);
alert(dataF.surveyId);
},
error:function(){
alert('Error: Unable to connect to the server');
}
});
}
I am able to dump the JSON from the php server on my browser console. But i am unable to see the alert "SurveyID" value on alert box.
Kindly take the JSON data available in JS fiddle link and paste it in your PHP script and test it.
If you are testing on chrome Please add the ((Chrome installation path))--disable-web-security to allow cross domain origin policy and then run the JSfiddle link at your end.
JSfiddle for client JS and PHP JSON data
You should use the dataType option instead of contentType if you need the response to be JSON parsed automatically by jQuery.
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
dataType:'json', /* dataType instead of contentType */
...
success:function(dataF){
console.log('SuccessMsg:'+dataF);
alert(dataF.surveyId);
},
...
});
Sometimes jQuery (or the browser?) respone with a string instead of an object.
You have to ckeck this an parse it to json maybe. I've encountered this problem too often, so i' checking this every time.
function clickbtn(){
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
success:function(dataF){
console.log('SuccessMsg:'+dataF);
if(typeof dataF != 'object')
{
dataF = jQuery.parseJSON(dataF);
}
alert(dataF.surveyId);
},
error:function(){
alert('Error: Unable to connect to the server');
}
});
}
I think that the dataType parameter is sometimes ignored :(
I have the following code which displays session data.The problem am facing is even if the session has value and the ajax get that data the alert that I have put below the function call getValFromSession(qes) always shows null data.I think this is due to the asynchronous execution of ajax with in the javascript.So I put some extra code as shown in the function
getValFromSession(qid).How can I overcome this asynchronous issue?
var qes=$('#qsid_'+q).val();
var res=getValFromSession(qes);
alert(res);//always shows null value
$('#select_'+).val(parseInt(res));
function getValFromSession(qid)
{
return $.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
cache: false,
async: false
}).responseText;
}
/*controller*/
function getValFromSession()
{
echo $_SESSION['time'][$_REQUEST['qid']];
}
Try this:
var qes=$('#qsid_'+q).val();
var res=getValFromSession(qes);
function getValFromSession(qid)
{
$.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
cache: false,
async: false,
success: function(data) {
alert(data); // alert here in successHandler
$('#select_'+).val(parseInt(data));
}
})
}
/*controller*/
function getValFromSession()
{
echo $_SESSION['time'][$_REQUEST['qid']];
}
Hope this helps.
$.ajax provides you with a success, error and complete callback handlers. Populate your response text in those handlers because the way you have implemented is synchronous and would execute immediately instead of after the request completes.
Docs
You can put your code into a function and call that function on success event of AJAX as below
---
---
return $.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
false,
async: false,
success: finalfunction
---
---
function finalfunction(res)
{
alert(res);//always shows null value
$('#select_'+).val(parseInt(res));
}
Hi I have a jQuery ajax request for a login system. At first, it worked very well. But after a few try, it just started to show negative response. I checked firebug and it says that the response is, in my case "Connected". But the ajax response just shows "Not_connected". I don't know what to do :(. Please help me.
This is my jquery code :
var data_str = "username="+usrn+"&password="+pwd;
$.ajax({
type: "POST",
url: "index.php?rnd=" + Math.random(),
data : data_str,
complete : function(xhr,data){
if(data == 'connected'){window.location.href = 'admin.php';}
else if(data = 'not_connected'){ error_gen.html('Invalid username or password'); }
alert(data);
}
});
AS for the PHP code :
$log_result = $u_obj->login_user();
if($log_result == true)/*user is connected*/
{
echo 'connected';
exit;/*stoping the script after sending the result*/
}
elseif($log_result == false)/*error while logging in*/
{
echo 'not_connected';
exit;/*stoping the script after sending the result*/
}
Look at this thread: Is it possible to cache POST methods in HTTP?
It might be that there are headers which now make browser caching the response (although it's POST).
Also instead of rnd=" + Math.random() you can add write
$.ajax({
type: "POST",
cache: false,
..
Could it be browser caching?
Try adding this $.ajaxSetup({ cache: false });
You are using the wrong $.ajax option to retrieve the result. You should use the success option. Just change the
complete : function(xhr,data){
line for
success : function(data){
It should work.