AJAX - Why page redirect is failing here? - javascript

I have a problem here. I am posting data using $ajax to update a MySQL table. The update logic is done fine.
PHP Snipet
$count=$stmnt->rowCount();
if ($count==1){
$output=array('op'=>'tt');
echo json_encode($output);
}else{
$output=array('op'=>'ff');
echo json_encode($output);
}
JS Code
success: function(data) {
console.log(data);//On update, this is printing{"op":"tt"}
if (data.op ==='tt') {
console.log(data);//this is not executing.
window.location.href= 'post.php'
}else{
alert("Error!");
}
}
I have realized that my if statement is not being executed. What has gone wrong here?

By default, jquery ajax without a dataType will try to set the response based on the MIME type.
If you have a string, you can manually parse it, ie:
success: function(data) {
data = $.parseJSON(data);
or you can specify the dataType for jquery to use on the $.ajax request.

You should parse the json first before you can get the plain text out of it.
var result = jquery.parseJSON(data);
if (result.op == 'tt') {
...
}

Related

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

jQuery ajax php function

I have never been in contact with ajax. Can I get some help?
I know how to call a php script.
Example:
<script>
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#mybox").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
How can I get a response from function? If my ajax.php has function
<?php
function example(){
return "blablalba.....";
}
?>
How should my script looks like?
How can i get a response from function?
The same way you get a response from any other PHP script. The Ajax is irrelevant.
header("Content-Type: text/plain"); // or whatever
print example();
The PHP script just needs to display content as it would if you loaded it directly in the browser, using echo or simply closing your PHP tag ?> and outputting HTML or similar.
You should not return, you should send actual output. For example: a JSON encoded string or array, with the correct content type. The result will populate to the variable mentioned in request.done, i.e. msg.
You will need to use echo rather than return.
ajax.php
<?php
function example(){
echo "blablalba.....";
}
?>
It depends on the content of which you are using.
Since you specified content is HTML, your response will be a string with HTML code (as if you wrote it in notepad).
But AJAX as far as I know wont get response unless "echo 'html code'" is used in php.
<?php
echo '<body><div>Response from php script</div></body>';
?>
So fix your php code first. Then in AJAX set "data" as function argument and use it inside function. Data will be your response from php.
.done(function(data){
var smth = data;
});

Sending data from javascript to php using via Ajax using jQuery. How to view the data back?

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!

submitting a form using $.ajax

I'm calling this function when the dom is ready on $().submit
but it seems not working there is no response from server
$(function(){
$("#logingform").submit(function(){
var values =$(this).serialize();
call_server("../php/login.php",values);
});
});
function call_server(URL,DATA)
{
$.ajax(
{
type:'POST',
url : URL,
data : DATA,
dataType:'json',
success:function(response){
$("#d1").append(response);
}
}
);
}
nothing seems to get back from the server.
server code
<?php
$email = $_POST['loginemail'];
$password =$_POST['loginpassword'];
echo json_encode(array('returned_val' => 'yoho'));
There is an extra semi colon following your ajax option:
data : $(this).serialize();,
vs correct
data : $(this).serialize(),
You do not need to parse the json that is returned, since you already have dataType:'json' defined in the ajax options.
$("#d1").append($.parseJSON(response));
That is not necessary.
If you want to show the response object as a string, then you need to stringify it instead:
$("#d1").append(JSON.stringify(response));
Also, you have a syntax error on this line:
data : $(this).serialize();,
Remove the ;.
Your data for a POST should be in json format, so rather than $(this).serialize(), use $(this).serializeArray() for your data. This will pass those values for POST body rather than in the querystring.

JSON with jQuery and PHP

I have a script for updating a database table. I need to return a JSON array and to update some tables with JQUERY.
my php script:
$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);
jquery code:
$("button").live("click", function(event) {
event.preventDefault();
$.getJSON("startsearch.php", {
searchId: $(this).val()
}, function(data) {
alert(data[0].status);
});
now ...the problem is that if i use $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) the script gets executed and i get a nice alert with value undefined. if i add the parameter "json" the script doesn't get executed anymore. I tried to use getJSON but again the same problem.
Anybody has any ideas? I am desperate...this has been bugging me for almost a week and I still haven't managed to solve it.
In your php file make sure to set the correct content type:
header("Content-type: application/json; charset=utf-8");
so that jquery can correctly eval the response into a json object.
You can get to your response data as follows:
alert(data.status);
alert(data.results);
alert(data.totalResults);
please don't use alert, install firebug into your firefox or enable the javascript console in chrome or safari. after that you can use console.log(data);
my guess is that data isn't an array. also have a look at the each() exmaple on the jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON
Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.
I always write my AJAX request like this:
$.post(URL,
{ PARAM },
function(data){
try {
var r = JSON.parse(data);
//this for your code above
alert (r.status); //should be 'COMPLETED'
}
catch (e) {
//data is not in json format, or there are another exception in try block
//do something about it
alert('Exception occured, please check the data!');
}
});
When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.

Categories

Resources