The situation is I am using an API to fetch some data and update my database. I want to show user about the update.
So my ajax request is something like this.
$.ajax({
url: '<?php echo base_url() ?>add_products/',
data: "store_id="+store_id,
type: 'POST',
dataType: 'json',
async : true,
success: function(response) {
if ( response.result == 'success') {
//some data
} else {
genError();
}
}
});
and I am trying to get the process update like this.
$.ajax({
url: '<?php echo base_url() ?>get_product_progress/',
data: "store_id="+store_id,
type: 'POST',
dataType: 'json',
async : true,
success: function(response) {
if ( response.result == 'success') {
console.log(response);
} else {
genError();
}
}
});
I am not using any php session. I pass store id which fetch values from DB. I want to send 1 request that add products and other one to check how many products are added.
The problem is one 1st request of adding product is made, the get progress call does not progress. Get progress call is only made after the add product request is completed. I want them to be parallel.
I have found out that its server problem. Server blocks the second request until first request is completed. So how can I make the server return an ajax request when it is complete and make independent of each other.
You can use $.when.
Here is a good blog post about it.
Docs.
Example:
$.when(
$.ajax({
url: '<?php echo base_url() ?>add_products/',
data: "store_id="+store_id,
type: 'POST',
dataType: 'json',
async : true,
success: function(response) {
if ( response.result == 'success') {
//some data
} else {
genError();
}
}
});
).then(function() {
$.ajax({
url: '<?php echo base_url() ?>get_product_progress/',
data: "store_id="+store_id,
type: 'POST',
dataType: 'json',
async : true,
success: function(response) {
if ( response.result == 'success') {
console.log(response);
} else {
genError();
}
}
});
});
Related
I am using below code to get builder list auto-suggestions when user start typing. I gives proper result but after sometime, i am getting error message too many redirects.
Below is my code:
$(document).on("keyup","#builder_name", function(){
if($(this).val().length > 2){
$.ajax({
type: "POST",
url: "/home-loan-balance-transfer",
data: "step=search_builder&builder_detail="+$(this).val(),
dataType: 'json',
async: false,
success: function(response) {
if(response.status == 'success'){
$("#builder-list").html(response.html);
$("#builder-list").removeClass('hide');
} else{
$("#builder-list").addClass('hide');
}
}
});
}
});
I am trying to figure out how to just display a particular response from php using ajax for example. I have a php which gives the following response -
echo 'Success'; //Display only this
//Some other process
echo 'Something else for other process';
JS
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Use if else.
And while sending AJAX request, send conditional parameters.
For example, flag: set it to either yes or no.
Get these parameters $_POST ed in PHP back end.
Depending upon the value of AJAX sent parameter, print the response.
JS:
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test', 'flag' : 'yes'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Set flag to yes or no // This is just sample.
In PHP,
if (isset($_POST['flag'] && $_POST['flag'] == 'yes') {
echo 'Success'; //Display only this
}
else {
echo 'Something else for other process';
}
You will have send json_encode to receive a JSON response and will have to accordingly change the PHP too. Below is the updated code that you can try:
PHP:
if($_POST['action'] == 'test') {
$returnArray = array('message' => 'Success');
} else {
$returnArray = array('message' => 'Something else for other process');
}
echo json_encode($returnArray);
JS
$.ajax({
type: "POST",
url: "some.php",
data: {
action: 'test'
},
dataType: 'JSON',
success: function(response) {
var responseObj = jQuery.parseJSON(response);
$('#name_status').html(responseObj.message);
}
});
I have an ajax post that looks like this: (Located in: post.php)
$.ajax({
type: "POST",
url: 'prize.php',
cache: false,
beforeSend: function(req) {
req.setRequestHeader("Accept", 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
},
data: {sw: screen.width, sh: screen.height, saw:screen.availWidth, sah: screen.availHeight, scd: screen.colorDepth, tz: (new Date().getTimezoneOffset()), bp: sbp, hf: have_flash},
success: function (data, textStatus, xhr) {
if(data=="success"){
$('#status').text("You won: $<?php echo $data['prize'] ?>!");
}else {
$("#m_error_msg").html(data);
}
},error: function (){
}
});
The above ajax call, posts to this page: prize.php That looks like this:
if($_POST){
$data = array("data"=>"success","code"=>"100","prize"=>"$prize","type"=>"$text");
die($data['data']);
}
My question is.. How can I pass the $data['prize'] or $data['type'] to the:
if(data=="success"){}
code?
Add dataType:'json' to your $.ajax() handler to declare you wish to receive a json encoded result back from the server:
type: "POST",
url: 'prize.php',
cache: false,
dataType:'json',
Then in your response from the server, send back a json_encodeded array.
echo json_encode($data);
die();
Then in your success function, let's check:
success: function(data){
if(data.data == 'success'){
}
}
I am working on my site and i have a jquery request to the server
$.ajax(
// do an ajax to send value to the database...
{
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
})
How can I get a response as a json data from which is not a html data and how do I parse the json response from the server to the html file?
You write the PHP to emit JSON.
<?php
# Some code to populate $some_associative_or_non_associative_array
header("Content-Type: application/json");
echo json_encode($some_associative_or_non_associative_array);
?>
You need to use the parseJSON function in the js.
Here is the Php code:
function send_reply(){
echo json_encode(array('reply'=>'here is my reply'));
exit;
}
Here is the js code:
$.ajax({
url:'myajax.php',
data:{'func':send_reply},
type:'POST',
dateType:'json'
}).success(function(data){
data=$.parseJSON(data);
alert(data.reply);
}).error(function(jqxhr,error,status){
alert('Error sending reply');
});
As #Quentin said, you need to output JSON in your PHP result. Then you need to use done() to receive the data on the client side and work with it from there:
$.ajax({
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
}).done(function( json ) {
// do something with json here
});
You need to add the "JSON" header to your "pages/welcome_get.php" file:
header("Content-Type: application/json");
And also in your AJAX call remember to add the "success" and "error" callback:
jQuery.ajax({
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
success: function(response) {
//Do stuff with response here
}
error: function(){
//Display error msg or something like that
}
});
lets say you are checking user in your welcome_get.php
then in your welcome_get.php
use this
if(isset($_GET['wm_val'])){
$wm_val = $mysqli->real_escape_string($_GET['wm_val']);
$check_user = $mysqli->prepare("SELECT email FROM members WHERE username = ? LIMIT 1 ");
$check_user->bind_param('s', $wm_val);
$check_user->execute();
$check_user->store_result();
$check_user->bind_result( $email);
$check_user->fetch() ;
if ($check_user->num_rows == 1) { $datas['msg']= "failed" ;}
else{$datas['msg']= "success" ;}
$check_user->close() ;
echo json_encode($datas);
}
and your ajax
$.ajax(
// do an ajax to send value to the database...
{
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel},
success: function(msg) {
if (data.msg == 'success'){
// do what you like here example
$('#mydata').html("<span >you welcome ! </span>").delay(4000).fadeOut('fast');
}else{
//do something else example
$('#mydata').html("<span >failed ! </span>").delay(4000).fadeOut('fast');
}
})
here I have jQuery ajax calling a .php file that SOMETIMES executes let's say the following
echo "hello"
Here it is:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
}
});
I would like to know: is it possible to make the ajax return ERROR and not SUCCESS when something like the previous echo is executed in the PHP file? I mean, checking inside this $.ajax if the php file is executed as I would or not.
EXPLAINING BETTER:
I get error when the request could not be completed and success when it could. But I would like to get like a return value from this PHP file. If it returns 1, I wanna do something. If it returns 2, instead, I wanna do something else. Hope I explained it better..
Thanks in advance.
I recommend using json_encode() within your PHP file. For example:
echo json_encode(array('success' => 'do_foo'));
exit();
Then you can add a conditional within the success callback:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
dataType: "JSON", //tell jQuery to expect JSON encoded response
timeout: 6000,
success: function (response) {
if (response.success === 'hello'){
console.log(response);
} else {
console.log('else');
}
}
});
Based on your question make php return 1 or return 2. You can make it return 1 on failure and 0 (which is null) on success. Then you can do this for your ajax return.
$.ajax({
type: "POST",
url: "YOUR URL",
data: dataString,
success: function(server_response)
{
if(server_response == 1)
{
alert("You have made a mistake");
return true;
}
HERE YOU WILL PUT WHAT HAPPENS ON SUCCESS
}
});
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function (msg) {
if (msg != "Hi")
{
//TODO
} else
{
//TODO
}
}
});
You can use error callback for this:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
},
error: function() {
/* Code reacting to error here */
}
});
Also, there are other callback opportunities which you can check out at $.ajax documentation page.
If you are going to "say" fron PHP that there is an error, this can be done with 2 ways:
You can print in PHP a keyword meaning an error and then check it in you success function:
success: function (data) {
if (data == 'error') {
} else {
}
}
Or, the other way, you can provide with PHP right headers to cause "error". Then you can use the error callback as usual. I would choose this way.