I am encoding my returned response through JSON and trying to make it work as per the JSON Response's values.
Assume below values are what I am returning.
if ($upload = 1){
$response['status'] = 1;
$response['message'] = 'SUCCESS';
$response['success'] = 'false';
}else{
$response['status'] = 3;
$response['message'] = 'CATEGORY ASSOCIATED';
$response['success'] = 'false';
}
header('Content-type: application/json');
echo json_encode($response);
I will be retrieving it to my form and handle the action through the encoded responses.
$('#form').on('submit', function(e){
e.preventDefault();
var id = $('#id').val();
$.ajax({
type: "POST",
url: 'edit.php',
data: {cid:id},
success: function(response){
if(response.status = 1){
console.log('THE STATUS IS 1');
}
else if(response.status = 3){
console.log('THE STATUS IS 3');
}
}
});
});
The issue I am facing is I am getting both responses on browser's network tab. console prints status 1 but not status 3. Where am I making the mistake?
Try this.....
$('#form').on('submit', function(e){
e.preventDefault();
var id = $('#id').val();
$.ajax({
type: "POST",
url: 'edit.php',
data: {cid:id},
success: function(response,status){
if(status == 1){
const newres = JSON.parse(response);//parse the response
if(newres.status == 1)
console.log('The status is 1');
else if (newres.status == 3)
console.log('The status is 3');
}
else {
console.log('No response');
}
}
});
});
The json_encode($response); is a json format string, parsing makes it an object.
I'm absolutely new to asp.net and I want to create infinite scrolling using jQuery Ajax and ASP.NET MVC. So here;s what I got so far
<div id="container"></div>
<div id="progress" style="display:none">
<h4>Loading...</h4>
<div class="col-md-12 panel panel-default"></div>
</div>
<script type="text/javascript">
var pageSize = 10;
var pageIndex = 0;
$(document).ready(function () {
GetData();
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetData();
}
});
});
function GetData() {
$.ajax({
type: 'GET',
url: 'http://localhost:64949/api/values/delfi',
dataType: 'json',
success: function(data) {
alert("yra");
//if (data != null) {
// for (var i = 0; i < data.length; i++) {
// $("#container").append("<h2>" +
// data[i].CompanyName + "</h2>");
// }
// pageIndex++;
//}
},
beforeSend: function() {
$("#progress").show();
},
complete: function() {
$("#progress").hide();
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.' + jqXHR.responseText;
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]' + jqXHR.responseText;
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
});
}
</script>
I impemented scroll listener and every time I reach end of page I make new request to my api which simply returns json data. Here's what it returns
[{"Index":1,"List":{"Img":"http://g1.dcdn.lt/images/pix/jonas-udris-72559208.jpg","Title":"J. Udris. Scenarijai dėl Šilutės balsavimo reikalų","Description":"Policijai pradėjo ikiteisminį tyrimą dėl galimo rinkėjų papirkimo Šilutės rajone partijos „Tvarka ir teisingumas naudai. Ketvirtadienį policija pranešė sulaikiusi septynis asmenis, antradienį jų namuose atliktos kratos. Vienas asmuo suimtas 10 parų."}}]
However every time my ajax jumps to error function and jqXHR.status is always 0. I also try to pass url like this url: localhost:64949/api/values/delfi and still get the same response. What's wrong with my code?
You should not hardcode the URL.
If you use a Controller, you could go for:
url: '#Url.Action("Action", "Controller")',
For linking to your api, you should look at Attribute Routing
A quick fix could be:
url: '/api/values/delfi',
Edit: #lmad that is indeed no answer to ops question im sorry for that. Status code 0 means the requested url is not reachable, so what i would do is to edit the url with the code above!
I'm trying to send an AJAX response to a PHP file. Based on the response I would like to redirect to another page. If the response is success I would like to redirect to a 'thank you' page along with the parameter data.
How can I pass this transactionId to another page?
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
if (response == "success") {
window.location.href = 'http://www.google.com';
}
});
});
});
change your php output from
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
to
if ($result->success)
{
echo json_encode(array('status'=>'success','id'=>$result->transaction->id));
}
else if ($result->transaction) {
echo json_encode(array('status'=>'error','code'=>$result->transaction->processorResponseCode, 'text'=> $result->transaction->processorResponseText)));
}
else
{
echo json_encode(array('status'=>'error','text'=>$result->errors->deepAll()));
}
and change your js to the following
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
var data= $.parseJSON(response);
if (data.status == "success") {
window.location.replace('http://www.google.com?id='+data.id);
}else{
alert('Operation Failed');
if(data.code){
console.log('response code: '+data.code);
}
console.log('response text: '+data.text);
}
});
});
});
looking at your php code - it never returns success, it will return success!: somthing so this condition if (response == "success") is never true
you could use
if(response.indexOf("success") == 0)
or change the response in the php file
You can send the response variables you'd like by incorporating them into a query on the redirect.
For instance if you wanted to pass on foo to your redirected php domain.com/bar.php:
var url = 'domain.com/bar.php?foo=' + foo
window.location.href = url;
And then on the PHP page, you can use this data:
$bits = parse_url($url);
parse_str($bits['query'], $query);
echo $query['foo']
I am trying to send a "notification" or error messages from php to ajax. I'm trying to achieve something like this:
php:
if (myString == '') {
// Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
// Send "stringEqualsFoo" error to ajax
}
ajax
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(){
alert("It works");
},
error: function() {
if(stringIsEmpty) {
alert("String is empty");
} else if(stringEqualsFoo) {
alert("String equals Foo");
}
}
});
How can I send error messages to ajax?
Update
Here's the php file I have. I tried using the echo solution answers said, but when I output what the data is (in ajax), I get undefined:
<?php
$img=$_FILES['img'];
if($img['name']==''){
echo('noImage');
}else{
$filename = $img['tmp_name'];
$client_id="myId";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$pvars = array('image' => base64_encode($data));
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$out = curl_exec($curl);
curl_close ($curl);
$pms = json_decode($out,true);
$url=$pms['data']['link'];
if($url!=""){
echo "<h2>Uploaded Without Any Problem</h2>";
echo "<img src='$url'/>";
}else{
echo "<h2>There's a Problem</h2>";
echo $pms['data']['error'];
header("HTTP/1.1 404 Not Found");
}
}
?>
I added echo("noImage") in if($img['name']==''){
The error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/
So if you return a response from your PHP server, the error function won't be triggered. However, you can define a function to handle the error based on the response you send from PHP:
success: function(data){
if (data === "stringIsEmpty") {
triggerError("stringIsEmpty");
} else if (data === "stringEqualsFoo") {
triggerError("stringEqualsFoo");
}
},
And then you can have the error function like this:
function triggerError(error) {
if (error === "stringIsEmpty") {
alert("Your string is empty!");
} else if (error === "stringEqualsFoo") {
alert("Your string is equal to Foo!");
}
}
If you make a request to let's say post.php, you can just return a string:
// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;
Or specifically for the example:
echo "stringIsEmpty";
For more information see: How to return data from PHP to a jQuery ajax call
You can trigger the jQuery error-handler by changing the http response code in php. Any 4xx or 5xx error should work, but best stay in rfc.
PHP:
// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";
jQuery:
[...]
error: function(jqxhr) {
alert(jqxhr.responseText)
}
[...]
The thing is, if your php responds, then it's technically not a error, and must be handled in the success callback.
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(data){
alert('The response is: '+data);
if(data=="empty sting"){
alert("The string is empty");
} else if (data == 'foo') {
alert("The string equals 'foo'");
} else {
alert("It works");
}
},
});
And in your PHP:
if (myString == '') {
echo('empty string');
} else if (myString == 'foo') {
echo('foo');
}
The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...
If you want to control some response of the server you can write this code in the "success" setting.
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response){
if (response == '') {
// Send "stringIsEmpty" error to ajax
} else if (response== 'foo') {
// Send "stringEqualsFoo" error to ajax
}
}
}
});
The PHP could be something like this
if (myString == '') {
echo '';
} else if (myString == 'foo') {
echo 'foo';
}
I've tried the bootstrap Model using jQuery AJAX And PHP with error handling
Javascript File:
// add receipt data
$('#insert_form').on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "includes/user-insert.inc.php",
method: "POST",
data: $('#insert_form').serialize(),
async: true,
beforeSend: function() {
$('#insert').val("Inserting");
},
success: function(data) {
$('#insert_form')[0].reset();
$('#add_reciept').modal('hide');
dataTable.ajax.reload(null, false);
if (data == "No") {
$('#alert-danger').addClass('alert alert-danger');
$('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
$('#alert-danger').fadeIn().show();
setTimeout(function() {
$('#alert-danger').fadeOut("slow");
}, 8000);
} else if (data == "Yes") {
$('#alert-success').html('<strong>Well done!</strong> A Record has been Added.');
$('#alert-success').addClass('alert alert-info');
$('#alert-success').fadeIn().show();
setTimeout(function() {
$('#alert-success').fadeOut("slow");
}, 8000);
}
},
error: function(err) {
$('#alert-danger').addClass('alert alert-danger');
$('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
$('#alert-danger').fadeIn().show();
setTimeout(function() {
$('#alert-danger').fadeOut("slow");
}, 8000);
},
complete: function(data) {
$('#insert').val("Insert");
}
});
});
process.inc.php file:
// check users again or not
$sql = "SELECT * FROM users_acc WHERE U_Email='$U_Email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo 'No';
} else {
$query = "
INSERT INTO users_acc(Firstname, Lastname, U_Email, U_Password, Gender, user_role_id)
VALUES('$Firstname', '$Lastname', '$U_Email', '$U_Password', '$Gender' , '$user_role_id')
";
echo 'Yes';
}
So if your returned string is empty, or it equals "foo", you may think that is an error, but HTTP thinks it is a success, and you need to look for these strings in the "success" function.
I have the following Script;
function FetchNews(user_id,api_token){
$.ajax({
type:'GET',
url: 'http://192.168.**.**/mysite/public/index.php/api/v1/news/'+user_id,
headers: {'X-Auth-Token' : api_token},
dataType:'json',
success: function(data)
{
var comment='';
for(var i = 0; i < data.length; i++) {
comment = data[i];
$('headlines').append('<li><h2>'+ comment.news_headline +'</h2><p><strong>'+ comment.news_content +'</strong></p><p class="ui-li-aside"><strong>'+ comment.created_at +'</strong></p></li>');
}
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert("Not connected. Verify Network.");//show error
} else if (jqXHR.status == 404) {
alert("Requested page not found. [404]");//show error
} else if (jqXHR.status == 500) {
alert("Internal Server Error [500].");//show error
} else if (exception === 'parsererror') {
alert("Requested JSON parse failed.");//show error
} else if (exception === 'timeout') {
alert("Time out error.");//show error
} else if (exception === 'abort') {
alert( "Ajax request aborted.");//show error
} else {
alert("Uncaught Error.\n" + jqXHR.responseText);//show error
}
}
});
}
I call this FetchNews function as the page loads, It is at the bottom of the page close to the </body> tag. The function get called but no responds from server at all, and when I checked LogCat, the requestState(status) get stuck at 1
Change this...
dataType:'json',
To this...
dataType:'jsonp',
dataType: jsonp is for cross-domain requests/different domain than the origin. dataType:json is for same domain-same origin request.
But also...this seems wrong..
$('headlines').append('<li><h2>'+ comment.news_headline +'</h2><p><strong>'+ comment.news_content +'</strong></p><p class="ui-li-aside"><strong>'+ comment.created_at +'</strong></p></li>');
Should maybe be
$('.headlines') or $('#headlines')