Reputation: 121
I'm not sure if I'm doing something wrong here. I have been looking into this quite a while now. I have basically looked trough everything on google and on this page and still haven't understood how my first page should look like in order to get this to work.
<script>
//firstpage.php
function fetch(){
$.ajax({
url: 'secondpage.php',
type: 'POST',
data: {
id:'ok'
},
success: function(data){
//var data = jQuery.parseJSON(data);
if (data.phpvar == 'ok'){
alert('Success!');// for testing
}else{
alert('Failure!');// for testing
}
}
});
}
</script>
ajax requesting the second page:
<?php
//secondpage.php
if($_POST['id'] == 'ok'){
$return_data['phpvar'] = 'ok';
return json_encode($return_data);
}
?>
What am i doing wrong??? I'm new to ajax, so please explain the best way possible. My goal is simple enough, it is to grab PHP variable with value "ok" from the second page and pass it back to the first page as a type of a confirmation to find out which PHP if() condition was entered->(depends on the sql database response).
Upvotes: 0
Views: 888
Reputation: 121
Nevermind! My experience now with ajax has been that I don't really need to grab a PHP variable at any point. Because if something needs to be checked for existence, then we either use SESSION check or a COOKIE check on the 1st or the 2nd page. Otherwise we use jquery data to send it like so:
<script>
//firstpage.php
$.ajax({
type:'POST',
url:'secondpage.php',
data:'id=ok&do=check',
success:function(data){
if(data=='good'){
//do stuff
}
if(data=='bad'){
//do stuff
}
}});
</script>
requesting page:
if($_POST['id'] == 'ok' AND $_POST['do'] != ''){//something was sent, do..
echo 'good';
}else
if($_POST['id'] == 'ok' AND $_POST['do'] == ''){//if nothing was sent, do..
echo 'bad';
}else{/*do nothing*/}
?>
And in the end if absolutely necessary, we can always try to find a way to run PHP in JS file and try to do a splitting of the data using PHP functions and then returning the split data as an ARRAY and then we can use array sections like $data[1] or $data[2].. etc.. in our code to perform different tasks using the exactly same data string in jQuery.
Upvotes: 1
Reputation: 318488
You need to get rid of var obj = jQuery.parseJSON(data);
and use data
directly. jQuery usually detects JSON and automatically parses it. Add dataType: 'json'
to your ajax arguments to be sure though.
Besides that you should change your PHP script to always return some JSON - and if it's just an empty object.
Upvotes: 1