Ajax request to php file with no response - php

I have the code below requesting a php file result:
var fn_name = function(data){
var tmp = 'no change';
$.ajax({
type: 'POST'
, url: 'std/files/fn/cquery.php'
, cache: false
, data: { query:data }
, success: function(data){ tmp = data; }
, error: function() { tmp = 'error'; }
});
return tmp;
}
And here is the php file:
<?php
function cquery($data){
$conn = new mysqli('localhost','user','pswd','db');
if(($conn->query($data))->fetch_assoc()){
return 'true';
}else{
return 'false';
}
}
if(isset($_POST['query'])){ echo cquery($_POST['query']); }
?>
The problem is that the fn_name('correct query here') returns 'no change'. The Ajax's success is been executed, inserting an alert() there works...
Can't figure out what's happening...

Related

jquery ajax response in html form

I have send query ajax request to server. The server response in two variable that is errmsg or successmsg . so how can i understand response is whether errmsg or successmsg. More code explain below
script.js
$.ajax({
url:"abc.php",
method:"POST",
data:$('#form').serialize(),
success:function(data){
?????????
}
error:function(data){
.......
}
});
abc.php
<?php
if (condition) {
$successmsg = hello;
echo "$successmsg";
}
elseif (condition) {
$errmsg = Error Occured;
echo "$errmsg";
}
elseif (condition) {
$successmsg = welcome;
echo "$successmsg";
}
else {
$errmsg = Bye;
echo "$errmsg";
}
?>
return error or success depending on what you are doing with your code in php for example
return iferror ? ['errmsg' = 'Error'] : ['successmsg'=>'success'];
then get your response in ajax like
$.ajax({
url : 'your-url,
data : {your - data},
success: function(response){
if(response.successmsg){
console.log(response.successmsg);
}
else{
console.log(response.errmsg);
},
error: function(response){
console.log(response);
}
});
You can return the server's response using this code:
<?php
if ($textvar > 500){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
?>
Then the Ajax code can be:
$.ajax({
cache: false,
url: '/js/checkmsgs.php',
success: function(res){ // This will be applied if the php code is completlly done without any programming mistakes.
if (res == 'SUCCESS'){
alert('Success');
}else{
alert('Error !');
}
},
error: function(){ // this one will be applied if the php code have a mistake !
alert('eeeeeerrror');
}
});

do not work properly duplicate entry validation in php using jquery

I have create multiple forms, this form hide and show after change a drop down value
I wank to check duplicate entry on click on submit button
than add this code
but this code do not work properly
jQuery('#form_1').on('submit', function(event) {
jQuery.ajax({
url: SITE_URL+'/admin/ajax/function.php',
type: "POST",
data: jQuery('#form_1').serialize(),
dataType : 'json',
a sync : false,
success: function(response){
if(response.status === true){
var error = '<div class="alert alert-danger">this record already exist</div>';
jQuery('.form1ErrorMsg').html(error);
return false;
}else{
alert('test');
//return true;
}
},
error: function(){
return false;
}
});
//return false;
});
function.php
if(isset($_POST['ActionToCall'])){
$Action = $_POST['ActionToCall'];
switch($Action){
default:{
break;
}
case 'chkDuplicatChiefInvigilator':{
require_once('../../class/staff.class.php');
require_once('../../class/user.class.php');
$staff = new staffmanager();
$users = new usermanager();
$result=$staff->getDuplicatChiefInvigilator($_POST);
if(!empty($result)){
$output['status']=1;
}else{
$output['status']=0;
}
print json_encode($output,true);
die;
}
}
Look at your syntax error:
dataType : 'json',
async : false,

issue with ajax doesnt continue

I have one issue with ajax when I get echo success on my php. I don't get execute the first if
if(text[0]==="success")
Code inside php
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
My code in ajax
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
Image console
What is the problem?
Could say me which it is problem?
I have that convert the message success to json too
Replace the success echo with
echo json_encode(["success"]);
or leave echo the same and replace if in ajax
if(text == "success")
The problem could be that it is an array, so you can try this:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
And if you want to see the results:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});

How to run PHP with Ajax to validate results?

I'm making a Ajax script which validates results with PHP file before processing. Below is my Ajax script but I don't understand how to retrieve this DATA to validate.php and how to get results back from my PHP file.
<script>
function shake(){
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(),
success: function(data){
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
How can I process this Ajax script with validate.php ?
Can it be like:
<?php
// Get values from AJAX
$userid = $_GET['userID'];
$pass = $_GET['pw'];
?>
What results is this Ajax script expecting? I see resultado==0
So my question is how can I send resultado=1 with PHP to this script?
Should it be:
<?php
// Send result to AJAX
$resultado = 1;
?>
Thank you for helping.
I think this is what you're asking for.
The php script at the bottom is missing the closing tag for a reason.
In the success function, after you parse the result into a json object, you can reference the members with a '.' E.G result.varName
<script>
function shake()
{
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else
{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: {userID: $("#userID").val(), pw: $("#pw").val()},
success: function(data){
try
{
var result = $.parseJSON(data);
// result is now a JSON object
}
catch (e)
{
alert("JSON Parsing Failed on" + data );
return 0;
}
console.log(result);
if(result.isValid === 1){
// do something
}
alert(result.Message);
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else
{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
<?php
if( !isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST')
{
exit;
}
if( !isset($_POST['userID']) || !isset($_POST['pw']) )
{
// need more validation than this
exit;
}
$output = array();
$output['isValid'] = '1';
$output['Message'] = 'Data transfered';
$output['moreData'] = false;
echo json_encode($output);
Change data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(), to:
data: {userID: $("#userID").val(), pw: $("#pw").val()}
Also, I'd recommend setting userID and pw vars before passing it in as it is easier to read and easier to maintain.

How to return an error callback in php?

I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});

Categories