I am trying to create a node programmatically from the data(JSON) sent by my front-end template.
<input id="title" name="title" type="text" > <input id="body" name="body" type="text"> <input type="file" name="pic" id ="pic1" accept="image/*">
^^ This is my front end html
jQuery(document).ready(function(){ jQuery("#save").click(function(){ //alert("The paragraph was clicked."); var postData = [{ "content-type" : "article", "title": jQuery("#title").val(), "body" : jQuery("#body").val(), "pic1" : jQuery("#pic1").val(), }]; jQuery.ajax({ type: "POST", dataType: "application/json; charset=utf-8", url: "my-module/create-artcle/", //This is the menu hook I created data: {'article': postData}, success:function(data){ //if(data.status === "success"){ alert(data); // window.location = "/user"; //} } }); }); });
^^^ This is my json.
This data is sent to the hook_menu I created, which triggers a callback function to create the node. here is the code for that.
function create_article(){ global $user; if(isset($_POST['article'])) { $json = $_POST['article']; $decodedData = json_decode($json, true); $contentType = $decodedData[0]["content-type"]; $title = $decodedData[0]["title"]; $body= $decodedData[0]["body"]; $image1 = $decodedData[0]["pic1"]; //Create a article $node = new stdClass(); //Set values to fields $node->type = $contentType; $node->title = $title; $node->body[LANGUAGE_NONE][0]['value'] = $body; node_object_prepare($node); $node->language = LANGUAGE_NONE; $node->uid = $user->uid; $node->status = 1; $node = node_submit($node); node_save($node); } }
So far I am getting my code to work except saving the image, because I’m seriously confused in saving an image to my node. The value that I get from front-end is simply the name of the image. my question is : can I save an image to the node I am creating with what I am getting from front-end ? If so I am confused with this reference https://www.drupal.org/node/201594
could any one guide me to extend this code to save my image.. $image1 this variable contains the image name.
Thank you.