0

First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.

I'd have this html:

<form method="post" action="?c=Logo&action=save" id="form">
    <!-- some inputs -->
    <img src="" data-filename="new-logo.png">
    <input type="submit" value="submit">
</form>

Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].

// $_POST['new-logo'] =  $('img').data('filename')
$logo = new Logo($_POST['new-logo']); 
$logo->save();

I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)

SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)

Cellendhyll
  • 63
  • 1
  • 1
  • 11
  • you need to put enctype attribut on form tag ```
    ``` see this https://stackoverflow.com/questions/8659808/how-does-http-file-upload-work and here https://www.w3schools.com/php/php_file_upload.asp
    – TotPeRo Aug 08 '17 at 21:27
  • You should post what you tried, even if it didn't work. Then we at least have a starting point for trying to show you where you went wrong. – Patrick Q Aug 08 '17 at 21:32

4 Answers4

0

You could also make the data array from scratch like this:

$('#form').on('submit', function(e){
    e.preventDefault();

    $.ajax({
       type: "POST",
       url: $(this).attr('action'),
       data: {key1:"value", key2:"value2"},
       dataType: "json",
       success: function(data) {
           //do success stuff here
       },
       error: function() {
           //do error stuff here.
       }
    });
});
catbadger
  • 1,662
  • 2
  • 18
  • 27
0

You can add it as a hidden input.

$("#form").submit(function() {
    $(this).append($("<input>", {
        type: "hidden",
        name: "new-logo",
        value: $(this).find("img").data("filename")
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

you can add this to you're post request like this :

$('#form').on('submit', function(e){
    e.preventDefault();

    var $form = $(this);

    var datastring = $form.serializeArray();
    datastring.push({name:'new-logo', value:$form.find('img').data('filename')});

    $.ajax({
       type: "POST",
       url: $form.attr('action'),
       data: datastring,
       dataType: "json",
       success: function(data) {
           //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
           // do what ever you want with the server response
       },
       error: function() {
           alert('error handing here');
       }
    });
});
yoeunes
  • 2,927
  • 2
  • 15
  • 26
-1
        $logo = new Logo($_POST['new-logo']); 

Is "new Logo" a function or something? Pretty sure that can't have a space.