I have my AJAX working and I can INSERT new data in the database. Basically I can not get an array to echo back into my page. I was wondering, do I need a separate AJAX to get the information from my first AJAX and will it work? Here is my code:
<?
$msg = array ("MSG1"=>"Error","MSG2"=>"Registered");
if(isset($_POST['register'])){
echo $msg['MSG1'];
}
?>
<script>
function Registration(){
var values = {};
values['register'] = '';
$.ajax({
'url' : '',
'type' : 'POST',
'data' : values,
success : function(data){
}
})
}
</script>
How can I get my Array to echo back from AJAX?
How about this one?
formData = {
register: register
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "http://localhost/register.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data);
//success handler
},
error: function(data) {
//error handler
}
});
about your 'Array to echo back from AJAX', you need to setup if else condition in your 'http://localhost/register.php' . Let say if condition A, "MSG1"=>"Error". If condition B, "MSG2"=>"Registered".
Please refer to this site for your reference.
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
Related
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 want to display welcome message to the user with his name...on next page but without redirecting the page(url should not be changed) for the same I have used ajax call and stores data in MySQL database.It works fine,stores data,returns array of values in success function of ajax call,but how to get the first name from that array which is returned by ajax call..
Can anyone please help me for the same..
Thank you..
Here is the block of code...which I have used..
$('document').ready(function () {
$('#f1').submit(function (e) {
e.preventDefault();
$.ajax({
url: 'process.php',
type: 'post',
data: $('#f1').serialize(),
datatype:'json',
success: function (data) {
$('body').html('Welcome ' + data.fname);
}
});
This returns on next page as Welcome undefined
And if I modified it as-
$('document').ready(function () {
$('#f1').submit(function (e) {
e.preventDefault();
$.ajax({
url: 'process.php',
type: 'post',
data: $('#f1').serialize(),
datatype:'json',
success: function (data) {
$('body').html('Welcome ' + data);
}
});
This returns output like below-
Welcome 1{"fname":"test","lname":"test","pnum":"1234567890","email":"test#gmail.com","gender":"f","status":"married"}
Try this:
php function called by ajax:
<?php
// your code logic
$array = array('fname' => 'Pooja', 'lname' => 'Singh');
echo json_encode($array);
?>
ajax:
success: function(response) // here response is an json object so you have to parse it.
{
var data = JSON.parse(response);
// data.fname contains Pooja
// data.lname contains Singh, Show it where ever you required.
}
nali.php
$tagId = mysqli_insert_id($link);
echo $tagId;
at ajax success call
$.ajax({
url: "nail.php",
type: "post",
data: {Tag:tag},
success: function(data) {
$enter_tag_id = data.tagId;
alert(data);
}
});
i get the correct echo at php page . but not get any value at ajax success.i want to save tagId to a variable at ajax success
Update your ajax code:
success: function(data) {
//$enter_tag_id = data;
alert(data);
}
I'm using bootstrap validator to validate my form data. If form is validated I'm posting those data to php. In php I'm returning json string. Even though my post is success and get correct response, I can't access json object.
$('#dealForm')
.bootstrapValidator({
message: 'This value is not valid',
fields: {
deal_description: {
message: 'The deal discription is not valid',
validators: {
notEmpty: {
message: 'The deal discription is required and can\'t be empty'
}
}
}
}
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var formObj = $(e.target);
var formURL = formObj.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType:JSON
}).done(function(data) {
console.log(data);
});
});
debugger output
php
$temp= $_POST['deal_description'];
if(!empty($_FILES['userfile']['name'])){$temp2='has';} else $temp2='no has';
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Either set the correct header in php:
header('Content-Type: application/json');
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Or use JSON.parse in js:
}).done(function(data) {
data = JSON.parse(data);
console.log(data);
alert(data.mesage);
});
EDIT just noticed you also have a spelling mistake in your js. data.mesage should have two s data.message
Try
.done(function(data) {
var res=$.parseJSON(data);
alert(res.message);
});
Your AJAX request is wrong I think. It should be
function getData(){
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: 'application/json; charset=utf-8',
cache: false,
dataType: 'json'
}).success(function (data) {
console.log(data);
workWithData(data);
}).done(function(e){
console.log("I'm done");
});
}
function workWithData(data){
if (typeof data != 'undefined') {
var jsonData = $.parseJSON(data);
// do stuff with data
}
}
The reason for having it in a second function is that it is a callback. We don't know how long the AJAX request might take, so we must not interrupt execution of the page whilst waiting for a response. By using a callback, when the data eventually arrives it will be processed.
I'd like to recommend you go through this to learn more about AJAX requests http://api.jquery.com/jquery.ajax/
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');
}
})