3

I am trying to call a php script that accepts JSON data, writes it into a file and returns simple text response using jQuery/AJAX call.

jQuery code :

   $("input.callphp").click(function() {
    var url_file = myurl;
    $.ajax({type : "POST",
            url : url_file,
            data : {puzzle: 'Reset!'},
            success : function(data){
                alert("Success");
                alert(data);
            }, 
            error : function (jqXHR, textStatus, errorThrown) {
                alert("Error: " + textStatus + "<" + errorThrown + ">");
            },
            dataType : 'text'
    });
});

PHP Code :

<?php
  $thefile = "new.json"; /* Our filename as defined earlier */
  $towrite = $_POST["puzzle"]; /* What we'll write to the file */
  $openedfile = fopen($thefile, "w");
  fwrite($openedfile, $towrite);
  fclose($openedfile);
  echo "<br> <br>".$towrite;
?>

However, the call is never a success and always gives an error with an alert "Error : [Object object]".

NOTE

This code works fine. I was trying to perform a cross domain query - I uploaded the files to the same server and it worked.

2 Answers 2

2
var url_file = myurl"; // remove `"` from end

Arguments of error function is:

.error( jqXHR, textStatus, errorThrown )

not data,

You can get data (ie. response data from server) as success() function argument.

Like:

success: function(data) {

}

For more info look .ajax()

NOTE

If you're trying to get data from cross-domain (i.e from different domain), then you need jsonp request.

Sign up to request clarification or add additional context in comments.

7 Comments

success: function(data) { ... } is perfectly valid.
Yes, but you said (before your edit) that the arguments are not data, which is incorrect.
@JamWaffles I told that for .error(), anyway thanks Sir, for your comment
Ah, so you did, my apologies.
#thecodeparadox : thanks for the reply. I have updated the code after making the suggestions, however, i am still getting an error alert "Error: error<>".
|
0

Your data object isn't valid; the key shouldn't be quoted:

data : { puzzle: 'Reset!' }

In addition, SO's syntax highlighting points out that you have missed out a " in your code:

var url_file = myurl";

Should be

var url_file = "myurl;

1 Comment

thanks for the reply. I have updated the data object (edited the original post). But, I am still getting an error alert "Error: error<>".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.