WP REST API Post Status Using JavaScript - javascript

I am getting my hands dirty in WP REST API. I have gone through a couple of tutorials and have a question using JavaScript to create a new post.
In this tutorial, the post var status = 'draft'; (see code). So I am just worried that won't anyone able to hack that status?
jQuery( document ).ready( function ( $ ) {
$( '#post-submission-form' ).on( 'submit', function(e) {
e.preventDefault();
var title = $( '#post-submission-title' ).val();
var excerpt = $( '#post-submission-excerpt' ).val();
var content = $( '#post-submission-content' ).val();
var status = 'draft'; // this code
var data = {
title: title,
excerpt: excerpt,
content: content
};
$.ajax({
method: "POST",
url: POST_SUBMITTER.root + 'wp/v2/posts',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
});
} );

Users can always manipulate the data being sent in javascript/jquery requests since it all lives client-side
It is not possible to ensure what data is coming from a client. This passes the burden to the server to validate each incoming request. The only way to guarantee a user doesn't submit a different value than expected would be to handle that server-side. Anything you do client side can be manipulated by anyone visiting your site.

Related

Ajax upload failing but impossible to catch any errors

I use frontend jquery ajax script to send image on to a php backend script hosted by a slim framework app.
The process works for all images except a single one (attached).
The backend is supposed to send back a json object. With that particular image it triggers the 'fail' promise of the jquery ajax upload.
When I log 'errorThrown' I get:
SyntaxError: JSON Parse error: Unrecognized token '<'
It's possible I get this because the returned data is not json but html. Still it is irrational that it does it with one image only. I'm not able to catch any error in the process.
I think the goal here is to know what is the error. If you have a suggestion as a way to find the error in the chain, please advise.
Front end upload script:
$( function() {
let idOfUploadedImage = null
let maxAllowedImages = 5
// Use case: User clicks on the 'Upload your image' button: image is sent to the server.
$( '.imageUploader' ).on( 'click', function( event ) {
event.preventDefault();
// determine which image (field) is currently treated
idOfUploadedImage = event.target.id
let form = $( '.blog-form' );
let formdata = (window.FormData) ? new FormData( form[ 0 ] ) : null;
let data = (formdata !== null) ? formdata : form.serialize();
$.ajax( {
url : '/image-attachment/upload-image',
type : form.attr( 'method' ),
contentType: false, // obligatoire pour de l'upload
processData: false, // obligatoire pour de l'upload
dataType : 'json', // selon le retour attendu
data : data
} ).done( function( response ) {
console.log( `Upload image success: ${idOfUploadedImage}` )
console.log( response )
console.log( numberOfImagesVisibleFieldsOnTheForm )
// Store in corresponding hidden fieldpath of uploaded image as returned from server.
$( `#path-${idOfUploadedImage}` ).val( response.path );
// In case an image was sucessfully uploaded, we make sure the image count that determines
// the number of image container to show stays sync.
numberOfImagesVisibleFieldsOnTheForm++
// Show thumbnail of uploaded file
let field = form.find( `input[name="${idOfUploadedImage}"]` );
let files = field[ 0 ].files;
let image = files[ 0 ];
let $imagePreview = $( `#image-preview-${idOfUploadedImage}` ).show();
$imagePreview.find( 'img' ).attr( 'src', window.URL.createObjectURL( image ) );
// Check if we can still ad images. If so, show next image elements.
if ( numberOfImagesVisibleFieldsOnTheForm > maxAllowedImages ) {
console.log( "You can't add more images" )
} else {
$( `#container-image-${numberOfImagesVisibleFieldsOnTheForm}` ).show()
}
} ).fail( function( xhr, textStatus, errorThrown ) {
console.log( errorThrown );
// Reset field from which image caused the error
resetUploadImageField( idOfUploadedImage )
//if ( response.responseJSON && response.responseJSON.error ) {
// alert( response.responseJSON.error );
//}
} ).always( function() {
console.log( "Upload image process complete" );
} );
} );
} )
Backend script:
namespace Rib\Src\Apps\ImageAttachment\ImageAttachmentControllers;
use Rib\Src\Apps\ImageAttachment\ImageAttachmentModel;
use Slim\Http\Request;
use Slim\Http\Response;
class UploadImage
{
/**
* Use case: user has clicked to upload via ajax a single image from the frontend. This is NOT
* the entire blog post form submission.
* #param Request $request
* #param Response $response
* #return Response
*/
public function upload( Request $request, Response $response )
{
$imageModel = new ImageAttachmentModel();
# Create image in temp dir. Return its information
$tmpImageInfo = $imageModel->uploadImageInTempDir();
# If there are any error with the image (not an image, too big....) treat the error
$error = $tmpImageInfo[ 'error' ] ?? null;
if ( $error ) {
# Inform the frontend with error message
return $response->withJson( $tmpImageInfo, 500 );
}
# Resize image and create its thumbnails in tmp directory
$tmpImageInfo = $imageModel->resizeImageAndCreateThumbnails(
$tmpImageInfo[ 'tmpSaveTargetPlusImageName' ],
$tmpImageInfo[ 'imageNameWithoutExtension' ],
$tmpImageInfo[ 'imageOriginalExtension' ] );
// At this point array $tmpImageInfo = "201703/e-1490022600.jpg"
# We pass back to the frontend the final path of the image which will be in the form of:
# 'yearmonth/filename-random.ext' . Note that currently image is NOT in its final
# destination. It will have to be moved there when user finally posts the full form.
return $response->withJson( $tmpImageInfo );
}
}
Image culprit:
EDIT: The upload WORKS with the image when I grab it back from stackoverflow, but not the original from my computer. I tried rename it and move it locally: it doesn't work.
It was a 'exif_read_data(e-1490024361.jpg): Illegal IFD size'. problem happening on very specific images. I had a global exception handler but I couldn't get the error because post ajax call you can't render anything on the screen. As suggested i was able to get to it from reading the response text in the browser network utilities.
I then excluded treatment of this particular error from my exception and error handlers and script was able to run fine.

Autocomplete Jquery Json

I'm trying to use an external Json as source for the autocomplete Jquery UI plugin : http://jqueryui.com/autocomplete/
This code works fine:
var availableTags = ["aberdeen","aberystwyth","aberystwyth juniors"]
$( "#enter-your-parkrun" ).autocomplete({
open: function(e) {
var results = $.ui.autocomplete.filter(availableTags, e.term);
response(results);
valid = false;
},
select: function(e){
valid = true;
},
close: function(e){
if (!valid) $(this).val('');
},
source: availableTags,
});
$("#enter-your-parkrun").change(function(){
if (availableTags.indexOf($(this).val()) == -1){
$(this).val("");
}
});
but as I have almost 800 values, I need to use an external source. I've tried different things but I can't find a way to make it work:
$( "#enter-your-parkrun" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://tribesports.com/pages/parkrun-event-list",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
delay: 400,
});
I'm not sure what q: request.term should be and if data should be parsed? I also need to add validation to make sure that only the values in the list can be accepted, it works on my first example, not too sure how to transfer this to my second code.
Thanks
request.term is what the user has typed so far, and should be passed to the server as a parameter in the AJAX call so that the server can filter the results.
In the .ajax call, dataType is the kind of data you're expecting back from the server. You have not shown it, but most probably is json, not jsonp. If it's JSON jQuery parses it automatically.
As to sending the term to the server,
if you use the GET method (which is the default), you have to include it in the query string, like this:
url: 'http://tribesports.com/pages/parkrun-event-list?term='+request.term
if you use other method (usually POST) you have to specify the method option in the jquery ajax call options, and also specify the contentType, which shuld be JSON: contentType: "application/json", and send the data in the requiredn format
As you can see this all depends on what's on the server.

check file exists on folder on server using jquery ajax

I am trying to check file exist on server using ajax. i have used below script
my server name is like www.Mydomain.netp/Application_Folder/
var fileobj="../invoices/"+filename+".pdf";
var pdfurl;
$.ajax({
url: fileobj, //or your url
success: function(data){
alert('exists');
pdfurl = "http://Mydomain.orgi/Application_Folder/Invoices/" + Invoiceid + ".pdf";
window.open(pdfurl, "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
},
error: function(data){
alert('does not exists');
pdfurl = "http://AnotherDomain.orgi/Invoices/" + Invoiceid + ".pdf";
window.open(pdfurl, "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
},
});
If file exists that time also i am getting into error part,
any other alternative ways to do this. above script perfect with localhost but not working on production environment
The code snippet you provided seems to use calls from two different domains "Mydomain.orgi" and "AnotherDomain.orgi". You need to check if the another server you are requesting follows CORS. I will suggest console/debug your code And another minor thing that a variable named Invoiceid has been used. Please check if this also resolves well.
As long as the file existence is to be checked and as you have already included jquery on your page, I would just try the following
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
or if I follow the promise pattern I would go for the following:
var jqxhr = $.get( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
For more here

Reading a json response in jquery

i am trying to reading json response from server by using jquery in webpage, this is my json response {"code":0,"message":success"}, and this is my jquery code . this code does not sent data to server and does not read json response from server. please help me to resolve the problem.
$("#myForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
userid=$form.find(input[name="userid"]).val(),
file = $form.find( 'input[name="file"]' ).val(),
filename = $form.find( 'input[name="filename"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { userid: userid,file:file,filename:filename } );
/* Put the results in a div */var obj = jQuery.parseJSON( '{ "code": "0" }' );
$.getJSON(url, { get_param: 'code' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
});
You have syntax error, in the find method quotes is missing :)
userid=$form.find(input[name="userid"]).val(),
cange to
userid=$form.find('input[name="userid"]').val(),
PS: All browser have a javascript console, that show u where is script crashed

Why does JQuery $.post send the first variable with a leading ampersand?

This small snippet of code I'm using is causing issues because the request string is coming through to apache as "delete.php&id={id}&confirm=yes" instead of "delete.php?id={id}&confirm=yes".
if(result) {
var posting = $.post( '/support_ticket/delete.php', {id: tickId, confirm: 'yes'});
posting.done(function( data ) {
var content = $( data ).find( '#main' );
bootbox.alert(content);
});
}
As far as I can recall I've never had this issue before and don't understand why it's doing this.

Categories

Resources