Successful ajax script doesn't give me response - javascript

The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}

Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}

Related

if use ajax call for contact form submitting, header(location:/path) not working

The issue is if try to ajax call for submitting my contact form. then header("location: /path); starts not working.
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
// header("location: /contact/thankyou.html");
}
} else {
echo "Invalid captcha! Please enter again. ";
}
And yes, because header redirect is not working. I comment it out. And tried to redirect page inside ajax call like below.
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function(){
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data){
response.html(data).fadeIn();
window.location.href ="/contact/thankyou.html";
},
error: function(e){
console.log(e)
}
});
});
});
But this time, it's only redirecting inside the .status div! like in the image Normally I am displaying a error message in that div...
Hey This is wrong practice if you are using ajax req then php not able to redirect to your destination all you need to redirect in ajax success response simple us
$data = array();
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
$data['status'] = 1; // for true
$data['message'] = "your success message"; // for true
}
}
else {
$data['status'] = 0; // for false
$data['message'] = "your error message"; // for false
}
//define content type json if you never echo like echo 'ss' then no need to this
header('Content-Type: application/json');
echo json_encode($data);exit;
and get response in ajax request dataType Json to access json array obj
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'json',
data: form.serialize(),
beforeSend: function() {
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data) {
if (data.status == 1) {
response.html(data.message).fadeIn();
window.location.href = "/contact/thankyou.html";
}
else{
// for error
response.html(data.message).fadeIn();
}
},
error: function(e) {
console.log(e)
}
});
});
});
You have to send header as Base64 string then decode it in the service / Backend.

Post to php file, and retrieve data with javascript

So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});

CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

How can I call second jquery/ajax request?

Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel.
So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.
Can someone suggest me how can I do this ?
Html form code :
<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
$('#success').delay(3000).fadeOut('slow');
</script>
add_contact_process.php page :
<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));
$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);
$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);
$msg = array();
$msg['error'] = false;
if(empty($family_name)){
$msg[] = "<div class='error'>Family name required.</div>";
$msg['error'] = true;
}
if(strlen($given_name) > 30){
$msg[] = "<div class='error'>Given name is too big.</div>";
$msg['error'] = true;
}
// If error is not found
if($msg['error'] === false){
if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
$msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?
<input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>
<input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>
</div>";
$msg['error'] = true;
}else{
$query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
$query_2 = mysqli_query($link, $query_2);
$last_id = mysqli_insert_id($link);
if($query_2){
$msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";
$msg['last_id'] = "$last_id";
$another = "close";
}else{
$msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
$msg[] .= mysqli_error();
$another = "close";
}
}
}
echo json_encode($msg);
?>
Call Second ajax within success
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
/*------------------------------------------------------------------*/
if(confirm('Write your message here')){
/* Second ajax after clicking ok on confirm box */
$.ajax({
url : 'Second URL',
method :'POST',
data : {'data1':data1},
success:function(response){
// code after success
},
error: function(e){
return false;
}
});
}else{
$('#success').hide();
$('#success').hide();
}
/*----------------------------------------------------------*/
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
// some code
},
complete:function () {
//you second ajax call
}

How to show alert when error comes from the PHP as response to ajax request in following case?

The jQuery AJAX function is as follows :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
The PHP code is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg;
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data = $objUserLogin->GetResponse();
echo json_encode($data);
die;
}
break;
Now I'm able to print the success when the response comes without any error but what about showing the alert message when some error happens. How to achieve it? What change needs to make to the above code? Please help me.
Use below condition in success:
success: function(result, success) {
if($.inArray( "error_message", result)) {
alert("Error message");
} else {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
}
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case echo "error";
and on ajax page check for result if its value is error then do what else u want
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}

Categories

Resources