jQuery - POSTing with JSON and receiving both JSON and HTML - javascript

I have an HTML page, that posts JSON information to the server.
If the server thinks there is an error with the information posted, it returns a JSON string so that the client can modify the current HTML page with an error message.
Otherwise, the server returns a new HTML page.
How can I handle this in jQuery?

Well, then you can put the html page content into a json variable and still return it as a json. In that way you would be still following practice.
Example:
PHP pseudo code:
if($ok) //you condition here
{
$html = file_get_contents("newPage.php");
$toEcho = array("status"=>"true" , "message"=>"successful", "html"=>html);
$json_parsed = JOSN_encode($toEcho);
echo $json_parsed;
}
else
{
$toEcho = array("status"=>"false" , "message"=>"Wrong information", "html"=>false);
$json_parsed = JOSN_encode($toEcho);
echo $json_parsed;
}
JS pseudo code:
$.ajax({
url: "yourUrl.php",
type: "post",
data:"json"
}).done(function (result){
if(result.status==="true")
{
if(result.html)
{
$("#oldDiv").html(result.html);
}
}
else if(result.message)
{
$("#errorMsg").html(result.message);
}
});

It's bad practice but you can try parse the response:
$.ajax({ url: " ....URL...." , type:"POST" , data:{.. your variables ..} })
.done(function(response) {
var tryRes = false;
try { response = $.parseJSON(response); tryRes = true; }
catch (e) { }
if (tryRes) {
//JSON ~ resonse is allready an object
} else {
//OTHER ~ HTML
}
}).fail(function(response) {
//Bad request
});

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

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.

How to make jQuery alert if PHP response is equal to something

I have this jQuery script:
$(document).ready(function(){
$('#submitNewExam').click(function(e){
e.preventDefault();
var examName = $('#newExam').val();
if ($.trim(newExam) != ''){
$.post('functions/addExam.php', { newExam: examName }, function(data){
console.log(data);
if(data =='error'){
$('#notify').html(data);
$('.alert').toggle();
}
});
}
$('.add').toggle();
});
});
and this PHP:
if(isset($_POST['newExam'])){
if(preg_match('/(<|>|"|%3c|%3e|%22)/', $_POST['newExam'])){
$a = 'error';
echo json_encode($a);
} else {
echo "something";
}
}
I'm able to output the response of PHP, what I'm not able to do is to make jQuery read that response and do something if the response in my example is equal to error. I have tried to encode the response in JSON and just to echo the response as a string, but none of those is working. In the console.log I can see the response but jQuery is doing nothing.
Without parsing of the json, your string will contain quotes: "error".
You can either manually parse the json or have jQuery do it automatically by specifying a data type:
$.post('functions/addExam.php', { newExam: examName }, function(data){
console.log(data);
if(data =='error'){
$('#notify').html(data);
$('.alert').toggle();
}
}, 'json');
^^^^ here you specify the data type

jquery ajax json doesnt return true

i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}
You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");
you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.

PHP/ Ajax/ jQuery - Equivalent for my code

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.
You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);
JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Categories

Resources