Asked  7 Months ago    Answers:  5   Viewed   30 times

I am still struggling to get my head around the ins and out of JQUERY, AJAX and PHP.

I can now call the PHP OK, process the form elements and send an email, but I am not handling the return to the AJAX. I am always getting the error: selector activated and when I try to list the supposed JSON returned, I get info, that is obviously wrong.

PHP with supposed JSON return

<?php

touch('phpTouch.txt');
// process email
$email=1;
if ($email) {
    $value = array('return' => 1, 'msg1' => 'Message sent OK, we will be in touch ASAP');
} else {
    $value = array('return' => 0, 'msg1' => 'Message Failed, please try later');
}
$output = $json->encode($value);
echo $output;

?>

Javascript and AJAX

function submitForm(evt) {
    $('#msgid').html('<h1>Submitting Form (External Routine)</h1>');
    if ($('#formEnquiry').valid() ) {
        $("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
            $.ajax({
            url: "ContactFormProcess3.php",
            type: "POST",
            data: $('#formEnquiry').serialize(),
            dataType: "json",
            success: function (data) {
                alert("SUCCESS:");
                for(var key in data) {
                    $('#msgid').append(key);
                    $('#msgid').append('=' + data[key] + '<br />');
                }
            },
            error: function (data) {
                alert("ERROR: ");
                for(var key in data) {
                    $('#msgid').append(key);
                    $('#msgid').append('=' + data[key] + '<br />');
                }
            }
        });
    } else {
        $('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
    }
    evt.preventDefault();
};

Listing of supposed JSON data

readyState=4
setRequestHeader=function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}
getAllResponseHeaders=function (){return s===2?n:null}
getResponseHeader=function (a){var c;if(s===2){if(!o){o={};while(c=bF.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c}
overrideMimeType=function (a){s||(d.mimeType=a);return this}
etc etc 

If anyone can advise as to what stupid mistake I have made, then I would be most grateful.

 Answers

85

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
Wednesday, March 31, 2021
 
samrap
answered 7 Months ago
46

I found the error: my base layout was still including HTML code in the response. I followed the steps in handle JSONP calls in ZEND (second answer) and now it works perfectly. Thanks for the help anyway!

Wednesday, March 31, 2021
 
rasmusx
answered 7 Months ago
44

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}
Sunday, June 13, 2021
 
buymypies
answered 5 Months ago
60

However when I make a change in JSON encoded string - adding Backslash to single quote

That escapes it in the PHP string literal. It is then inserted into the PHP string as a simple '.

If you want to escape it before inserting it into JavaScript then you need to add slashes to the string you get out of json_encode (or rather, since you aren't using that (you should be!) the JSON string you build by hand).

That is more work then you need though. The real solution is to remember that JSON is a subset of JavaScript literal syntax:

var obj = <?=$data?>;
Sunday, August 8, 2021
 
MM1
answered 3 Months ago
MM1
80

I think that you are not returning a valid json: try something like:

  return  "{"name":"unknown", "age":-1}"

because this

{
    "name": "unknown",
    "age": -1
}

is a valid JSON (You must use ", not ') while this is not

{
    'name': 'unknown',
    'age': -1
}

You should also specify the datatype

 $.ajax({  
       type: "GET",  
       url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2",  
       dataType: "json",  
       success: function(resp){  
         // we have the response  
         alert("Server said123:n '" + resp.name + "'");  
       },  
       error: function(e){  
         alert('Error121212: ' + e);  
       }  
     });
Thursday, August 19, 2021
 
Marcus Junius Brutus
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share