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

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

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

Cant read php JSON encoded data in js

I'm calling a php script via AJAX which returns a json encoded object.
$.post("php/getCamera.php", {
cam_id: identifier
}, function(data){
console.log(data);
//var camera = JSON.parse(data);
var camera = $.parseJSON(data);
console.log(camera.name);
console.log(data['name']);
console.log(camera['name']);
});
}
Here's my php script:
<?php
require 'Camera.php';
$camera = new Camera();
if(isset($_POST["cam_id"])) {
$cam_obj = $camera->getCamera($_POST['cam_id']);
$cam_obj_array = get_object_vars($cam_obj);
echo json_encode($cam_obj_array);
}
?>
And here's my camera class:
class Camera
{
public $id;
public $name;
...
}
In the js console, I see the encoded data, but I can't access its elements:
{"id":"6","name":"camera 1"}
undefined
undefined
undefined
undefined
add 'json' at the end of your post request :
$.post("php/getCamera.php", {
cam_id: identifier
}, function(data){
console.log(data);
console.log(camera.name);
console.log(data['name']);
console.log(camera['name']);
}, 'json');
}
It's a shorthand for full ajax syntax dataType: "json".
Better, use getJSON instead of post (but then, remove 'json' :)
Try this:
console.log(data.name);
It appears, from your log, that the data is already a JSON object, and so needs no further parsing.

jQuery - POSTing with JSON and receiving both JSON and HTML

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

jQuery ajax issue(succes data not correct)

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... :)

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