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'){
}
}
Related
Ajax success does not work without alert message.
there is no error in the console.
$.ajax({
url: "<?php echo base_url(); ?>Sensor/ConnectionTypeList",
type: "POST",
data: {'model_id': model_id},
dataType: 'json',
success: function (data) {
console.log(data); //not runnig
//alert(''running);
if (document.getElementById("offset")) {
document.getElementById("offset").value = data[0].offset;
}
if (document.getElementById("multiplier")) {
document.getElementById("multiplier").value = data[0].multiplier;
}
if (document.getElementById("func")) {
document.getElementById("func").value = data[0].func;
}
if (document.getElementById("meas_command")) {
document.getElementById("meas_command").value = data[0].meas_command;
}
if (document.getElementById("read_command")) {
document.getElementById("read_command").value = data[0].read_command;
}
},
error: function () {
alert('Error.');
}
});
Is the result type JSON? In that case you need to parse the returned result in order to use it, like this:
$.ajax({
url: "<?php echo base_url(); ?>Sensor/ConnectionTypeList",
type: "POST",
data: {'model_id': model_id},
dataType: 'json',
success: function (data) {
data = JSON.parse(data);
console.log('>>', data);
...
I always use '>>' (or something like that) inside a console.log to make sure you always see a console message, even if the result is empty. Check the console log to see if the result and its type.
i have to pass header information while posting a url and want to pass raw data in the url can any on help me on this
i have tried
function test(){
alert("test");
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("X-APIKEY", "y5q9q1at8u-1uf4bao2yq-bsjdj3gh1g-u9ymh1t2f8-tt85pn4r50");
},
url: "https://backoffice.hostcontrol.com/api/v1/domain-is",
data: {"domain": "mahrosh.com"},
processData: false,
success: function(msg) {
alert(msg);
$("#results").append("The result =" + StringifyPretty(msg));
}
});
}
its not returning me results
You can add header variables as per given in below described code
function test(){
alert("test");
$.ajax({
type:"POST",
headers: { 'X-APIKEY': 'y5q9q1at8u-1uf4bao2yq-bsjdj3gh1g-u9ymh1t2f8-tt85pn4r50'},
url: "https://backoffice.hostcontrol.com/api/v1/domain-is",
data: {"domain": "mahrosh.com"},
processData: false,
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data){
alert(JSON.stringify(data));
}
});
}
If server gives error in response than you have idea about it so i added the error section as well ...
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();
}
}
});
});
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');
}
})
I'm sending some data over with jQuery/Ajax. My code is marked as POST, but PHP is actually seeing it as GET. What gives?
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
callback(results);
},
error: function (req, msg, obj) {
console.log('An error occured while executing a request for: ' + url);
console.log('Error: ' + msg);
}
});
I'm able to confirm it's coming in on the PHP side as GET by doing print_r($_GET) and print_r($_POST)
you r not sending any data in post. try add some data and check in server side.
JS
<script>
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data : {
'sample' : 'sample_data'
},
success: function (results) {
callback(results);
},
error: function (req, msg, obj) {
console.log('An error occured while executing a request for: ' + url);
console.log('Error: ' + msg);
}
});
</script>
PHP
<?php
$sample = '';
if (isset($_POST['sample'])) {
$sample = $_POST['sample'];
}
echo $sample;
?>
// Output
sample_data
I think through the url you are passing values instaed of get if you want to post try like
$.ajax({
url: url,
type: "POST",
data:{'my_var':'gautam'},
-------------
and in php you can use like
<?php
print_r($_POST); //or you can print_r($_POST['my_var']);
?>
gives you 'gautam'...
Use $_SERVER['REQUEST_METHOD'] to check if its GET or POST
echo $_SERVER['REQUEST_METHOD'];
Use $_REQUEST[] for getting both POST and GET method values
<?php
print_r($_REQUEST);
extract($_REQUEST);
echo "sample : ".$sample;
?>
output:
sample : sample_data