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
Related
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.
How can I pass data from a query in php and set it's result using an ajax method.
Here is what I have so far in a file called file1.php:
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
I wanna put the contents in this html element in the php file file2.php:
<p id ="resultFromFile1" name = "results">No Results</p>
Many stack overflow posts haven't been any help. Could someone point me in the right direction?
It's wrong approach.
You should rather create php script which will save your ajax request data in let's say database and then in file2.php load this data from DB, not directly update file
First of all what kind of content is query.php returning? Is it a JSON Object or are you just "echoing" the output as a string?
Next Question: Are you using jQuery, AngularJS or something in that direction?
Usually what you want to do is get the information from the "query.php" and pass it as a JSON formatted ajax result...
Now to your actual Problem: You want to get the element called "resultFromFile1" that's inside file2.php but you aren't adding anything to the "visible scope" yet since Load only loads the content but it doesn't add the content to any element you have to define an element holding your "file2.php". If i were you to avoid all these Problems i would use AngularJS for displaying your data in to a view and just include your "result" template via ng-include and let the ajax fill the document..
To solve your Problem:
<script type = "text/javascript">
// Your Solution
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
// My Solution for this problem using native js
// Load the "file2" contents in to the file2Holder element
LoadUrlToElement('file2.php','file2Holder',function(data){
/* When the first loading of file2.php is done, load the results from the query.php and put it in to the element called "resultFromFile1" which we just loaded and placed in to the dom before. But i would recommend you to use AngularJS to avoid this Callback hell and get many cool features that webdevelopers don't want to miss these days.... */
LoadUrlToElement('query.php','resultFromFile1',function(){
alert('Content of resultFromFile1 is => '+document.getElementById('resultFromFile1'));
});
});
function LoadUrlToElement(url,elementID,done) {
$.ajax( { type : 'POST',
data : { },
url : url,
success: function ( data ) {
if(document.getElementById(elementID) === undefined){
alert("Can't proceed cause the content holder"+elementID+" is not found");
return; // Abort here cause there is no container with this id...
}
document.getElementById(elementID).html = data;
if(done !== undefined && typeof done === 'function') done(data);
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<div id="file2Holder"></div>
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.
I'm building a mobile app and i build a PHP API that renders data from a mysql db and encode it as JSON
i call this api with Jquery ajax to get to display the records from the json output as JSONP and render it in my document in the success function.
so far i get the JSON correctly when i do the request via $.ajax and i can see the data in the Response in my firebug but in the other side the ajax function fires the ERROR not the Success.
i have a demo code in here :jsfidle
this is my $.ajax Call:
$(document).on("pageinit","#myPage", function() {
$("#autocomplete").on("listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
var dataString = 'keyword='+value;
if (value.length > 2 ) {
$.mobile.loading("show");
$.ajax({
type: "GET",
url: "http://example.com/search.php",
dataType: "jsonp",
jsonpCallback: 'jsonpCallback',
cache:true,
data: dataString,
success: function(data) {
$.mobile.loading("hide");
alert(data);
}
})
}
});
});
if you check the net panel you 'll find it successful and there is data coming.
Kindly Advise.
Thanks A lot
Your response is not including the callback jsonpCallback() in the response, the response I'm seeing is simply
({"name": ... })
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.