Jquery Callback Was Not Called - php

I've Googled every instance of this error I can find, and none of the solutions work for me. In essence, I am doing what others have suggested. Despite that, I am receiving an error that my callback function is not being called. I am using Ajax/Jquery/JASONP to do a cross domain form submission using GET. Here is my code on the form side:
$(document).ready(function() {
$("#ajaxform1").submit(function(e){
e.preventDefault();
var surl = "http://blahblah/test_create_user.php?callback=?";
$.ajax({
type: 'GET',
url: surl,
crossDomain: true,
data: $('#ajaxform1').serialize(),
dataType: "jsonp",
success: function(msg) {
$.each(msg, function (index, value) {
if(value==1)
{
alert("New User Added");
} else {
alert("User Already Exists")
} }
});
},
error: function(xhr, status, error) {
var myerror = xhr+" "+status+" "+error;
alert("Failure Connecting to Kayako. Please Try Again("+myerror+")"); }
});
Here is the applicable snippet of my PHP Code:
if($USER_CHK->first()->id){
$data = array('msg' => '0'); // user exists
else {
$data = array('msg' => '1'); // User added
}
//echo customerAdded(FALSE);
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization,X- Requested- With');
header("Content-type: application/json");
$data = array('msg' => '0');
print $_REQUEST['callback']. '('.json_encode($data).')';
exit;
});
});
My debugging shows that all form variables are getting posted.
The PHP code returns: jQuery11020900643879813015_1397599599587({"msg":"1"})
Yet the error indicating the callback was not called is thrown.

How does the request looks like on the server side?
I have a working example which is very similar to what you have. The only difference is that the content type I am replying with is:
'text/javascript'
Also, my JSONP message includes a semicolon at the end (which I think is not really a cause for failure).
returnJSONP = $_REQUEST['callback']. '('.json_encode($data).');';
If you were able to resolve, could you please post the solution?

I gave up trying to get this working and, instead, posted to a local php script which then used CURL to post to the remote server. I echo the CURL results back to the jQuery function and all works well.

Related

Axios and reactjs showing empty posted data at php backend

Iam using the Axio Reactjs code below to post form data to php backend.
when I check record.php files from the chrome browser console and
network. it shows that connection is okay but posted data is empty. it seems like the axios is not sending the data to php backend.
I have tried some solutions here on SO but cannot get it to work. Any work around will be appreciated.
axios({
method:'POST',
url:'http://localhost/mydata/record.php',
rec:{
myParameter1: 'test',
myParameter2: 'test2',
}
}).then(res => {
const data = res.data;
this.setState({ data });
console.log(data);
})
.catch(err => { // log request error
//this.setState({ error: false });
console.error(err);
})
php code
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
//header("Content-Type: application/json");
//check if file_get_contents is enabled
if( ini_get('allow_url_fopen') ) {
echo "enabled";
} else{
echo "not enabled";
}
$data = file_get_contents("php://input");
$request = json_decode($data);
print_r($request);
print_r($data);
?>
In axios docs you can find data tag:
https://github.com/axios/axios#request-config
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
this is what you need, there is no rec property in axios config
Try removing the key rec in your data segment in axios or better still do something along the lines of
{
rec: {
myParameter1: 'test',
myParameter2: 'test2',
}
}

Ajax and php Response doesn't work

I really like the help here and normally i figured out any Problem so far just by reading the existing Posts. However this time i can't quiet figure out whats wrong in my code.
I want to write dataildata values of a specific Tablerow in a form. The Data is stored in an mysql database and I access it with php.
The Probleme is that it seems that the Ajax request isn't working. neighter the success nor the error Event get triggered. Although the alter(id) works just fine.
Here is the Ajax call of the function:
$( "#table1 tbody tr" ).on( "click", function() {
var id = $(this).attr('id');
alert( id );
$.ajax({
type: 'POST',
url: 'getDetailData.php',
dataType: 'json',
data: {id : id },
success: function(data){
$("#inputWstId").val(data.WST-ID);
$("#inputSerialNumber").val(data.SERNO);
$("#inputName").val(data.NAME);
alert(data.NAME);
alert ("Test");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
and here is the .php File:
<?php
header('Content-Type: application/json');
$connect = include 'connect.php';
if (isset ($_POST['id'])){
$id= $_POST['id'];
}
$query = " select * FROM pci WHERE id= ". $id ;
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
"WST-ID" => $ligne["WST_ID"],
"SERNO" => $ligne["SERNO"],
"NAME" => $ligne["NAME"]
);
mysql_close($connect);
echo (json_encode($data));
?>
If you Need more sourcecode or anything else just let me know- Thank you so much for your help!!
WST_ID instead of WST-ID really worked - thank you so much !!
Why is it, that I can't use a "-" in my values ... guess there is a lot more to learn ;)
In the PHP part you need add two more headers :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
Add the two line of coding with the:
header('Content-Type: application/json');
change the:
echo (json_encode($data));
to:
print $my_json = json_encode($data);
or:
print_r ($my_json);
Hope it will work.
I think you need to give absolute url. Only getDetailData.php will not work. Try http://xyzabc.com/getDetailData.php

PHP json_encode data returned to AJAX call goes to fail and not done

Scenario: I have a php script which outputs data in json_encoded array, and an index html page with javascript which calls the php script via AJAX and handles the results.
Problem: AJAX call goes to .fail instead of .done even though it's getting a 200 response code and the responseText is json_encoded array.
After struggling with this I'm looking to you for help, not flames and unwarranted downvotes; I've researched this but the similar questions haven't resolved the issue.
getDomains.php:
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$domains = array();
$domains[] = array('domainID' => 1, 'domainName' => 'alpha.com');
$domains[] = array('domainID' => 2, 'domainName' => 'beta.com');
echo json_encode($domains);
?>
getDomains.php output in browser:
[{"domainID":"1","domainName":"alpha.com"},{"domainID":"2","domainName":"beta.com"}]
index.html/ajax.js:
<script>
// Ajax execute
var go = $.ajax({
url: 'getDomains.php',
type: 'POST',
dataType: 'json'
})
.done(function(results) {
console.debug('callAPI done');
console.debug(results);
})
.fail(function(msg) {
console.debug('callAPI fail');
console.debug(msg);
})
.always(function() {
});
</script>
When I visit index.html I see callAPI fail message in console.log.
callAPI fail
Object { ...
responseText: "[{"domainID":"1","domainName":"alpha.com"},{"domainID":"2","domainName":"beta.com"}]"
status: 200
statusText: "OK"

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

jquery POST does not return any result in https

I have a jquery script that just runs fine on http://mysite.com
and looks like this:
Javascript:
$('#form_changePass').live('submit', function() {
//alert('form_changePass cliked');
$.POST("_ajaxCall.php", $(this).serialize(),
function(data){
var json = eval('('+data+')');
//alert(data);
if(json.message=='alert') {
$('div.info').hide();
$('div.alert').show().html(json.string);
}
if(json.message=='info') {
$('div.alert').hide();
$('div.info').show().html(json.string);
}
}
);
return false;
})
PHP script:
if ($_POST['formType']=="form_changePass") {
.....
.......
$arr = array( 'message' => 'info', 'string' => $INFO['updatePass']);
echo json_encode($arr);
}
Now when I move the domain into https the jquery script is not working anymore. I do not get any return value back. Nothing happens.
I also tried to change the POST to getJSON in the javascript and changed the $_POST to $_GET in the php script but it is still not working.
Anybody a idea?
http and https are considered different domains, so it is a cross domain issue. The fix is:
header('Access-Control-Allow-Origin: https://domain.com');
Add this to your php script. Or this only in development so you don't need to worry too much:
header('Access-Control-Allow-Origin: *');
.serialize serializes the form data as a string, so send them using a parameter instead.
$('#form_changePass').on('submit', function() {
//alert('form_changePass cliked');
$.POST("_ajaxCall.php", { formData: $(this).serialize() },
function(data){
var json = eval('('+data+')');
//alert(data);
if(json.message=='alert') {
$('div.info').hide();
$('div.alert').show().html(json.string);
}
if(json.message=='info') {
$('div.alert').hide();
$('div.info').show().html(json.string);
}
}
);
return false;
})
And stop using .live() methods, they have been deprecated now. Use .on() methods.

Categories