Ajax success does not work without alert message - php

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.

Related

AJAX / PHP - Get specific data back from POST (Pass data)

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'){
}
}

how do i get a response from a jquery ajax request

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');
}
})

jquery json request failed

I'm trying to make a json call with jquery but noting happened. My code:
javascript:
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
}
});
});
});
</script>
PHP
$output = array(
'percentage' => "50"
);
echo json_encode($output);
Any suggestions?
The code looks fine to me,
EDITED
Also try removing the protocol and use url: "//<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
if you add and error callback to the ajax call you should get some error printouts to let you know what is going on
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error : function (e1, e2, e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});
EDIT:
i just had a thought, if i remember correctly jquery ajax doesnt like using full url's if possible try using a relative path

$.ajax get return value from a PHP file

here I have jQuery ajax calling a .php file that SOMETIMES executes let's say the following
echo "hello"
Here it is:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
}
});
I would like to know: is it possible to make the ajax return ERROR and not SUCCESS when something like the previous echo is executed in the PHP file? I mean, checking inside this $.ajax if the php file is executed as I would or not.
EXPLAINING BETTER:
I get error when the request could not be completed and success when it could. But I would like to get like a return value from this PHP file. If it returns 1, I wanna do something. If it returns 2, instead, I wanna do something else. Hope I explained it better..
Thanks in advance.
I recommend using json_encode() within your PHP file. For example:
echo json_encode(array('success' => 'do_foo'));
exit();
Then you can add a conditional within the success callback:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
dataType: "JSON", //tell jQuery to expect JSON encoded response
timeout: 6000,
success: function (response) {
if (response.success === 'hello'){
console.log(response);
} else {
console.log('else');
}
}
});
Based on your question make php return 1 or return 2. You can make it return 1 on failure and 0 (which is null) on success. Then you can do this for your ajax return.
$.ajax({
type: "POST",
url: "YOUR URL",
data: dataString,
success: function(server_response)
{
if(server_response == 1)
{
alert("You have made a mistake");
return true;
}
HERE YOU WILL PUT WHAT HAPPENS ON SUCCESS
}
});
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function (msg) {
if (msg != "Hi")
{
//TODO
} else
{
//TODO
}
}
});
You can use error callback for this:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
},
error: function() {
/* Code reacting to error here */
}
});
Also, there are other callback opportunities which you can check out at $.ajax documentation page.
If you are going to "say" fron PHP that there is an error, this can be done with 2 ways:
You can print in PHP a keyword meaning an error and then check it in you success function:
success: function (data) {
if (data == 'error') {
} else {
}
}
Or, the other way, you can provide with PHP right headers to cause "error". Then you can use the error callback as usual. I would choose this way.

Cant get value back from PHP

JavaScript
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP file just a simple
print_r($_REQUEST);
Also tried
echo "got iT!";
But nothing, been looking of over tried differant things but no luck
first //alert (dataString); works
but after the success:function (data) I don't get any alerts - no response within the page!
What am I doing wrong?
There's a SyntaxError in your snippet. I'm not sure if that's also in your real code.
Be sure to use json_encode in your PHP file and dataType: 'json' in jQuery.ajax. And always use an error callback as well. You don't want your application to become indefinitely frozen if something fails.
Something like this:
$.ajax({
url: 'api.php',
data: {
action: 'greet',
foo: 'bar',
baz: 'quux'
},
type: 'POST',
dataType: 'json',
}).then(function (response) {
console.log(response); // DEBUG
if (response.error) {
alert('Greet Error: ' + response.error);
} else {
alert(response.greet);
}
}).catch(function (jqXHR) {
console.log('AJAX Error', jqXHR); // DEBUG
alert('AJAX Error: Request failed');
});
PHP:
<?php
$input = $_POST;
$response = array();
if (!isset($input['action'])) {
$response['error'] = 'Action parameter required';
} else {
if ($input['action'] === 'greet') {
if (!isset($input['foo']) || !isset($input['bar'])) {
$response['error'] = 'Invalid greet request';
} else {
$response['greet'] = 'Welcome home, David!';
}
} else {
$response['error'] = 'Unknown action';
}
}
header('Content-Type: application/json; charset=utf8');
echo json_encode($response);
First: you missed dataType property from ajax function, next, you need to pass json type data, and you had a syntax error in code, try this:
$.ajax({
type : 'POST',
url : 'post.php',
dataType: 'text',
data: {
data_to_pass: dataString
},
success:function (data) {
if (data==null) {
alert("darnit!!!!");
} else {
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP:
$dataString = $_POST['data_to_pass'];
if($dataString) {
echo "got IT!";
}
JQuery ignoring your data return usually means it doesn't understand the format that's being returned, or doesn't know what to expect. Set the dataType to an acceptable format and also double check that your PHP script is actually sending something back to the page in Firebug's console.
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
dataType: 'text',
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
I would like share the following, and I think I've solved the problem.
Besides the fact that I did made a mistake, retrieving the values from the form a bit wrong.
so the first alert gave me name=[Object name], now that was stupid.
The problem of not getting results seemed to be a problem with jquery itself, in my case.
I do not know if it is the same problem other people are having. I replaced the included file of jquery 1.7 with 1.4.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
than with the following code (only from $.ajax).
var dataString = $("#contactForm").serialize();
$.ajax({
type: 'POST',
url: './php/mail.php',
data: dataString,
success: function(msg){
if (msg === 'sent'){
$('#success').text('Message sent!');
} else{
$('#success').text('Mail Error. Please Try Again.!');
}
}
});
Now i have it working - and gonna tweak it a bit to my needs!
Thx all for all help!
Try this:
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data===undefined) { alert("darnit!!!!");}
//$("#response").append(data);
alert(data);
}
});
});
Also I would look into using json_encode on an array in your php file and returning a json object.

Categories