Syntax difficulties in ajax - javascript

I have a function connected with onclick button.
It sends some data through ajax to another php file.
Actually everything was working fine, but I tried to add now to 'success' a simple IF statement, that would get true or false from external file.
I guess some of the syntax may be wrong here because the error message says that my main fuction is not defined.
Could someone find some mistakes here please?
main file (here in success: i have added if else statement only):
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id,
userId: userId},
success:function(data){
if(data.success){
$(".newCommentForm" +id).replaceWith("<span id='" + id + "' class='limitedText'>" + newComment + "</span>");
$(thisId).data("PinComment", newComment);
}
else { alert('error');},
error:function(){
alert('error');
}
});
}
external file (i have added the return arrays here):
public function editComment(){
$userId = Input::get('userId');
if ( $userId == Auth::id() or Auth::user()->hasRole("admin")){
$id = Input::get('id');
$newComment = Input::get('newComment');
DB::update('UPDATE `comments` SET f_text = ? WHERE h_id = ?', array($newComment, $id));
return array('success' => true);
} else {
return array('success' => false);
}
}

You have a typo here else { alert('error');},, you need another closing brace to close the success function.

You are trying to access PHP array in JS that not possible. What you need to do is, either you need to return response as an string or JSON from PHP file
see: Get data from php array - AJAX - jQuery

Get rid of commas. Try this in else block
jAlert('No Success', 'alert box');

Related

AJAX call fails with SyntaxError: Unexpected end of JSON input

Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!
Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..
Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.
Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.
If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.
When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify

Ajax call to submit text into database don't work

I have a page where users can put comments below photos, everything works fine in php, comments go to the database and displayed below the photo.
Now I'm trying to make it work with ajax but I have some troubles.
I have an javascript document with this:
$(document).ready(function(){
$("#btnSubmit").on("click", function(e){
var update = $("#activitymessage").val()
$.ajax({
method: "POST",
url: "./ajax/save_comment.php",
//data: { update: update}, - first version, not correct
data: { activitymessage: update},
datatype: 'json'
})
.done(function(response) {
console.log("ajax done");
console.log (response.message);
var ht = "<li>" + update + "</li>";
$("#listupdates").append(ht);
});
e.preventDefault();
});
});
The php page (save_comment.php) where I tell what to do with the input text:
<?php
spl_autoload_register(function ($class) {
include_once("../classes/" . $class . ".class.php");
});
$activity = new Comment();
if (!empty($_POST['activitymessage'])) {
$activity->Text = $_POST['activitymessage'];
try {
//$activity->idPost = $_GET['nr'];
//$activity->idUser = $_SESSION['user_id'];
// with this it works, but not yet correct
$activity->idPost = 66;
$activity->idUser = 3;
$activity->SavePost();
$response['status'] = 'succes';
$response['message'] = 'Update succesvol';
} catch (Exception $e) {
$error = $e->getMessage();
$response['status'] = "error";
$response['message'] = $feedback;
}
header('Content-type: application/json');
echo json_encode($response);
}
There is also the file Comment.class.php with the 'Comment' class and the function SavePost(). This works without ajax, so I assume the function is correct.
What works
the comment (var update) is printed on the screen into the list.
The console says : "ajax done"
What don't work
The input text don't insert into the database (and disappears when page refresh)
The console says: "undefined" (there must be something wrong with the 'response I use in this function)
I hope you guys can help me out. Thanx
update
I changed the: data: { activitymessage: update} line in the js file, and set manually values for the $activity->idPost = 66; $activity->idUser = 3; And everything works !
Only one thing I want to get fixed
the values of the $_GET['nr'] and $_SESSION['user_id'] are now set manually. Is this possible to get these automatic?
The $_GET['nr'] is the id of the page were the photo is and the comments. In this way I can make a query that returns all comments for this page.
The $_SESSION['user_id'] is the id of the user,so I can echo the username and profile photo.
You are sending data with the key being update not activitymessage
Change data to:
data: { activitymessage: update}
Or change $_POST['activitymessage'] to $_POST['update']
Also you have no $_GET['nr'] in url used for ajax. Nothing shown would help us sort that out but you would need the url to look more like:
url: "./ajax/save_comment.php?nr=" + nrSourceValue,
Not sure why you need to use $_GET['nr'] and don't use $_POST for that also and and nr property to data object being sent

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

Page redirect with successful Ajax request

I have a form that uses Ajax for client-side verification. The end of the form is the following:
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
EDIT: this is my mail3.php file dealing with errors:
$errors=null;
if ( ($name == "Name") ) {
$errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
$errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
$errors .= $spamError; // spam error
}
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
//header ("Location: thankyou.html");
echo "Your message was successfully sent!";
//instead of echoing this message, I want a page redirect to thankyou.html
} else {
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
I was wondering if it's possible to redirect the user to a Thank You page if the ajax request is successful and no errors are present. Is this possible?
Thanks!
Amit
Sure. Just put something at the the end of your success function like:
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
where your server returns the response no_errors when there are no errors present.
Just do some error checking, and if everything passes then set window.location to redirect the user to a different page.
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if ( /*no errors*/ ) {
window.location='thank-you.html'
}
}
});
You can just redirect in your success handler, like this:
window.location.href = "thankyou.php";
Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:
setTimeout(function() {
window.location.href = "thankyou.php";
}, 2000);
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
}
});
In your mail3.php file you should trap errors in a try {} catch {}
try {
/*code here for email*/
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
}
Then in your success call you wont have to worry about your errors, because it will never return as a success.
and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.
I posted the exact situation on a different thread. Re-post.
Excuse me, This is not an answer to the question posted above.
But brings an interesting topic --- WHEN to use AJAX and when NOT to use AJAX. In this case it's good not to use AJAX.
Let's take a simple example of login and password. If the login and/or password does not match it WOULD be nice to use AJAX to report back a simple message saying "Login Incorrect". But if the login and password IS correct, why would I have to callback an AJAX function to redirect to the user page?
In a case like, this I think it would be just nice to use a simple Form SUBMIT. And if the login fails, redirect to Relogin.php which looks same as the Login.php with a GET message in the url like Relogin.php?error=InvalidLogin... something like that...
Just my 2 cents. :)
I think you can do that with:
window.location = "your_url";
I suppose you could attack this in two ways;
1) insert window.location = 'http://www.yourdomain.com into the success function.
2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/
Another option is:
window.location.replace("your_url")

Categories