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');
}
})
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 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'){
}
}
Some code I want to call from ajax is in a separate file.php:
<?php
session_start();
$email1 = $_POST['email1'];
//some code here processing $email1
$response = 'some text';
?>
This is how I call it from ajax:
$.ajax({ url: 'file.php',
data: {email1: $("#user_email").val()},
type: 'post'
});
I'd like to be able to do something like this after the call to file.php:
alert($response);
How do I do that?
In your PHP you have to echo the $response, and in your JS you have to specify the callback function like so:
$.ajax({
url: 'file.php',
data: {
email1: $("#user_email").val()
},
type: 'post',
success: function(data) {
alert(data);
}
});
Inside the ajax call, include a success.. ex:
success: function(data) {
alert(data);
},
This will pop an alert up with your response.
Try:
$.ajax({ url: 'file.php',
data: {email1: $("#user_email").val()},
type: 'post',
success: function(data) {
alert(data);
}
});
Check out the documentation
You also need to echo out the response in your PHP file:
echo $response;
Something like this?
$.ajax({
type: "POST",
url: "file.php",
data: {email1: $("#user_email").val()},
success: function(data) {
alert(data);
}
});
I have a piece of jQuery code:
var newData = checkCP(somedata);
if(newData=="hi"){
alert("Welcom");
}
function checkCP(jsData){
$.ajax({
type: "POST",
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
return "hi";
else
return "bye";
}
});
}
I don't know why the welcome alert never shows up. I checked everything; the PHP file returns 1, but apparently before it waits on the AJAX response it passes the
if(new=="hi"){
alert("Welcom");
}
Is there any way to wait for the AJAX response, then read the rest of codes in jQuery?
Yes, you can set the 'async' option in $.ajax() to false.
$.ajax({
type: "POST",
async: false,
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
return "hi";
else
return "bye";
}
Firstly, please don't use 'new' as a variable name. 'new' already means something.
Now onto the actual question...
when you call checkCP jquery does the ajax post successfully and automatically waits for a response before execuiting the success function. the thing is that the success function is a stand-alone function and returning a value from that does not return anything from checkCP. checkCP is returning null.
As proof try sticking an alert in your success function.
Something like this should do the trick:
function deal_with_checkCP_result(result)
{
if(result=="hi"){
alert("Welcom");
}
}
function checkCP(jsData,callback){
$.ajax({
type: "POST",
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
callback( "hi");
else
callback( "bye");
}
});
}
Pass deal_with_checkCP_result as callback