jQuery ajax issue(succes data not correct) - javascript

I am building a small ajax contact form and i am testing it with a basic php file(learning the whole jQuery ajax thing), but for some reason it doesn't works.
Even if the data is correct it stil gives me the error code(if data = ok doent work).
here's the basic jquery code
$(document).ready(function ($) {
$("#contactform").submit(function(){
var str = $(this).serialize();
$.ajax({
type: obj.attr('method'),
url: obj.attr('action'),
data: str,
dataType: 'html',
success: function(data){
$('.acf-wrap').ajaxComplete(function(event, request, settings){
if(data == 'OK'){
msg = 'success';
}else{
msg = data;
}
//display msg
$(this).html(msg);
});
}
});
return false;
});
});
test php file
if(1 == 1){
echo 'OK';
}else{
echo 'error!!!';
}

Your PHP will never echo 'OK', because 1 will never equal 2. At least not in the universe I'm from.
if(1 ==2){
How can that ever be true? Either it won't, or a philosopher will need to weigh in.

The data is probably a JSON string. JSON.parse the data and access the "d" property...
var parsed = JSON.parse(data);
if(parsed.d == 'OK'){
alert('works');
}
Actually wrote this answer on my phone... Might not be right. Couldn't test it... :)

Related

unable to parse xml data with AJAX + Wordpress

Ok, I am officially stumped. I have been trying to find why my calls for specific items in a PubMed xml data file are not working... I can execute this one with my current coding:
$test = (string)$id_json->PubmedArticle->MedlineCitation->PMID;
but if I try to get a variable that is in a deeper array, it does not return a value. I have even tested with console.log(data) and I get my PMID returning but not my other, deeper values in the XML file. For example;
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
returns nothing for data in console.log(data)
Here is my function in wordpress:
function get_abstract(){
$id = $_POST['abstractid'];
$pubmed_api_call = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id='.$id;
$id_wpget = wp_remote_get($pubmed_api_call, array('timeout' => 20));
if( is_wp_error( $id_wpget ) ) {
echo "Error Contacting PubMed, please refresh page and try again";
die();
}
$id_xml = wp_remote_retrieve_body($id_wpget);
$id_json = simplexml_load_string($id_xml);
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
if($test === ""){
echo "NOTHING";
die();
}
echo $test;
die();
}
and here is my javascript AJAX call:
jQuery(document).ready(function() {
jQuery('.reference_header').click(function(e) {
jQuery(this).find("i").toggleClass("arrow-down arrow-up");
jQuery(this).nextUntil('.reference_header').slideToggle('fast');
var abstractid = jQuery(this).data("id");
e.preventDefault();
jQuery.ajax({
url: get_abstract.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
abstractid: jQuery(this).data("id"),
action: 'get_abstract'
},
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data);
console.log(data);
}
});
});
});
I cannot find out why it doesnt work... any help is greatly appreciated.
So I figured out the solution to the issue... you need to pass the string text as a json object to AJAX for it to read properly...
working code:
PHP:
echo json_encode(array("result" => "$test"));
die();
AJAX:
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data.result);
console.log(data.result);
}

Unable to send JSON via AJAX

I made a function which counts how much time I spent on some page and where I came from. I collect all the data and save it into a JSON but when I try to send that JSON via ajax on the success it alerts me with an empty alert box, which means that nothing is being sent. I tried to add async to false because I use the onbeforeunload function but that doesn't work. I tried numberless combinations with AJAX setting but nothing is working.
HTML / JS
(function(){
var time,timeSite,endTime,seconds,testObject,retrievedObject,text;
window.onload=function(){
time= new Date();
}
window.onbeforeunload=function(){
endTime = new Date();
timeSite= time.getTime()-endTime.getTime();
seconds =Math.abs(timeSite/1000);
window.localStorage['seconds']=seconds;
text = 'Visitor accessed site directly.';
if(document.referrer == ''){
var link = text;
} else{
var link = document.referrer;
}
var url = window.location.href;
var main = {
'From': link,
'Current was' : url,
'Time Spent': seconds
}
$.ajax({
type: "POST",
data: {'data': main},
url: "http://localhost:8080/projectFour/test.php", //i use this page only to check if i receive data
contentType:'application/json',
success: function(data) {
alert(data);
},
error: function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
}
})();
Test.php
<?php
if(isset($_POST['main'])) {
$obj = json_decode($_POST['main']);
//some php operation
echo $obj;
}
?>
Your test.php is looking for a POST variable called main, but you're sending one called data.
You can change the data part of the ajax call from:
data: {'data': main}
to
data: {'main': main}
and that should cause it to post the variable with main as the variable name.
Secondly, when you return the data, it would be better to return it as JSON again, otherwise it might mangle the result a bit.
Replace
echo $obj;
with
echo json_encode($obj);
And in the ajax replace
alert(data);
with
alert(JSON.stringify(data));
That will give you a view of the returned data structure as a string.
You should also consider returning something from PHP when the if statement is false, whether that be an error code, or some other response. Sending no response in this case isn't very helpful to the client side, and has hindered your debugging.

Script return blank just in jQuery AJAX

I've got very frustrating problem. I send AJAX request to PHP file and when I see Chrome Network Tools, it donť return any JSON. But when I try post the same data via POSTMAN tool in Chrome, it return right. When I open script normally, it return right. Just when I sen request via AJAXm it return nothing.
This is my PHP file: (I know it's functionally useless at this time, i need fix this error before it can do what I need)
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
echo $json;
At line 3 must be problem, because when I put it out, it works. But function is 100% exist, 'cause when i put nonsense name of function, it write an error. DB query is also right, i tried it in phpMyAdmin console.
This is my AJAX request:
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if(vysledek.stav===1){
window.location.href("../index.php")
}
else if(vysledek.stav===2){
alertify.error('Špatné uživatelské jméno');
}
else if(vysledek.stav===3){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
How I wrote, if I open PHP file in browser, it echo {"stav":2}, when I try POSTman, it echo {"stav":2}. But when I run AJAX request, it makes nothing. I really don't know what is wrong.
EDIT
Firebug:
Here
can you please try with the following code
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if( parseInt(vysledek.stav) == 1 ){
window.location.href("../index.php")
}
else if( parseInt(vysledek.stav) == 2 ){
alertify.error('Špatné uživatelské jméno');
}
else if( parseInt(vysledek.stav) == 3 ){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
<?php
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
print_r($json);
?>
Remember to parse JSON to the response
...
success: function (vysledek){
var vysledek = (vysledek);
if(vysledek.stav === 1){
window.location.href("../index.php")
}
...

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

How to beat my CodeIgniter bad practices

Accessing functions from the view?
I know the correct way should be that the controllers handles all the function calls, but
If I need to call another function and pass a variable that comes from a db data in a loop in view eg.
view:
if($persons != ""){
foreach($persons as $p){
echo $p->name;
echo $p->lastname;
// Now I need to call a function and pass parameters from loop
$is_banned = $this->model_users->checkIfBanned($p->name);
echo $is_banned;
}
}
How should I do this the right way in the controller?
Other thing is the javascript ajax calls. I have been putting lots of javascript in the controllers when I need to receive more than one response. For instance, if i need to get all the posts from a user via ajax and get the response to update the posts div, plus get the number of posts and update the post count div.
The wrong way I've been doing:
eg. js:
function insertNewPost(){
var the_text = $('#post_text_input').val();
if(the_text != ""){
$.ajax({
type:"POST",
url:base_url+"controller/insertNewPost",
data: {post_text: the_text},
cache:false,
success:function(response){
$('#post_output').prepend(response);
$('#post_text_input').val('');
}
});
}
Controller:
function insertNewPost(){
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->load->model('model_posts');
$email = $this->session->userdata('email');
$myid = $this->model_users->getUserId($email);
$post_text= $this->FilterData($this->input->post('post_text'));
if($this->model_posts->insertNewPost($myid,$post_text)){
$count = $this->model_posts->countPosts($myid);
echo 'More recent: '.$post_text;?>
<script>
var count = "<?php echo $count;?>";
$('#posts_count').html(count);
</script>
<?php
}
}else{
redirect("inicio");
}
}
Is it possible to get 2 responses at the same time and update content from 2 divs at the same time? How would I get hold of the $count variable and pass it on the same ajax response?
Any light shed would be very greatful.
Thanks in advance
As suggested by #charlietfl:
Changed the Controller:
function insertNewPost(){
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->load->model('model_posts');
$email = $this->session->userdata('email');
$myid = $this->model_users->getUserId($email);
$post_text= $this->FilterData($this->input->post('post_text'));
if($this->model_posts->insertNewPost($myid,$post_text)){
$content = 'More recent: '.$post_text;
$count = $this->model_posts->countPosts($myid);
$items = array($content,$count);
echo json_encode($items);
}
}else{
redirect("inicio");
}
}
And changed the js function:
function insertNewPost(){
var the_text = $('#post_text_input').val();
var post_count = '#posts_count';
if(the_text != ""){
$.ajax({
type:"POST",
url:base_url+"controller/insertNewPost",
data: {post_text: the_text},
cache:false,
success:function(response){
var content = json_encode(response);
$('#post_output').prepend(content[0]);
$(post_count).html(content[1]);
$('#post_text_input').val('');
}
});
}
it's not happening, i must be doing something wrong.
For your first problem:
Its OK the way you doing.But I don't recommend it because it is not programmer friendly.
You can solve it many way.
Here is one solution that you want.
Process your controller before sending data at view this way after getting persons
for($i=0;$i<sizeof($persons);$i++)
{
$persons[$i]->is_banned=$this->model_users->checkIfBanned($persons[$i]->name);
}
Now send this new $persons to your view.Your new view code will be like this
if($persons != "")
{
foreach($persons as $p)
{
echo $p->name;
echo $p->lastname;
echo $p->is_banned;
}
}
Hope you understand this.
For your second problem you can use #charlietfl solution.
Here is summary:
Instead of calling multiple ajax call- call one ajax and return all the results as array.Like
function insertNewPost()
{
//do your stuff;
$data['content']="something";//it may be anything array,string
//do your stuff;
$data['count']="something";
//do your stuff;
$data['moreresult']="something";
header('Content-type: application/json');
echo json_encode($data);
exit();
}
Now at your js
function insertNewPost()
{
var the_text = $('#post_text_input').val();
if(the_text != "")
{
$.ajax({
type:"POST",
url:base_url+"controller/insertNewPost",
data: {post_text: the_text},
dataType: "JSON",
success:function(response){
//here you will get datas as response.content,response.count,response.moreresult
//Now use them as you want as example
$('#post_output').prepend(response.content);
$('#post_text_input').val(response.count);
$('#anotherid').val(response.moreresult);
}
});
}
Hope it will help you.

Categories

Resources